diff --git a/Eratta.txt b/Eratta.txt deleted file mode 100644 index 04cf19c..0000000 --- a/Eratta.txt +++ /dev/null @@ -1,3 +0,0 @@ -05 June 2007 -- Comma on line 233 preventing EJS from working in IE6 (Thanks, Justin from jupiterit.com) -- \ No newline at end of file diff --git a/ProjectHome.md b/ProjectHome.md new file mode 100644 index 0000000..1a45048 --- /dev/null +++ b/ProjectHome.md @@ -0,0 +1,64 @@ +EJS cleans the HTML out of your JavaScript with client side templates. After EJS gets its rubber gloves on dirty code, you'll feel organized and uncluttered. + +| [Home](http://embeddedjs.com/) | [Getting Started Guide](http://embeddedjs.com/getting_started.html) | [NBA Demo ](http://embeddedjs.com/application.html) | [How-to Screencast ](http://embeddedjs.com/screencast/index.html) | +|:--------------------------------|:--------------------------------------------------------------------|:----------------------------------------------------|:------------------------------------------------------------------| + +# Description # + +EJS is essentially a port of Masatoshi Seki's erb.rb in the Ruby Core. It operates in the same way that PHP, ERB, or any of the other embedded language interpreters work, except where all existing preprocessing engines execute on the server-side, EJS is intended to run within the web browser. This allows client-side code to process JavaScript-based web templates for insertion into the current page without consulting the server. + +EJS uses <% %> or [% %] as its magic tags. Like most other frameworks of its type, <% %> tags cause all code within them to be executed, and the addition of an equals sign (<%= %>) causes the enclosed code to be evaluated and the toString representation of the result appended to the document. + + +## Typical Use ## +EJS templates can be loaded within a page or a separate file. Once the EJS template is loaded, it is passed data used to render template. The result of the render is typically used to update HTML on the page. + +### Example ### +With this example, we will create and load a template that displays a list of cleaning supplies. + +First, lets create a template file that iterates through a list of supplies: +``` + + +

Supplies

+ +``` + +Next, we create an object to hold those supplies: +``` +var my_supplies = {supplies: ['mop', 'broom', 'duster']} +``` + +Finally, we load the template, render it with the supply object, and update an HTML element with the results. + +``` +var result = new EJS({url: 'templates/supplies.ejs'}).render(my_supplies); +document.getElementById('supply_list').innerHTML = result +``` + + + +# View Helpers # +EJS includes view helpers to make building repetitive HTML snippets easier. The view helpers are very similar to Ruby on Rails ActionView helpers. + +## Example ## +The following builds a form that adds cleaning supplies. +``` +<%= form_tag('/cleaning/add_supply') %> + <%= input_field_tag('cleaning_supply') %> + <%= submit_tag('Submit') %> +<%= form_tag_end() %> +``` + + +# Error Handling # +Using a special version of JSLint, EJS can provide nice error handling when you are developing your templates. +By including ejs\_fulljslint similar to +``` + +``` +EJS will error with a line number if there is a syntax error. \ No newline at end of file diff --git a/Templates.md b/Templates.md new file mode 100644 index 0000000..bb94c82 --- /dev/null +++ b/Templates.md @@ -0,0 +1,55 @@ +# Introduction # + +EJS provides a lot of flexibility for using JavaScript templates. This article documents EJS's template API. + +EJS is typically used by loading a template and rendering it with data. + +# Loading a template # + +Load a template by creating a new EJS template. Templates are cached by default. + +### Example ### +``` +template = new EJS({url: '/mytemplate.ejs'}) +``` +options is a hash that can include the following attributes: + + * url {string} - loads a template from a file + * text {string} - uses the provided text as the template + * element {string or element} - loads a template from the innerHTML or value of the element. + type {string} (optional) - '<' or '[', default is '<', except for loading a template from an element. + * name {string} (optional) - an optional name that is used for caching. This defaults to the element ID or URL provided. + * cache {boolean} (optional) - defaults to true. True if you want to enable caching of templates, false if otherwise. + + +# Rendering # + +There are 2 ways to render a template. The first method, render, simply returns text. Other method, update, is used to update the inner HTML of an element. + +## render(data) ## +Renders the template with the provided data. +``` + html = new EJS({url: '/template.ejs'}).render(data) +``` + +## update(element, url\_or\_data) ## +Updates an element with the result of the template. + +### options ### +**element** {string or element} - the element you want updated + +**url\_or\_data** - can be one of the following: +> {null} - returns a function that takes an object as its first argument. That object will be used to render the template and update the element. + +> {string} - The string is used as a url to perform an AJAX request. The data returned from the ajax request is used to render the template and update the element. + +> {object} - Data used to render the template and update the element. + +### Examples ### +``` +f = new EJS({url: '/mytemplate.ejs'}).update('my_element') + +new EJS({url: '/mytemplate.ejs'}).update('my_element', '/data.json') + +new EJS({url: '/mytemplate.ejs'}).update('my_element', {supplies: ['mop']}) +``` \ No newline at end of file diff --git a/Testing.md b/Testing.md new file mode 100644 index 0000000..1913312 --- /dev/null +++ b/Testing.md @@ -0,0 +1,22 @@ +# Introduction # + +EJS uses scriptaculous's testing functionality. + + +# Instructions # + +After obtaining the trunk folder from SVN: + 1. open test/index.html + 1. On the left frame, click 'Rendering Test' or 'Templating Test' to test ejs or templates respectively. + +# Tests # + +## Rendering Test ## + +### render with left bracket ### + +Tests with the default delimiters [% %] + +### render with left carrot ### + +Tests with erb-style delimiters <% %> \ No newline at end of file diff --git a/ViewHelpers.md b/ViewHelpers.md new file mode 100644 index 0000000..fdcfc07 --- /dev/null +++ b/ViewHelpers.md @@ -0,0 +1,170 @@ +# Introduction # + +EJS provides view helpers for common tasks. These helpers are very similar to those found in the Ruby On Rails framework. + +| date\_tag | form\_tag | form\_tag\_end | hidden\_field\_tag | input\_field\_tag | +|:----------|:----------|:---------------|:-------------------|:------------------| +| is\_current\_page | link\_to | submit\_link\_to | link\_to\_if | link\_to\_unless | +| link\_to\_unless\_current | password\_field\_tag | select\_tag | single\_tag\_for | start\_tag\_for | +| submit\_tag | tag | tag\_end | text\_area\_tag | text\_tag | +| text\_field\_tag | url\_for | img\_tag | + +# Details # + +### date\_tag(name, value, html\_options) ### +Creates a date tag +``` +date_tag('Installation[date]', new Date(1982, 10,20) ) +``` + + +### form\_tag(action, html\_options) ### +Creates a start form tag. +``` +form_tag('/myaction',{multipart: true}) +``` + + +### end\_form\_tag() ### +Creates a start form tag. +``` +form_tag_end() +``` + + +### hidden\_field\_tag( name, value, html\_options) ### +Creates a hidden field. +``` +hidden_field_tag('something[interesting]', 5) => + + "" +``` + + +### img\_tag ### +Creates an image tag. +``` +img_tag('/some.png', 'something') => "something" +``` + + +### input\_field\_tag ### +Creates an input field tag. +``` +input_field_tag('something[interesting]', 5) => + + "" +``` + + +### is\_current\_page ### +Returns true if the url equals location.href or location.pathname, false if otherwise. +``` +is_current_page('yahoo.com') => false +``` + + +### link\_to ### +Creates a link to another page. +``` +link_to('hello world', '/something/here') => "hello world" +``` + + +### submit\_link\_to ### +Creates a submit button that links to another page. +``` +submit_link_to('holla', '/new/location') => + + "" +``` + + +### link\_to\_if(condition, name, url, html\_options, post, block) ### +Just like link\_to if the condition is true. If condition is false it returns name. + +### link\_to\_unless(condition, name, url, html\_options, block) ### +Just like link\_to if the condition is false. If condition is true it returns name. + +### link\_to\_unless\_current(name, url, html\_options, block) ### +Just like link\_to if the url passed in matches the current pages url. Returns name if otherwise. + +### password\_field\_tag ### +Returns a password field. +``` +password_field_tag('something[interesting]', 5) => + + "" +``` + + +### select\_tag ### +Returns a select tag. +``` +var choices = [ {value: 1, text: 'First Choice' }, + {value: 2, text: 'Second Choice'}, + {value: 3, text: 'Third Choice'} ] +select_tag('mySelectElement', 2, choices) => + + "" +``` + + +### single\_tag\_for ### + +Helper for creating a single tag like
+ +### start\_tag\_for ### + +Helper for creating a beginning tag like
+ +

submit_tag

+Creates a submit tag.
+
submit_tag('Submit') => "<input type=\'submit\' value=\'Submit\' />"
+
+

tag

+ +Creates a general tag.
+
+

tag_end

+ +Creates an end tag like
+ +### text\_area\_tag ### +``` +text_area_tag('task[description]', 'Here is some text.\nA new line.') => + "" +``` + + +### text\_field\_tag ### +``` +text_field_tag('something[interesting]', 5) => + "" +``` + + +### url\_for ### + +returns a string that changes the url. \ No newline at end of file diff --git a/example/demo.html b/example/demo.html deleted file mode 100644 index 062bba8..0000000 --- a/example/demo.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - EJS - Embedded JavaScript - Demo - - - - - - - -

EJS - Embedded JavaScript

-

Demo Page

-

This page is a quickly cobbled together demo of compiling EJS from a DOM source and from a String source. For more information and demos, see EJS on the web.

- -
-

Example 1: Running from the a String

-

Run

-

This example compiles and runs EJS from a String stored in the example.js file included with this project.

-
- -
-

Example 2: Running from the DOM

-

Run

-

This example compiles and runs EJS from the DOM node directly below this sentence.

-
-[% var title = "Items to buy!"; %] -

[%= title %]

- -
-
-
-
-

Compiled Code

- -
-
-
-
-

Compilation Results

-
-
-
-
- - -


-

Copyright © 2007 Edward Benson
edwardbenson.com

- - \ No newline at end of file diff --git a/example/ejs.gif b/example/ejs.gif deleted file mode 100644 index d6e95f5..0000000 Binary files a/example/ejs.gif and /dev/null differ diff --git a/example/example.css b/example/example.css deleted file mode 100644 index 7c6c062..0000000 --- a/example/example.css +++ /dev/null @@ -1,31 +0,0 @@ -div.example, div.output { - min-width: 250px; - min-height: 100px; - border: 1px solid black; - margin: 5px; - padding-top: 0px; -} - -hr { - clear: both; -} - -div.example h3 { - width: 100%; - color: white; - background-color: #000066; - padding: 0px; - margin: 0px; -} - -div.output h3{ - width: 100%; - color: white; - background-color: #006600; - padding: 0px; - margin: 0px; -} - -a img { - border: 0; -} \ No newline at end of file diff --git a/example/example.js b/example/example.js deleted file mode 100644 index 489e6e6..0000000 --- a/example/example.js +++ /dev/null @@ -1,88 +0,0 @@ - -function testUsingText() { - /* - * Some DOM Element on your web page is to be the recipient - * of the processed EJS fragment. This element is assigned - * to *output*. - */ - var output = $('output_results'); - - /* Create some fragment of EJS code. Variables from the - * current scope can be used inside the current EJS code. - */ - var animals = ['sloth', 'bear', 'monkey']; - var ejs = ""; - - /* - * Create a new compiler and pass it a reference to the DOM - * node containing the source. - */ - var compiler = new EjsCompiler(ejs); - - /* - * Call the compile() function - */ - compiler.compile(); - - /* - * View the compiled results - */ - $('output_code').innerHTML = compiler.out.escapeHTML(); - - /* - * Evaluate the compiled EJS code and save the output as - * the string *compiled*. This string contains the result. - */ - var compiled = eval(compiler.out); - - /* - * Set the inner HTML of the output node to the result. - */ - output.innerHTML = compiled; -} - - -function testUsingDOM() { - /* - * Some DOM Element on your web page has EJS source code - * within it. This element is assigned to *source* - * - * Some DOM Element on your web page is to be the recipient - * of the processed EJS fragment. This element is assigned - * to *output*. - * - */ - var source = $('source_code'); - var output = $('output_results'); - - /* - * Create a new compiler and pass it a reference to the DOM - * node containing the source - */ - var compiler = new EjsCompiler(source); - - /* - * Call the compile() function - */ - compiler.compile(); - - /* - * View the compiled results - */ - $('output_code').innerHTML = compiler.out.escapeHTML(); - - /* - * Evaluate the compiled EJS code and save the output as - * the string *compiled*. This string contains the result. - */ - var compiled = eval(compiler.out); - - /* - * Set the inner HTML of the output node to the result. - */ - output.innerHTML = compiled; - - -} diff --git a/lib/ejs_fulljslint.js b/lib/ejs_fulljslint.js deleted file mode 100644 index a1b073d..0000000 --- a/lib/ejs_fulljslint.js +++ /dev/null @@ -1,3774 +0,0 @@ -// jslint.js -// 2007-12-10 -/* -Copyright (c) 2002 Douglas Crockford (www.JSLint.com) - -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 shall be used for Good, not Evil. - -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. -*/ - -/* - JSLINT is a global function. It takes two parameters. - - var myResult = JSLINT(source, option); - - The first parameter is either a string or an array of strings. If it is a - string, it will be split on '\n' or '\r'. If it is an array of strings, it - is assumed that each string represents one line. The source can be a - JavaScript text, or HTML text, or a Konfabulator text. - - The second parameter is an optional object of options which control the - operation of JSLINT. All of the options are booleans. All are optional and - have a default value of false. - - If it checks out, JSLINT returns true. Otherwise, it returns false. - - If false, you can inspect JSLINT.errors to find out the problems. - JSLINT.errors is an array of objects containing these members: - - { - line : The line (relative to 0) at which the lint was found - character : The character (relative to 0) at which the lint was found - reason : The problem - evidence : The text line in which the problem occurred - raw : The raw message before the details were inserted - a : The first detail - b : The second detail - c : The third detail - d : The fourth detail - } - - If a fatal error was found, a null will be the last element of the - JSLINT.errors array. - - You can request a Function Report, which shows all of the functions - and the parameters and vars that they use. This can be used to find - implied global variables and other problems. The report is in HTML and - can be inserted in a . - - var myReport = JSLINT.report(option); - - If the option is true, then the report will be limited to only errors. -*/ - -/*jslint evil: true, nomen: false */ - -/*members "\b", "\t", "\n", "\f", "\r", "\"", "(begin)", "(context)", - "(end)", "(global)", "(identifier)", "(line)", "(name)", "(params)", - "(scope)", "(verb)", ")", "++", "--", "\/", ADSAFE, Array, Boolean, COM, - Canvas, CustomAnimation, Date, Debug, Error, EvalError, FadeAnimation, - Frame, Function, HotKey, Image, Math, MenuItem, MoveAnimation, Number, - Object, Point, RangeError, ReferenceError, RegExp, RotateAnimation, - ScrollBar, String, SyntaxError, Text, TextArea, TypeError, URIError, - URL, Window, XMLDOM, XMLHttpRequest, "\\", "]", a, abbr, "about-box", - "about-image", "about-text", "about-version", acronym, action, address, - adsafe, alert, alignment, anchorstyle, animator, appleScript, applet, - apply, area, author, autohide, b, background, base, bdo, beep, beget, - bgcolor, bgcolour, bgopacity, big, bitwise, block, blockquote, blur, - body, br, browser, button, bytesToUIString, c, call, callee, caller, - canvas, cap, caption, cases, center, charAt, charCodeAt, character, - checked, chooseColor, chooseFile, chooseFolder, cite, clearInterval, - clearTimeout, cliprect, clone, close, closeWidget, closed, code, col, - colgroup, color, colorize, colour, columns, combine, company, condition, - confirm, console, constructor, content, contextmenuitems, - convertPathToHFS, convertPathToPlatform, copyright, d, data, dd, debug, - decodeURI, decodeURIComponent, defaultStatus, defaulttracking, - defaultvalue, defineClass, del, description, deserialize, dfn, dir, - directory, div, dl, doAttribute, doBegin, doIt, doTagName, document, dt, - dynsrc, editable, em, embed, empty, enabled, encodeURI, - encodeURIComponent, entityify, eqeqeq, errors, escape, eval, event, - evidence, evil, exec, exps, extension, fieldset, file, filesystem, - fillmode, flags, floor, focus, focusWidget, font, fontstyle, forin, - form, fragment, frame, frames, frameset, from, fromCharCode, fud, - function, gc, getComputedStyle, group, h1, h2, h3, h4, h5, h6, halign, - handlelinks, hasOwnProperty, head, height, help, hidden, history, - hlinesize, hoffset, hotkey, hr, href, hregistrationpoint, hscrollbar, - hsladjustment, hsltinting, html, i, iTunes, icon, id, identifier, - iframe, image, img, include, indexOf, init, input, ins, interval, - isAlpha, isApplicationRunning, isDigit, isFinite, isNaN, join, kbd, key, - kind, konfabulatorVersion, label, labelled, laxbreak, lbp, led, left, - legend, length, level, li, line, lines, link, load, loadClass, - loadingsrc, location, locked, log, lowsrc, map, match, max, maxlength, - menu, menuitem, message, meta, min, minimumversion, minlength, - missingsrc, modifier, moveBy, moveTo, name, navigator, new, noframes, - nomen, noscript, notsaved, nud, object, ol, on, onblur, onclick, - oncontextmenu, ondragdrop, ondragenter, ondragexit, onerror, - onfirstdisplay, onfocus, ongainfocus, onimageloaded, onkeydown, - onkeypress, onkeyup, onload, onlosefocus, onmousedown, onmousedrag, - onmouseenter, onmouseexit, onmousemove, onmouseup, onmousewheel, - onmulticlick, onresize, onselect, ontextinput, ontimerfired, onunload, - onvaluechanged, opacity, open, openURL, opener, opera, optgroup, option, - optionvalue, order, orientation, p, pagesize, param, parent, parseFloat, - parseInt, passfail, play, plusplus, pop, popupMenu, pre, preference, - preferenceGroups, preferencegroup, preferences, print, prompt, - prototype, push, q, quit, random, raw, reach, readFile, readUrl, reason, - reloadWidget, remoteasync, replace, report, requiredplatform, reserved, - resizeBy, resizeTo, resolvePath, resumeUpdates, rhino, right, root, - rotation, runCommand, runCommandInBg, samp, saveAs, savePreferences, - screen, script, scroll, scrollBy, scrollTo, scrollbar, scrolling, - scrollx, scrolly, seal, search, secure, select, self, serialize, - setInterval, setTimeout, setting, settings, shadow, shift, - showWidgetPreferences, size, skip, sleep, slice, small, sort, source, - span, spawn, speak, special, spellcheck, split, src, srcheight, - srcwidth, status, strong, style, sub, substr, subviews, sup, superview, - supplant, suppressUpdates, sync, system, table, tag, tbody, td, - tellWidget, test, text, textarea, tfoot, th, thead, this, thumbcolor, - ticking, ticklabel, ticks, tileorigin, timer, title, toLowerCase, - toSource, toString, toint32, token, tooltip, top, tr, tracking, trigger, - truncation, tt, type, u, ul, undef, unescape, unwatch, updateNow, url, - usefileicon, valign, value, valueOf, var, version, visible, vlinesize, - voffset, vregistrationpoint, vscrollbar, watch, white, widget, width, - window, wrap, yahooCheckLogin, yahooLogin, yahooLogout, zorder -*/ - -// We build the application inside a function so that we produce only a single -// global variable. The function will be invoked, its return value is the JSLINT -// function itself. - -var JSLINT; -JSLINT = function () { - -// These are words that should not be permitted in third party ads. - - var adsafe = { - apply : true, - call : true, - callee : true, - caller : true, - clone : true, - constructor : true, - 'eval' : true, - 'new' : true, - prototype : true, - source : true, - 'this' : true, - toSource : true, - toString : true, - unwatch : true, - valueOf : true, - watch : true - }, - -// These are all of the JSLint options. - - allOptions = { - adsafe : true, // if use of some browser features should be restricted - bitwise : true, // if bitwise operators should not be allowed - browser : true, // if the standard browser globals should be predefined - cap : true, // if upper case HTML should be allowed - debug : true, // if debugger statements should be allowed - eqeqeq : true, // if === should be required - evil : true, // if eval should be allowed - forin : true, // if for in statements must filter - fragment : true, // if HTML fragments should be allowed - laxbreak : true, // if line breaks should not be checked - nomen : true, // if names should be checked - on : true, // if HTML event handlers should be allowed - passfail : true, // if the scan should stop on first error - plusplus : true, // if increment/decrement should not be allowed - rhino : true, // if the Rhino environment globals should be predefined - undef : true, // if variables should be declared before used - white : true, // if strict whitespace rules apply - widget : true // if the Yahoo Widgets globals should be predefined - }, - - anonname, // The guessed name for anonymous functions. - -// browser contains a set of global names which are commonly provided by a -// web browser environment. - - browser = { - alert : true, - blur : true, - clearInterval : true, - clearTimeout : true, - close : true, - closed : true, - confirm : true, - console : true, - Debug : true, - defaultStatus : true, - document : true, - event : true, - focus : true, - frames : true, - getComputedStyle: true, - history : true, - Image : true, - length : true, - location : true, - moveBy : true, - moveTo : true, - name : true, - navigator : true, - onblur : true, - onerror : true, - onfocus : true, - onload : true, - onresize : true, - onunload : true, - open : true, - opener : true, - opera : true, - parent : true, - print : true, - prompt : true, - resizeBy : true, - resizeTo : true, - screen : true, - scroll : true, - scrollBy : true, - scrollTo : true, - self : true, - setInterval : true, - setTimeout : true, - status : true, - top : true, - window : true, - XMLHttpRequest : true - }, - - escapes = { - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '/' : '\\/', - '\\': '\\\\' - }, - - funct, // The current function - functions, // All of the functions - - href = { - background : true, - content : true, - data : true, - dynsrc : true, - href : true, - lowsrc : true, - value : true, - src : true, - style : true - }, - - global, // The global object - globals, // The current globals - implied, // Implied globals - inblock, - indent, - jsonmode, - lines, - lookahead, - member, - membersOnly, - nexttoken, - noreach, - option, - prereg, - prevtoken, - - rhino = { - defineClass : true, - deserialize : true, - gc : true, - help : true, - load : true, - loadClass : true, - print : true, - quit : true, - readFile : true, - readUrl : true, - runCommand : true, - seal : true, - serialize : true, - spawn : true, - sync : true, - toint32 : true, - version : true - }, - - scope, // The current scope - src, - stack, - -// standard contains the global names that are provided by the -// ECMAScript standard. - - standard = { - Array : true, - Boolean : true, - Date : true, - decodeURI : true, - decodeURIComponent : true, - encodeURI : true, - encodeURIComponent : true, - Error : true, - escape : true, - 'eval' : true, - EvalError : true, - Function : true, - isFinite : true, - isNaN : true, - Math : true, - Number : true, - Object : true, - parseInt : true, - parseFloat : true, - RangeError : true, - ReferenceError : true, - RegExp : true, - String : true, - SyntaxError : true, - TypeError : true, - unescape : true, - URIError : true - }, - - syntax = {}, - token, - warnings, - -// widget contains the global names which are provided to a Yahoo -// (fna Konfabulator) widget. - - widget = { - alert : true, - appleScript : true, - animator : true, - appleScript : true, - beep : true, - bytesToUIString : true, - Canvas : true, - chooseColor : true, - chooseFile : true, - chooseFolder : true, - convertPathToHFS : true, - convertPathToPlatform : true, - closeWidget : true, - COM : true, - CustomAnimation : true, - escape : true, - FadeAnimation : true, - filesystem : true, - focusWidget : true, - form : true, - Frame : true, - HotKey : true, - Image : true, - include : true, - isApplicationRunning : true, - iTunes : true, - konfabulatorVersion : true, - log : true, - MenuItem : true, - MoveAnimation : true, - openURL : true, - play : true, - Point : true, - popupMenu : true, - preferenceGroups : true, - preferences : true, - print : true, - prompt : true, - random : true, - reloadWidget : true, - resolvePath : true, - resumeUpdates : true, - RotateAnimation : true, - runCommand : true, - runCommandInBg : true, - saveAs : true, - savePreferences : true, - screen : true, - ScrollBar : true, - showWidgetPreferences : true, - sleep : true, - speak : true, - suppressUpdates : true, - system : true, - tellWidget : true, - Text : true, - TextArea : true, - unescape : true, - updateNow : true, - URL : true, - widget : true, - Window : true, - XMLDOM : true, - XMLHttpRequest : true, - yahooCheckLogin : true, - yahooLogin : true, - yahooLogout : true - }, - -// xmode is used to adapt to the exceptions in XML parsing. -// It can have these states: -// false .js script file -// " A " attribute -// ' A ' attribute -// content The content of a script tag -// CDATA A CDATA block - - xmode, - -// xtype identifies the type of document being analyzed. -// It can have these states: -// false .js script file -// html .html file -// widget .kon Konfabulator file - - xtype, - -// unsafe comment - ax = /@cc|<\/?script|\]\]|&/i, -// unsafe character - cx = /[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u2028\u2029\ufff0-\uffff]/, -// token - tx = /^\s*([(){}\[.,:;'"~]|\](\]>)?|\?>?|==?=?|\/(\*(global|extern|jslint|member|members)?|=|\/)?|\*[\/=]?|\+[+=]?|-[\-=]?|%[=>]?|&[&=]?|\|[|=]?|>>?>?=?|<([\/=%\?]|\!(\[|--)?|<=?)?|\^=?|\!=?=?|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+([xX][0-9a-fA-F]+|\.[0-9]*)?([eE][+\-]?[0-9]+)?)/, -// star slash - lx = /\*\/|\/\*/, -// identifier - ix = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/, -// javascript url - jx = /(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i, -// url badness - ux = /&|\+|\u00AD|\.\.|\/\*|%[^;]|base64|url|expression|data|mailto/i; - - function object(o) { - function F() {} - F.prototype = o; - return new F(); - } - - object_combine = function (object, o) { - var n; - for (n in o) if (o.hasOwnProperty(n)) { - object[n] = o[n]; - } - }; - - String.prototype.entityify = function () { - return this. - replace(/&/g, '&'). - replace(//g, '>'); - }; - - String.prototype.isAlpha = function () { - return (this >= 'a' && this <= 'z\uffff') || - (this >= 'A' && this <= 'Z\uffff'); - }; - - - String.prototype.isDigit = function () { - return (this >= '0' && this <= '9'); - }; - - - String.prototype.supplant = function (o) { - return this.replace(/\{([^{}]*)\}/g, function (a, b) { - var r = o[b]; - return typeof r === 'string' || typeof r === 'number' ? r : a; - }); - }; - - String.prototype.name = function () { - -// If the string looks like an identifier, then we can return it as is. -// If the string contains no control characters, no quote characters, and no -// backslash characters, then we can simply slap some quotes around it. -// Otherwise we must also replace the offending characters with safe -// sequences. - - - if (ix.test(this)) { - return this; - } - if (/[&<"\/\\\x00-\x1f]/.test(this)) { - return '"' + this.replace(/[&<"\/\\\x00-\x1f]/g, function (a) { - var c = escapes[a]; - if (c) { - return c; - } - c = a.charCodeAt(); - return '\\u00' + - Math.floor(c / 16).toString(16) + - (c % 16).toString(16); - }) + '"'; - } - return '"' + this + '"'; - }; - - - function populateGlobals() { - if (option.adsafe) { - object_combine(globals, {ADSAFE: true}); - } else { - if (option.rhino) { - object_combine(globals, rhino); - } - if (option.browser) { - object_combine(globals, browser); - } - if (option.widget) { - object_combine(globals, widget); - } - } - } - - -// Produce an error warning. - - function quit(m, l, ch) { - throw { - name: 'JSLintError', - line: l, - character: ch, - message: m + " (" + Math.floor((l / lines.length) * 100) + - "% scanned)." - }; - } - - function warning(m, t, a, b, c, d) { - var ch, l, w; - t = t || nexttoken; - if (t.id === '(end)') { - t = token; - } - l = t.line || 0; - ch = t.from || 0; - w = { - id: '(error)', - raw: m, - evidence: lines[l] || '', - line: l, - character: ch, - a: a, - b: b, - c: c, - d: d - }; - w.reason = m.supplant(w); - JSLINT.errors.push(w); - if (option.passfail) { - quit('Stopping. ', l, ch); - } - warnings += 1; - if (warnings === 50) { - quit("Too many errors.", l, ch); - } - return w; - } - - function warningAt(m, l, ch, a, b, c, d) { - return warning(m, { - line: l, - from: ch - }, a, b, c, d); - } - - function error(m, t, a, b, c, d) { - var w = warning(m, t, a, b, c, d); - quit("Stopping, unable to continue.", w.line, w.character); - } - - function errorAt(m, l, ch, a, b, c, d) { - return error(m, { - line: l, - from: ch - }, a, b, c, d); - } - - - -// lexical analysis - - var lex = function () { - var character, from, line, s; - -// Private lex methods - - function nextLine() { - var at; - line += 1; - if (line >= lines.length) { - return false; - } - character = 0; - s = lines[line]; - at = s.search(cx); - if (at >= 0) { - warningAt("Unsafe character.", line, at); - } - return true; - } - -// Produce a token object. The token inherits from a syntax symbol. - - function it(type, value) { - var i, t; - if (type === '(punctuator)' || - (type === '(identifier)' && syntax.hasOwnProperty(value))) { - t = syntax[value]; - -// Mozilla bug workaround. - - if (!t.id) { - t = syntax[type]; - } - } else { - t = syntax[type]; - } - t = object(t); - if (type === '(string)') { - if (jx.test(value)) { - warningAt("Script URL.", line, from); - } - } else if (type === '(identifier)') { - if (option.nomen && value.charAt(0) === '_') { - warningAt("Unexpected '_' in '{a}'.", line, from, value); - } else if (option.adsafe && - (adsafe[value] === true || value.slice(-2) === '__')) { - warning("ADsafe restricted word '{a}'.", - {line: line, from: character}, value); - } - } - t.value = value; - t.line = line; - t.character = character; - t.from = from; - i = t.id; - if (i !== '(endline)') { - prereg = i && - (('(,=:[!&|?{};'.indexOf(i.charAt(i.length - 1)) >= 0) || - i === 'return'); - } - return t; - } - -// Public lex methods - - return { - init: function (source) { - if (typeof source === 'string') { - lines = source. - replace(/\r\n/g, '\n'). - replace(/\r/g, '\n'). - split('\n'); - } else { - lines = source; - } - line = -1; - nextLine(); - from = 0; - }, - -// token -- this is called by advance to get the next token. - - token: function () { - var b, c, captures, d, depth, high, i, l, low, q, t; - - function match(x) { - var r = x.exec(s), r1; - if (r) { - l = r[0].length; - r1 = r[1]; - c = r1.charAt(0); - s = s.substr(l); - character += l; - from = character - r1.length; - return r1; - } - } - - function string(x) { - var c, j, r = ''; - - if (jsonmode && x !== '"') { - warningAt("Strings must use doublequote.", - line, character); - } - - if (xmode === x || xmode === 'string') { - return it('(punctuator)', x); - } - - function esc(n) { - var i = parseInt(s.substr(j + 1, n), 16); - j += n; - if (i >= 32 && i <= 127 && - i !== 34 && i !== 92 && i !== 39) { - warningAt("Unnecessary escapement.", line, character); - } - character += n; - c = String.fromCharCode(i); - } - j = 0; - for (;;) { - while (j >= s.length) { - j = 0; - if (xmode !== 'xml' || !nextLine()) { - errorAt("Unclosed string.", line, from); - } - } - c = s.charAt(j); - if (c === x) { - character += 1; - s = s.substr(j + 1); - return it('(string)', r, x); - } - if (c < ' ') { - if (c === '\n' || c === '\r') { - break; - } - warningAt("Control character in string: {a}.", - line, character + j, s.slice(0, j)); - } else if (c === '<') { - if (option.adsafe && xmode === 'xml') { - warningAt("ADsafe string violation.", - line, character + j); - } else if (s.charAt(j + 1) === '/' && ((xmode && xmode !== 'CDATA') || option.adsafe)) { - warningAt("Expected '<\\/' and instead saw '= 0) { - break; - } - if (!nextLine()) { - errorAt("Unclosed comment.", line, character); - } else { - if (option.adsafe && ax.test(s)) { - warningAt("ADsafe comment violation.", line, character); - } - } - } - character += i + 2; - if (s.substr(i, 1) === '/') { - errorAt("Nested comment.", line, character); - } - s = s.substr(i + 2); - break; - -// /*global /*extern /*members /*jslint */ - - case '/*global': - case '/*extern': - case '/*members': - case '/*member': - case '/*jslint': - case '*/': - return { - value: t, - type: 'special', - line: line, - character: character, - from: from - }; - - case '': - break; -// / - case '/': - if (prereg) { - depth = 0; - captures = 0; - l = 0; - for (;;) { - b = true; - c = s.charAt(l); - l += 1; - switch (c) { - case '': - errorAt("Unclosed regular expression.", line, from); - return; - case '/': - if (depth > 0) { - warningAt("Unescaped '{a}'.", line, from + l, '/'); - } - c = s.substr(0, l - 1); - if (s.charAt(l) === 'g') { - l += 1; - } - if (s.charAt(l) === 'i') { - l += 1; - } - if (s.charAt(l) === 'm') { - l += 1; - } - character += l; - s = s.substr(l); - return it('(regex)', c); - case '\\': - l += 1; - break; - case '(': - depth += 1; - b = false; - if (s.charAt(l) === '?') { - l += 1; - switch (s.charAt(l)) { - case ':': - case '=': - case '!': - l += 1; - break; - default: - warningAt("Expected '{a}' and instead saw '{b}'.", line, from + l, ':', s.charAt(l)); - } - } else { - captures += 1; - } - break; - case ')': - if (depth === 0) { - warningAt("Unescaped '{a}'.", line, from + l, ')'); - } else { - depth -= 1; - } - break; - case ' ': - q = 1; - while (s.charAt(l) === ' ') { - l += 1; - q += 1; - } - if (q > 1) { - warningAt("Spaces are hard to count. Use {{a}}.", line, from + l, q); - } - break; - case '[': - if (s.charAt(l) === '^') { - l += 1; - } - q = false; -klass: for (;;) { - c = s.charAt(l); - l += 1; - switch (c) { - case '[': - case '^': - warningAt("Unescaped '{a}'.", line, from + l, c); - q = true; - break; - case '-': - if (q) { - q = false; - } else { - warningAt("Unescaped '{a}'.", line, from + l, '-'); - q = true; - } - break; - case ']': - if (!q) { - warningAt("Unescaped '{a}'.", line, from + l - 1, '-'); - } - break klass; - case '\\': - l += 1; - q = true; - break; - default: - if (c < ' ') { - errorAt(c ? "Control character in a regular expression" : - "Unclosed regular expression.", line, from + l); - } - q = true; - } - } - break; - case ']': - case '?': - case '{': - case '}': - case '+': - case '*': - warningAt("Unescaped '{a}'.", line, from + l, c); - break; - default: - if (c < ' ') { - warningAt("Control character in a regular expression", line, from + l); - } - } - if (b) { - switch (s.charAt(l)) { - case '?': - case '+': - case '*': - l += 1; - if (s.charAt(l) === '?') { - l += 1; - } - break; - case '{': - l += 1; - c = s.charAt(l); - if (c < '0' || c > '9') { - warningAt("Expected a number and instead saw '{a}'.", line, from + l, c); - } - l += 1; - low = +c; - for (;;) { - c = s.charAt(l); - if (c < '0' || c > '9') { - break; - } - l += 1; - low = +c + (low * 10); - } - high = low; - if (c === ',') { - l += 1; - high = Infinity; - c = s.charAt(l); - if (c >= '0' && c <= '9') { - l += 1; - high = +c; - for (;;) { - c = s.charAt(l); - if (c < '0' || c > '9') { - break; - } - l += 1; - high = +c + (high * 10); - } - } - } - if (s.charAt(l) !== '}') { - warningAt("Expected '{a}' and instead saw '{b}'.", line, from + l, '}', c); - } else { - l += 1; - } - if (s.charAt(l) === '?') { - l += 1; - } - if (low > high) { - warningAt("'{a}' should not be greater than '{b}'.", line, from + l, low, high); - } - } - } - } - c = s.substr(0, l - 1); - character += l; - s = s.substr(l); - return it('(regex)', c); - } - return it('(punctuator)', t); - -// punctuator - - default: - return it('(punctuator)', t); - } - } - }, - -// skip -- skip past the next occurrence of a particular string. -// If the argument is empty, skip to just before the next '<' character. -// This is used to ignore HTML content. Return false if it isn't found. - - skip: function (p) { - var i, t = p; - if (nexttoken.id) { - if (!t) { - t = ''; - if (nexttoken.id.substr(0, 1) === '<') { - lookahead.push(nexttoken); - return true; - } - } else if (nexttoken.id.indexOf(t) >= 0) { - return true; - } - } - token = nexttoken; - nexttoken = syntax['(end)']; - for (;;) { - i = s.indexOf(t || '<'); - if (i >= 0) { - character += i + t.length; - s = s.substr(i + t.length); - return true; - } - if (!nextLine()) { - break; - } - } - return false; - } - }; - }(); - - - function addlabel(t, type) { - - if (t === 'hasOwnProperty') { - error("'hasOwnProperty' is a really bad name."); - } - if (option.adsafe && scope === global) { - warning('ADsafe global: ' + t + '.', token); - } - -// Define t in the current function in the current scope. - - if (funct.hasOwnProperty(t)) { - warning(funct[t] === true ? - "'{a}' was used before it was defined." : - "'{a}' is already defined.", - nexttoken, t); - } - scope[t] = funct; - funct[t] = type; - if (funct['(global)'] && implied.hasOwnProperty(t)) { - warning("'{a}' was used before it was defined.", - nexttoken, t); - delete implied[t]; - } - } - - - function doOption() { - var b, obj, filter, o = nexttoken.value, t, v; - switch (o) { - case '*/': - error("Unbegun comment."); - break; - case '/*global': - case '/*extern': - if (option.adsafe) { - warning("ADsafe restriction."); - } - obj = globals; - break; - case '/*members': - case '/*member': - o = '/*members'; - if (!membersOnly) { - membersOnly = {}; - } - obj = membersOnly; - break; - case '/*jslint': - if (option.adsafe) { - warning("ADsafe restriction."); - } - obj = option; - filter = allOptions; - } - for (;;) { - t = lex.token(); - if (t.id === ',') { - t = lex.token(); - } - while (t.id === '(endline)') { - t = lex.token(); - } - if (t.type === 'special' && t.value === '*/') { - break; - } - if (t.type !== '(string)' && t.type !== '(identifier)' && - o !== '/*members') { - error("Bad option.", t); - } - if (filter) { - if (filter[t.value] !== true) { - error("Bad option.", t); - } - v = lex.token(); - if (v.id !== ':') { - error("Expected '{a}' and instead saw '{b}'.", - t, ':', t.value); - } - v = lex.token(); - if (v.value === 'true') { - b = true; - } else if (v.value === 'false') { - b = false; - } else { - error("Expected '{a}' and instead saw '{b}'.", - t, 'true', t.value); - } - } else { - b = true; - } - obj[t.value] = b; - } - if (filter) { - populateGlobals(); - } - } - - -// We need a peek function. If it has an argument, it peeks that much farther -// ahead. It is used to distinguish -// for ( var i in ... -// from -// for ( var i = ... - - function peek(p) { - var i = p || 0, j = 0, t; - - while (j <= i) { - t = lookahead[j]; - if (!t) { - t = lookahead[j] = lex.token(); - } - j += 1; - } - return t; - } - - - var badbreak = { - ')': true, - ']': true, - '++': true, - '--': true - }; - -// Produce the next token. It looks for programming errors. - - function advance(id, t) { - var l; - switch (token.id) { - case '(number)': - if (nexttoken.id === '.') { - warning( -"A dot following a number can be confused with a decimal point.", token); - } - break; - case '-': - if (nexttoken.id === '-' || nexttoken.id === '--') { - warning("Confusing minusses."); - } - break; - case '+': - if (nexttoken.id === '+' || nexttoken.id === '++') { - warning("Confusing plusses."); - } - break; - } - if (token.type === '(string)' || token.identifier) { - anonname = token.value; - } - - if (id && nexttoken.id !== id) { - if (t) { - if (nexttoken.id === '(end)') { - warning("Unmatched '{a}'.", t, t.id); - } else { - warning("Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.", - nexttoken, id, t.id, t.line + 1, nexttoken.value); - } - } else { - warning("Expected '{a}' and instead saw '{b}'.", - nexttoken, id, nexttoken.value); - } - } - prevtoken = token; - token = nexttoken; - for (;;) { - nexttoken = lookahead.shift() || lex.token(); - if (nexttoken.type === 'special') { - doOption(); - } else { - if (nexttoken.id === ''); - } else { - error("Unexpected '{a}'.", nexttoken, '') { - if (xmode === 'CDATA') { - xmode = 'script'; - } else { - error("Unexpected '{a}'.", nexttoken, ']]>'); - } - } else if (nexttoken.id !== '(endline)') { - break; - } - if (xmode === '"' || xmode === "'") { - error("Missing '{a}'.", token, xmode); - } - l = !xmode && !option.laxbreak && - (token.type === '(string)' || token.type === '(number)' || - token.type === '(identifier)' || badbreak[token.id]); - } - } - if (l) { - switch (nexttoken.id) { - case '{': - case '}': - case ']': - break; - case ')': - switch (token.id) { - case ')': - case '}': - case ']': - break; - default: - warning("Line breaking error '{a}'.", token, ')'); - } - break; - default: - warning("Line breaking error '{a}'.", - token, token.value); - } - } - if (xtype === 'widget' && xmode === 'script' && nexttoken.id) { - l = nexttoken.id.charAt(0); - if (l === '<' || l === '&') { - nexttoken.nud = nexttoken.led = null; - nexttoken.lbp = 0; - nexttoken.reach = true; - } - } - } - - -// This is the heart of JSLINT, the Pratt parser. In addition to parsing, it -// is looking for ad hoc lint patterns. We add to Pratt's model .fud, which is -// like nud except that it is only used on the first token of a statement. -// Having .fud makes it much easier to define JavaScript. I retained Pratt's -// nomenclature. - -// .nud Null denotation -// .fud First null denotation -// .led Left denotation -// lbp Left binding power -// rbp Right binding power - -// They are key to the parsing method called Top Down Operator Precedence. - - function parse(rbp, initial) { - var left; - var o; - if (nexttoken.id === '(end)') { - error("Unexpected early end of program.", token); - } - advance(); - if (option.adsafe && token.value === 'ADSAFE') { - if (nexttoken.id !== '.' || !(peek(0).identifier) || - peek(1).id !== '(') { - warning('ADsafe violation.', token); - } - } - if (initial) { - anonname = 'anonymous'; - funct['(verb)'] = token.value; - } - if (initial && token.fud) { - left = token.fud(); - } else { - if (token.nud) { - o = token.exps; - left = token.nud(); - } else { - if (nexttoken.type === '(number)' && token.id === '.') { - warning( -"A leading decimal point can be confused with a dot: '.{a}'.", - token, nexttoken.value); - advance(); - return token; - } else { - error("Expected an identifier and instead saw '{a}'.", - token, token.id); - } - } - while (rbp < nexttoken.lbp) { - o = nexttoken.exps; - advance(); - if (token.led) { - left = token.led(left); - } else { - error("Expected an operator and instead saw '{a}'.", - token, token.id); - } - } - if (initial && !o) { - warning( -"Expected an assignment or function call and instead saw an expression.", - token); - } - } - if (!option.evil && left && left.value === 'eval') { - warning("eval is evil.", left); - } - return left; - } - - -// Functions for conformance of style. - - function adjacent(left, right) { - left = left || token; - right = right || nexttoken; - if (option.white) { - if (left.character !== right.from) { - warning("Unexpected space after '{a}'.", - nexttoken, left.value); - } - } - } - - - function nospace(left, right) { - left = left || token; - right = right || nexttoken; - if (option.white) { - if (left.line === right.line) { - adjacent(left, right); - } - } - } - - - function nonadjacent(left, right) { - left = left || token; - right = right || nexttoken; - if (option.white) { - if (left.character === right.from) { - warning("Missing space after '{a}'.", - nexttoken, left.value); - } - } - } - - function indentation(bias) { - var i; - if (option.white && nexttoken.id !== '(end)') { - i = indent + (bias || 0); - if (nexttoken.from !== i) { - warning("Expected '{a}' to have an indentation of {b} instead of {c}.", - nexttoken, nexttoken.value, i, nexttoken.from); - } - } - } - - function nolinebreak(t) { - if (t.line !== nexttoken.line) { - warning("Line breaking error '{a}'.", t, t.id); - } - } - - -// Parasitic constructors for making the symbols that will be inherited by -// tokens. - - function symbol(s, p) { - var x = syntax[s]; - if (!x || typeof x !== 'object') { - syntax[s] = x = { - id: s, - lbp: p, - value: s - }; - } - return x; - } - - - function delim(s) { - return symbol(s, 0); - } - - - function stmt(s, f) { - var x = delim(s); - x.identifier = x.reserved = true; - x.fud = f; - return x; - } - - - function blockstmt(s, f) { - var x = stmt(s, f); - x.block = true; - return x; - } - - - function reserveName(x) { - var c = x.id.charAt(0); - if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { - x.identifier = x.reserved = true; - } - return x; - } - - - function prefix(s, f) { - var x = symbol(s, 150); - reserveName(x); - x.nud = (typeof f === 'function') ? f : function () { - if (option.plusplus && (this.id === '++' || this.id === '--')) { - warning("Unexpected use of '{a}'.", this, this.id); - } - parse(150); - return this; - }; - return x; - } - - - function type(s, f) { - var x = delim(s); - x.type = s; - x.nud = f; - return x; - } - - - function reserve(s, f) { - var x = type(s, f); - x.identifier = x.reserved = true; - return x; - } - - - function reservevar(s) { - return reserve(s, function () { - return this; - }); - } - - - function infix(s, f, p) { - var x = symbol(s, p); - reserveName(x); - x.led = (typeof f === 'function') ? f : function (left) { - nonadjacent(prevtoken, token); - nonadjacent(token, nexttoken); - return [this.id, left, parse(p)]; - }; - return x; - } - - - function relation(s, f) { - var x = symbol(s, 100); - x.led = function (left) { - nonadjacent(prevtoken, token); - nonadjacent(token, nexttoken); - var right = parse(100); - if ((left && left.id === 'NaN') || (right && right.id === 'NaN')) { - warning("Use the isNaN function to compare with NaN.", this); - } else if (f) { - f.apply(this, [left, right]); - } - return [this.id, left, right]; - }; - return x; - } - - - function isPoorRelation(node) { - return (node.type === '(number)' && !+node.value) || - (node.type === '(string)' && !node.value) || - node.type === 'true' || - node.type === 'false' || - node.type === 'undefined' || - node.type === 'null'; - } - - - function assignop(s, f) { - symbol(s, 20).exps = true; - return infix(s, function (left) { - var l; - nonadjacent(prevtoken, token); - nonadjacent(token, nexttoken); - if (adsafe) { - l = left; - do { - if (l.value === 'ADSAFE') { - warning('ADsafe violation.', l); - } - l = l.left; - } while (l); - } - if (left) { - if (left.id === '.' || left.id === '[' || - (left.identifier && !left.reserved)) { - parse(19); - return left; - } - if (left === syntax['function']) { - warning( -"Expected an identifier in an assignment and instead saw a function invocation.", - token); - } - } - error("Bad assignment.", this); - }, 20); - } - - function bitwise(s, f, p) { - var x = symbol(s, p); - reserveName(x); - x.led = (typeof f === 'function') ? f : function (left) { - if (option.bitwise) { - warning("Unexpected use of '{a}'.", this, this.id); - } - nonadjacent(prevtoken, token); - nonadjacent(token, nexttoken); - return [this.id, left, parse(p)]; - }; - return x; - } - - function bitwiseassignop(s) { - symbol(s, 20).exps = true; - return infix(s, function (left) { - if (option.bitwise) { - warning("Unexpected use of '{a}'.", this, this.id); - } - nonadjacent(prevtoken, token); - nonadjacent(token, nexttoken); - if (left) { - if (left.id === '.' || left.id === '[' || - (left.identifier && !left.reserved)) { - parse(19); - return left; - } - if (left === syntax['function']) { - warning( -"Expected an identifier in an assignment, and instead saw a function invocation.", - token); - } - } - error("Bad assignment.", this); - }, 20); - } - - - function suffix(s, f) { - var x = symbol(s, 150); - x.led = function (left) { - if (option.plusplus) { - warning("Unexpected use of '{a}'.", this, this.id); - } - return [f, left]; - }; - return x; - } - - - function optionalidentifier() { - if (nexttoken.reserved) { - warning("Expected an identifier and instead saw '{a}' (a reserved word).", - nexttoken, nexttoken.id); - } - if (nexttoken.identifier) { - advance(); - return token.value; - } - } - - - function identifier() { - var i = optionalidentifier(); - if (i) { - return i; - } - if (token.id === 'function' && nexttoken.id === '(') { - warning("Missing name in function statement."); - } else { - error("Expected an identifier and instead saw '{a}'.", - nexttoken, nexttoken.value); - } - } - - function reachable(s) { - var i = 0, t; - if (nexttoken.id !== ';' || noreach) { - return; - } - for (;;) { - t = peek(i); - if (t.reach) { - return; - } - if (t.id !== '(endline)') { - if (t.id === 'function') { - warning( -"Inner functions should be listed at the top of the outer function.", t); - break; - } - warning("Unreachable '{a}' after '{b}'.", t, t.value, s); - break; - } - i += 1; - } - } - - - function statement(noindent) { - var i = indent, r, s = scope, t = nexttoken; - -// We don't like the empty statement. - - if (t.id === ';') { - warning("Unnecessary semicolon.", t); - advance(';'); - return; - } - -// Is this a labelled statement? - - if (t.identifier && !t.reserved && peek().id === ':') { - advance(); - advance(':'); - scope = object(s); - addlabel(t.value, 'label'); - if (!nexttoken.labelled) { - warning("Label '{a}' on {b} statement.", - nexttoken, t.value, nexttoken.value); - } - if (jx.test(t.value + ':')) { - warning("Label '{a}' looks like a javascript url.", - t, t.value); - } - nexttoken.label = t.value; - t = nexttoken; - } - -// Parse the statement. - - if (!noindent) { - indentation(); - } - r = parse(0, true); - -// Look for the final semicolon. - - if (!t.block) { - if (nexttoken.id !== ';') { - warningAt("Missing semicolon.", token.line, - token.from + token.value.length); - } else { - adjacent(token, nexttoken); - advance(';'); - nonadjacent(token, nexttoken); - } - } - -// Restore the indentation. - - indent = i; - scope = s; - return r; - } - - - function statements() { - var a = []; - while (!nexttoken.reach && nexttoken.id !== '(end)') { - if (nexttoken.id === ';') { - warning("Unnecessary semicolon."); - advance(';'); - } else { - a.push(statement()); - } - } - return a; - } - - - function block(f) { - var a, b = inblock, s = scope; - inblock = f; - if (f) { - scope = object(scope); - } - nonadjacent(token, nexttoken); - var t = nexttoken; - if (nexttoken.id === '{') { - advance('{'); - if (nexttoken.id !== '}' || token.line !== nexttoken.line) { - indent += 4; - if (!f && nexttoken.from === indent + 4) { - indent += 4; - } - a = statements(); - indent -= 4; - indentation(); - } - advance('}', t); - } else { - warning("Expected '{a}' and instead saw '{b}'.", - nexttoken, '{', nexttoken.value); - noreach = true; - a = [statement()]; - noreach = false; - } - funct['(verb)'] = null; - scope = s; - inblock = b; - return a; - } - - -// An identity function, used by string and number tokens. - - function idValue() { - return this; - } - - - function countMember(m) { - if (membersOnly && membersOnly[m] !== true) { - warning("Unexpected /*member '{a}'.", nexttoken, m); - } - if (typeof member[m] === 'number') { - member[m] += 1; - } else { - member[m] = 1; - } - } - - function note_implied(token) { - var name = token.value, line = token.line + 1, a = implied[name]; - if (!a) { - a = [line]; - implied[name] = a; - } else if (a[a.length - 1] !== line) { - a.push(line); - } - } - - -// XML types. Currently we support html and widget. - - var xmltype = { - html: { - doBegin: function (n) { - xtype = 'html'; - option.browser = true; - populateGlobals(); - }, - doTagName: function (n, p) { - var i, t = xmltype.html.tag[n], x; - src = false; - if (!t) { - error("Unrecognized tag '<{a}>'.", - nexttoken, - n === n.toLowerCase() ? n : - n + ' (capitalization error)'); - } - x = t.parent; - if (!option.fragment || stack.length !== 1 || !stack[0].fragment) { - if (x) { - if (x.indexOf(' ' + p + ' ') < 0) { - error("A '<{a}>' must be within '<{b}>'.", - token, n, x); - } - } else { - i = stack.length; - do { - if (i <= 0) { - error("A '<{a}>' must be within '<{b}>'.", - token, n, 'body'); - } - i -= 1; - } while (stack[i].name !== 'body'); - } - } - return t.empty; - }, - doAttribute: function (n, a) { - if (!a) { - warning("Missing attribute name.", token); - } - a = a.toLowerCase(); - if (n === 'script') { - if (a === 'src') { - src = true; - return 'href'; - } else if (a === 'language') { - warning("The 'language' attribute is deprecated.", - token); - return false; - } - } else if (n === 'style') { - if (a === 'type' && option.adsafe) { - warning("Don't bother with 'type'.", token); - } - } - if (href[a] === true) { - return 'href'; - } - if (a.slice(0, 2) === 'on') { - if (!option.on) { - warning("Avoid HTML event handlers."); - } - return 'script'; - } else { - return 'value'; - } - }, - doIt: function (n) { - return n === 'script' ? 'script' : n !== 'html' && - xmltype.html.tag[n].special && 'special'; - }, - tag: { - a: {}, - abbr: {}, - acronym: {}, - address: {}, - applet: {}, - area: {empty: true, parent: ' map '}, - b: {}, - base: {empty: true, parent: ' head '}, - bdo: {}, - big: {}, - blockquote: {}, - body: {parent: ' html noframes '}, - br: {empty: true}, - button: {}, - canvas: {parent: ' body p div th td '}, - caption: {parent: ' table '}, - center: {}, - cite: {}, - code: {}, - col: {empty: true, parent: ' table colgroup '}, - colgroup: {parent: ' table '}, - dd: {parent: ' dl '}, - del: {}, - dfn: {}, - dir: {}, - div: {}, - dl: {}, - dt: {parent: ' dl '}, - em: {}, - embed: {}, - fieldset: {}, - font: {}, - form: {}, - frame: {empty: true, parent: ' frameset '}, - frameset: {parent: ' html frameset '}, - h1: {}, - h2: {}, - h3: {}, - h4: {}, - h5: {}, - h6: {}, - head: {parent: ' html '}, - html: {}, - hr: {empty: true}, - i: {}, - iframe: {}, - img: {empty: true}, - input: {empty: true}, - ins: {}, - kbd: {}, - label: {}, - legend: {parent: ' fieldset '}, - li: {parent: ' dir menu ol ul '}, - link: {empty: true, parent: ' head '}, - map: {}, - menu: {}, - meta: {empty: true, parent: ' head noframes noscript '}, - noframes: {parent: ' html body '}, - noscript: {parent: ' head html noframes '}, - object: {}, - ol: {}, - optgroup: {parent: ' select '}, - option: {parent: ' optgroup select '}, - p: {}, - param: {empty: true, parent: ' applet object '}, - pre: {}, - q: {}, - samp: {}, - script: {parent: ' body div frame head iframe p pre span '}, - select: {}, - small: {}, - span: {}, - strong: {}, - style: {parent: ' head ', special: true}, - sub: {}, - sup: {}, - table: {}, - tbody: {parent: ' table '}, - td: {parent: ' tr '}, - textarea: {}, - tfoot: {parent: ' table '}, - th: {parent: ' tr '}, - thead: {parent: ' table '}, - title: {parent: ' head '}, - tr: {parent: ' table tbody thead tfoot '}, - tt: {}, - u: {}, - ul: {}, - 'var': {} - } - }, - widget: { - doBegin: function (n) { - xtype = 'widget'; - option.widget = true; - option.cap = true; - populateGlobals(); - }, - doTagName: function (n, p) { - var t = xmltype.widget.tag[n]; - if (!t) { - error("Unrecognized tag '<{a}>'.", nexttoken, n); - } - var x = t.parent; - if (x.indexOf(' ' + p + ' ') < 0) { - error("A '<{a}>' must be within '<{b}>'.", - token, n, x); - } - }, - doAttribute: function (n, a) { - var t = xmltype.widget.tag[a]; - if (!t) { - error("Unrecognized attribute '<{a} {b}>'.", nexttoken, n, a); - } - var x = t.parent; - if (x.indexOf(' ' + n + ' ') < 0) { - error("Attribute '{a}' does not belong in '<{b}>'.", nexttoken, a, n); - } - return t.script ? - 'script' : - a === 'name' && n !== 'setting' ? - 'define' : 'string'; - }, - doIt: function (n) { - var x = xmltype.widget.tag[n]; - return x && x.script && 'script'; - }, - tag: { - "about-box": {parent: ' widget '}, - "about-image": {parent: ' about-box '}, - "about-text": {parent: ' about-box '}, - "about-version": {parent: ' about-box '}, - action: {parent: ' widget ', script: true}, - alignment: {parent: ' canvas frame image scrollbar text textarea window '}, - anchorstyle: {parent: ' text '}, - author: {parent: ' widget '}, - autohide: {parent: ' scrollbar '}, - beget: {parent: ' canvas frame image scrollbar text window '}, - bgcolor: {parent: ' text textarea '}, - bgcolour: {parent: ' text textarea '}, - bgopacity: {parent: ' text textarea '}, - canvas: {parent: ' frame window '}, - charset: {parent: ' script '}, - checked: {parent: ' image menuitem '}, - cliprect: {parent: ' image '}, - color: {parent: ' about-text about-version shadow text textarea '}, - colorize: {parent: ' image '}, - colour: {parent: ' about-text about-version shadow text textarea '}, - columns: {parent: ' textarea '}, - company: {parent: ' widget '}, - contextmenuitems: {parent: ' canvas frame image scrollbar text textarea window '}, - copyright: {parent: ' widget '}, - data: {parent: ' about-text about-version text textarea '}, - debug: {parent: ' widget '}, - defaultvalue: {parent: ' preference '}, - defaulttracking: {parent: ' widget '}, - description: {parent: ' preference '}, - directory: {parent: ' preference '}, - editable: {parent: ' textarea '}, - enabled: {parent: ' menuitem '}, - extension: {parent: ' preference '}, - file: {parent: ' action preference '}, - fillmode: {parent: ' image '}, - font: {parent: ' about-text about-version text textarea '}, - fontstyle: {parent: ' textarea '}, - frame: {parent: ' frame window '}, - group: {parent: ' preference '}, - halign: {parent: ' canvas frame image scrollbar text textarea '}, - handlelinks: {parent: ' textarea '}, - height: {parent: ' canvas frame image scrollbar text textarea window '}, - hidden: {parent: ' preference '}, - hlinesize: {parent: ' frame '}, - hoffset: {parent: ' about-text about-version canvas frame image scrollbar shadow text textarea window '}, - hotkey: {parent: ' widget '}, - hregistrationpoint: {parent: ' canvas frame image scrollbar text '}, - hscrollbar: {parent: ' frame '}, - hsladjustment: {parent: ' image '}, - hsltinting: {parent: ' image '}, - icon: {parent: ' preferencegroup '}, - id: {parent: ' canvas frame hotkey image preference text textarea timer scrollbar widget window '}, - image: {parent: ' about-box frame window widget '}, - interval: {parent: ' action timer '}, - key: {parent: ' hotkey '}, - kind: {parent: ' preference '}, - level: {parent: ' window '}, - lines: {parent: ' textarea '}, - loadingsrc: {parent: ' image '}, - locked: {parent: ' window '}, - max: {parent: ' scrollbar '}, - maxlength: {parent: ' preference '}, - menuitem: {parent: ' contextmenuitems '}, - min: {parent: ' scrollbar '}, - minimumversion: {parent: ' widget '}, - minlength: {parent: ' preference '}, - missingsrc: {parent: ' image '}, - modifier: {parent: ' hotkey '}, - name: {parent: ' canvas frame hotkey image preference preferencegroup scrollbar setting text textarea timer widget window '}, - notsaved: {parent: ' preference '}, - onclick: {parent: ' canvas frame image scrollbar text textarea ', script: true}, - oncontextmenu: {parent: ' canvas frame image scrollbar text textarea window ', script: true}, - ondragdrop: {parent: ' canvas frame image scrollbar text textarea ', script: true}, - ondragenter: {parent: ' canvas frame image scrollbar text textarea ', script: true}, - ondragexit: {parent: ' canvas frame image scrollbar text textarea ', script: true}, - onfirstdisplay: {parent: ' window ', script: true}, - ongainfocus: {parent: ' textarea window ', script: true}, - onkeydown: {parent: ' hotkey text textarea window ', script: true}, - onkeypress: {parent: ' textarea window ', script: true}, - onkeyup: {parent: ' hotkey text textarea window ', script: true}, - onimageloaded: {parent: ' image ', script: true}, - onlosefocus: {parent: ' textarea window ', script: true}, - onmousedown: {parent: ' canvas frame image scrollbar text textarea window ', script: true}, - onmousedrag: {parent: ' canvas frame image scrollbar text textarea window ', script: true}, - onmouseenter: {parent: ' canvas frame image scrollbar text textarea window ', script: true}, - onmouseexit: {parent: ' canvas frame image scrollbar text textarea window ', script: true}, - onmousemove: {parent: ' canvas frame image scrollbar text textarea window ', script: true}, - onmouseup: {parent: ' canvas frame image scrollbar text textarea window ', script: true}, - onmousewheel: {parent: ' frame ', script: true}, - onmulticlick: {parent: ' canvas frame image scrollbar text textarea window ', script: true}, - onselect: {parent: ' menuitem ', script: true}, - ontextinput: {parent: ' window ', script: true}, - ontimerfired: {parent: ' timer ', script: true}, - onvaluechanged: {parent: ' scrollbar ', script: true}, - opacity: {parent: ' canvas frame image scrollbar shadow text textarea window '}, - option: {parent: ' preference widget '}, - optionvalue: {parent: ' preference '}, - order: {parent: ' preferencegroup '}, - orientation: {parent: ' scrollbar '}, - pagesize: {parent: ' scrollbar '}, - preference: {parent: ' widget '}, - preferencegroup: {parent: ' widget '}, - remoteasync: {parent: ' image '}, - requiredplatform: {parent: ' widget '}, - root: {parent: ' window '}, - rotation: {parent: ' canvas frame image scrollbar text '}, - script: {parent: ' widget ', script: true}, - scrollbar: {parent: ' frame text textarea window '}, - scrolling: {parent: ' text '}, - scrollx: {parent: ' frame '}, - scrolly: {parent: ' frame '}, - secure: {parent: ' preference textarea '}, - setting: {parent: ' settings '}, - settings: {parent: ' widget '}, - shadow: {parent: ' about-text about-version text window '}, - size: {parent: ' about-text about-version text textarea '}, - spellcheck: {parent: ' textarea '}, - src: {parent: ' image script '}, - srcheight: {parent: ' image '}, - srcwidth: {parent: ' image '}, - style: {parent: ' about-text about-version canvas frame image preference scrollbar text textarea window '}, - subviews: {parent: ' frame '}, - superview: {parent: ' canvas frame image scrollbar text textarea '}, - text: {parent: ' frame text textarea window '}, - textarea: {parent: ' frame window '}, - timer: {parent: ' widget '}, - thumbcolor: {parent: ' scrollbar textarea '}, - ticking: {parent: ' timer '}, - ticks: {parent: ' preference '}, - ticklabel: {parent: ' preference '}, - tileorigin: {parent: ' image '}, - title: {parent: ' menuitem preference preferencegroup window '}, - tooltip: {parent: ' frame image text textarea '}, - tracking: {parent: ' canvas image '}, - trigger: {parent: ' action '}, - truncation: {parent: ' text '}, - type: {parent: ' preference '}, - url: {parent: ' about-box about-text about-version '}, - usefileicon: {parent: ' image '}, - valign: {parent: ' canvas frame image scrollbar text textarea '}, - value: {parent: ' preference scrollbar setting '}, - version: {parent: ' widget '}, - visible: {parent: ' canvas frame image scrollbar text textarea window '}, - vlinesize: {parent: ' frame '}, - voffset: {parent: ' about-text about-version canvas frame image scrollbar shadow text textarea window '}, - vregistrationpoint: {parent: ' canvas frame image scrollbar text '}, - vscrollbar: {parent: ' frame '}, - width: {parent: ' canvas frame image scrollbar text textarea window '}, - window: {parent: ' canvas frame image scrollbar text textarea widget '}, - wrap: {parent: ' text '}, - zorder: {parent: ' canvas frame image scrollbar text textarea window '} - } - } - }; - - function xmlword(tag) { - var w = nexttoken.value; - if (!nexttoken.identifier) { - if (nexttoken.id === '<') { - if (tag) { - error("Expected '{a}' and instead saw '{b}'.", - token, '<', '<'); - } else { - error("Missing '{a}'.", token, '>'); - } - } else if (nexttoken.id === '(end)') { - error("Bad structure."); - } else { - warning("Missing quote.", token); - } - } - advance(); - while (nexttoken.id === '-' || nexttoken.id === ':') { - w += nexttoken.id; - advance(); - if (!nexttoken.identifier) { - error("Bad name '{a}'.", nexttoken, w + nexttoken.value); - } - w += nexttoken.value; - advance(); - } - if (option.cap) { - w = w.toLowerCase(); - } - return w; - } - - function closetag(n) { - return ''; - } - - function xml() { - var a, e, n, q, t, wmode; - xmode = 'xml'; - stack = null; - for (;;) { - switch (nexttoken.value) { - case '<': - if (!stack) { - stack = []; - } - advance('<'); - t = nexttoken; - n = xmlword(true); - t.name = n; - if (!xtype) { - if (option.fragment && option.adsafe && - n !== 'div' && n !== 'iframe') { - error("ADsafe HTML fragment violation.", token); - } - if (xmltype[n]) { - xmltype[n].doBegin(); - n = xtype; - e = false; - } else { - if (option.fragment) { - xmltype.html.doBegin(); - } else { - error("Unrecognized tag '<{a}>'.", nexttoken, n); - } - } - } else { - if (stack.length === 0) { - error("What the hell is this?"); - } - e = xmltype[xtype].doTagName(n, - stack[stack.length - 1].name); - } - t.type = n; - for (;;) { - if (nexttoken.id === '/') { - advance('/'); - if (nexttoken.id !== '>') { - warning("Expected '{a}' and instead saw '{b}'.", - nexttoken, '>', nexttoken.value); - } - e = true; - break; - } - if (nexttoken.id && nexttoken.id.substr(0, 1) === '>') { - break; - } - a = xmlword(); - switch (xmltype[xtype].doAttribute(n, a)) { - case 'script': - xmode = 'string'; - advance('='); - q = nexttoken.id; - if (q !== '"' && q !== "'") { - error("Missing quote."); - } - xmode = q; - wmode = option.white; - option.white = false; - advance(q); - statements(); - option.white = wmode; - if (nexttoken.id !== q) { - error("Missing close quote on script attribute."); - } - xmode = 'xml'; - advance(q); - break; - case 'value': - advance('='); - if (!nexttoken.identifier && - nexttoken.type !== '(string)' && - nexttoken.type !== '(number)') { - error("Bad value '{a}'.", - nexttoken, nexttoken.value); - } - advance(); - break; - case 'string': - advance('='); - if (nexttoken.type !== '(string)') { - error("Bad value '{a}'.", - nexttoken, nexttoken.value); - } - advance(); - break; - case 'href': - advance('='); - if (nexttoken.type !== '(string)') { - error("Bad value '{a}'.", - nexttoken, nexttoken.value); - } - if (option.adsafe && ux.test(nexttoken.value)) { - error("ADsafe URL violation."); - } - advance(); - break; - case 'define': - advance('='); - if (nexttoken.type !== '(string)') { - error("Bad value '{a}'.", - nexttoken, nexttoken.value); - } - addlabel(nexttoken.value, 'var'); - advance(); - break; - default: - if (nexttoken.id === '=') { - advance('='); - if (!nexttoken.identifier && - nexttoken.type !== '(string)' && - nexttoken.type !== '(number)') { - error("Bad value '{a}'.", - nexttoken, nexttoken.value); - } - advance(); - } - } - } - switch (xmltype[xtype].doIt(n)) { - case 'script': - xmode = 'script'; - advance('>'); - indent = nexttoken.from; - if (src) { - if (option.fragment && option.adsafe) { - warning("ADsafe script violation.", token); - } - } else { - statements(); - } - if (nexttoken.id !== '', nexttoken.value); - } - xmode = 'xml'; - break; - case 'special': - e = true; - n = closetag(t.name); - if (!lex.skip(n)) { - error("Missing '{a}'.", t, n); - } - break; - default: - lex.skip('>'); - } - if (!e) { - stack.push(t); - } - break; - case '') { - error("Missing '{a}'.", nexttoken, '>'); - } - if (stack.length > 0) { - lex.skip('>'); - } else { - advance('>'); - } - break; - case '') { - break; - } - if (nexttoken.id === '<' || nexttoken.id === '(end)') { - error("Missing '{a}'.", token, '>'); - } - } - lex.skip('>'); - break; - case ''); - break; - case '<%': - if (option.adsafe) { - error("ADsafe HTML violation."); - } - lex.skip('%>'); - break; - case '') { - break; - } - if (nexttoken.id === '' || nexttoken.id === '(end)') { - error("Missing '{a}'.", token, '?>'); - } - } - lex.skip('?>'); - break; - case '<=': - case '<<': - case '<<=': - error("Missing '{a}'.", nexttoken, '<'); - break; - case '(end)': - return; - } - if (stack && stack.length === 0) { - return; - } - if (!lex.skip('')) { - if (!stack) { - error("Bad XML."); - } - t = stack.pop(); - if (t.value) { - error("Missing '{a}'.", t, closetag(t.name)); - } else { - return; - } - } - advance(); - } - } - - -// Build the syntax table by declaring the syntactic elements of the language. - - type('(number)', idValue); - type('(string)', idValue); - - syntax['(identifier)'] = { - type: '(identifier)', - lbp: 0, - identifier: true, - nud: function () { - var v = this.value, - s = scope[v]; - -// The name is in scope and defined in the current function. - - if (s && (s === funct || s === funct['(global)'])) { - -// If we are not also in the global scope, change 'unused' to 'var', -// and reject labels. - - if (!funct['(global)']) { - switch (funct[v]) { - case 'unused': - funct[v] = 'var'; - break; - case 'label': - warning("'{a}' is a statement label.", token, v); - break; - } - } - -// The name is not defined in the function. If we are in the global scope, -// then we have an undefined variable. - - } else if (funct['(global)']) { - if (option.undef) { - warning("'{a}' is undefined.", token, v); - } - note_implied(token); - -// If the name is already defined in the current -// function, but not as outer, then there is a scope error. - - } else { - switch (funct[v]) { - case 'closure': - case 'function': - case 'var': - case 'unused': - warning("'{a}' used out of scope.", token, v); - break; - case 'label': - warning("'{a}' is a statement label.", token, v); - break; - case 'outer': - case true: - break; - default: - -// If the name is defined in an outer function, make an outer entry, and if -// it was unused, make it var. - - if (s === true) { - funct[v] = true; - } else if (typeof s !== 'object') { - if (option.undef) { - warning("'{a}' is undefined.", token, v); - } else { - funct[v] = true; - } - note_implied(token); - } else { - switch (s[v]) { - case 'function': - case 'var': - case 'unused': - s[v] = 'closure'; - funct[v] = 'outer'; - break; - case 'closure': - case 'parameter': - funct[v] = 'outer'; - break; - case 'label': - warning("'{a}' is a statement label.", token, v); - } - } - } - } - return this; - }, - led: function () { - error("Expected an operator and instead saw '{a}'.", - nexttoken, nexttoken.value); - } - }; - - type('(regex)', function () { - return [this.id, this.value, this.flags]; - }); - - delim('(endline)'); - delim('(begin)'); - delim('(end)').reach = true; - delim(''); - delim('?>'); - delim('(error)').reach = true; - delim('}').reach = true; - delim(')'); - delim(']'); - delim(']]>').reach = true; - delim('"').reach = true; - delim("'").reach = true; - delim(';'); - delim(':').reach = true; - delim(','); - reserve('else'); - reserve('case').reach = true; - reserve('catch'); - reserve('default').reach = true; - reserve('finally'); - reservevar('arguments'); - reservevar('eval'); - reservevar('false'); - reservevar('Infinity'); - reservevar('NaN'); - reservevar('null'); - reservevar('this'); - reservevar('true'); - reservevar('undefined'); - assignop('=', 'assign', 20); - assignop('+=', 'assignadd', 20); - assignop('-=', 'assignsub', 20); - assignop('*=', 'assignmult', 20); - assignop('/=', 'assigndiv', 20).nud = function () { - error("A regular expression literal can be confused with '/='."); - }; - assignop('%=', 'assignmod', 20); - bitwiseassignop('&=', 'assignbitand', 20); - bitwiseassignop('|=', 'assignbitor', 20); - bitwiseassignop('^=', 'assignbitxor', 20); - bitwiseassignop('<<=', 'assignshiftleft', 20); - bitwiseassignop('>>=', 'assignshiftright', 20); - bitwiseassignop('>>>=', 'assignshiftrightunsigned', 20); - infix('?', function (left) { - parse(10); - advance(':'); - parse(10); - }, 30); - - infix('||', 'or', 40); - infix('&&', 'and', 50); - bitwise('|', 'bitor', 70); - bitwise('^', 'bitxor', 80); - bitwise('&', 'bitand', 90); - relation('==', function (left, right) { - if (option.eqeqeq) { - warning("Expected '{a}' and instead saw '{b}'.", - this, '===', '=='); - } else if (isPoorRelation(left)) { - warning("Use '{a}' to compare with '{b}'.", - this, '===', left.value); - } else if (isPoorRelation(right)) { - warning("Use '{a}' to compare with '{b}'.", - this, '===', right.value); - } - return ['==', left, right]; - }); - relation('==='); - relation('!=', function (left, right) { - if (option.eqeqeq) { - warning("Expected '{a}' and instead saw '{b}'.", - this, '!==', '!='); - } else if (isPoorRelation(left)) { - warning("Use '{a}' to compare with '{b}'.", - this, '!==', left.value); - } else if (isPoorRelation(right)) { - warning("Use '{a}' to compare with '{b}'.", - this, '!==', right.value); - } - return ['!=', left, right]; - }); - relation('!=='); - relation('<'); - relation('>'); - relation('<='); - relation('>='); - bitwise('<<', 'shiftleft', 120); - bitwise('>>', 'shiftright', 120); - bitwise('>>>', 'shiftrightunsigned', 120); - infix('in', 'in', 120); - infix('instanceof', 'instanceof', 120); - infix('+', function (left) { - nonadjacent(prevtoken, token); - nonadjacent(token, nexttoken); - var right = parse(130); - if (left && right && left.id === '(string)' && right.id === '(string)') { - left.value += right.value; - left.character = right.character; - if (jx.test(left.value)) { - warning("JavaScript URL.", left); - } - return left; - } - return [this.id, left, right]; - }, 130); - prefix('+', 'num'); - infix('-', 'sub', 130); - prefix('-', 'neg'); - infix('*', 'mult', 140); - infix('/', 'div', 140); - infix('%', 'mod', 140); - - suffix('++', 'postinc'); - prefix('++', 'preinc'); - syntax['++'].exps = true; - - suffix('--', 'postdec'); - prefix('--', 'predec'); - syntax['--'].exps = true; - prefix('delete', function () { - var p = parse(0); - if (p.id !== '.' && p.id !== '[') { - warning("Expected '{a}' and instead saw '{b}'.", - nexttoken, '.', nexttoken.value); - } - }).exps = true; - - - prefix('~', function () { - if (option.bitwise) { - warning("Unexpected '{a}'.", this, '~'); - } - parse(150); - return this; - }); - prefix('!', 'not'); - prefix('typeof', 'typeof'); - prefix('new', function () { - var c = parse(155), i; - if (c) { - if (c.identifier) { - c['new'] = true; - switch (c.value) { - case 'Object': - warning("Use the object literal notation {}.", token); - break; - case 'Array': - warning("Use the array literal notation [].", token); - break; - case 'Number': - case 'String': - case 'Boolean': - warning("Do not use the {a} function as a constructor.", - token, c.value); - break; - case 'Function': - if (!option.evil) { - warning("The Function constructor is eval."); - } - break; - default: - if (c.id !== 'function') { - i = c.value.substr(0, 1); - if (i < 'A' || i > 'Z') { - warning( - "A constructor name should start with an uppercase letter.", - token); - } - } - } - } else { - if (c.id !== '.' && c.id !== '[' && c.id !== '(') { - warning("Bad constructor.", token); - } - } - } else { - warning("Weird construction. Delete 'new'.", this); - } - adjacent(token, nexttoken); - if (nexttoken.id === '(') { - advance('('); - nospace(); - if (nexttoken.id !== ')') { - for (;;) { - parse(10); - if (nexttoken.id !== ',') { - break; - } - advance(','); - } - } - advance(')'); - nospace(prevtoken, token); - } else { - warning("Missing '()' invoking a constructor."); - } - return syntax['function']; - }); - syntax['new'].exps = true; - - infix('.', function (left) { - adjacent(prevtoken, token); - var m = identifier(); - if (typeof m === 'string') { - countMember(m); - } - if (!option.evil && left && left.value === 'document' && - (m === 'write' || m === 'writeln')) { - warning("document.write can be a form of eval.", left); - } - this.left = left; - this.right = m; - return this; - }, 160); - - infix('(', function (left) { - adjacent(prevtoken, token); - nospace(); - var n = 0; - var p = []; - if (left && left.type === '(identifier)') { - if (left.value.match(/^[A-Z](.*[a-z].*)?$/)) { - if (left.value !== 'Number' && left.value !== 'String' && - left.value !== 'Boolean' && left.value !== 'Date') { - warning("Missing 'new' prefix when invoking a constructor.", - left); - } - } - } - if (nexttoken.id !== ')') { - for (;;) { - p[p.length] = parse(10); - n += 1; - if (nexttoken.id !== ',') { - break; - } - advance(','); - nonadjacent(token, nexttoken); - } - } - advance(')'); - nospace(prevtoken, token); - if (typeof left === 'object') { - if (left.value === 'parseInt' && n === 1) { - warning("Missing radix parameter.", left); - } - if (!option.evil) { - if (left.value === 'eval' || left.value === 'Function') { - warning("eval is evil.", left); - } else if (p[0] && p[0].id === '(string)' && - (left.value === 'setTimeout' || - left.value === 'setInterval')) { - warning( - "Implied eval is evil. Pass a function instead of a string.", left); - } - } - if (!left.identifier && left.id !== '.' && - left.id !== '[' && left.id !== '(') { - warning("Bad invocation.", left); - } - - } - return syntax['function']; - }, 155).exps = true; - - prefix('(', function () { - nospace(); - var v = parse(0); - advance(')', this); - nospace(prevtoken, token); - return v; - }); - - infix('[', function (left) { - if (option.adsafe) { - warning('ADsafe subscripting.'); - } - nospace(); - var e = parse(0), s; - if (e && e.type === '(string)') { - countMember(e.value); - if (ix.test(e.value)) { - s = syntax[e.value]; - if (!s || !s.reserved) { - warning("['{a}'] is better written in dot notation.", - e, e.value); - } - } - } - advance(']', this); - nospace(prevtoken, token); - this.left = left; - this.right = e; - return this; - }, 160); - - prefix('[', function () { - if (nexttoken.id === ']') { - advance(']'); - return; - } - var b = token.line !== nexttoken.line; - if (b) { - indent += 4; - if (nexttoken.from === indent + 4) { - indent += 4; - } - } - for (;;) { - if (b && token.line !== nexttoken.line) { - indentation(); - } - parse(10); - if (nexttoken.id === ',') { - adjacent(token, nexttoken); - advance(','); - if (nexttoken.id === ',' || nexttoken.id === ']') { - warning("Extra comma.", token); - } - nonadjacent(token, nexttoken); - } else { - if (b) { - indent -= 4; - indentation(); - } - advance(']', this); - return; - } - } - }, 160); - - (function (x) { - x.nud = function () { - var i, s; - if (nexttoken.id === '}') { - advance('}'); - return; - } - var b = token.line !== nexttoken.line; - if (b) { - indent += 4; - if (nexttoken.from === indent + 4) { - indent += 4; - } - } - for (;;) { - if (b) { - indentation(); - } - i = optionalidentifier(true); - if (!i) { - if (nexttoken.id === '(string)') { - i = nexttoken.value; - if (ix.test(i)) { - s = syntax[i]; - } - advance(); - } else if (nexttoken.id === '(number)') { - i = nexttoken.value.toString(); - advance(); - } else { - error("Expected '{a}' and instead saw '{b}'.", - nexttoken, '}', nexttoken.value); - } - } - countMember(i); - advance(':'); - nonadjacent(token, nexttoken); - parse(10); - if (nexttoken.id === ',') { - adjacent(token, nexttoken); - advance(','); - if (nexttoken.id === ',' || nexttoken.id === '}') { - warning("Extra comma.", token); - } - nonadjacent(token, nexttoken); - } else { - if (b) { - indent -= 4; - indentation(); - } - advance('}', this); - return; - } - } - }; - x.fud = function () { - error("Expected to see a statement and instead saw a block.", token); - }; - })(delim('{')); - - - function varstatement() { - -// JavaScript does not have block scope. It only has function scope. So, -// declaring a variable in a block can have unexpected consequences. - - for (;;) { - nonadjacent(token, nexttoken); - addlabel(identifier(), 'unused'); - if (nexttoken.id === '=') { - nonadjacent(token, nexttoken); - advance('='); - nonadjacent(token, nexttoken); - if (peek(0).id === '=') { - error("Variable {a} was not declared correctly.", - nexttoken, nexttoken.value); - } - parse(20); - } - if (nexttoken.id !== ',') { - return; - } - adjacent(token, nexttoken); - advance(','); - nonadjacent(token, nexttoken); - } - } - - - stmt('var', varstatement); - - stmt('new', function () { - error("'new' should not be used as a statement."); - }); - - - function functionparams() { - var i, t = nexttoken, p = []; - advance('('); - nospace(); - if (nexttoken.id === ')') { - advance(')'); - nospace(prevtoken, token); - return; - } - for (;;) { - i = identifier(); - p.push(i); - addlabel(i, 'parameter'); - if (nexttoken.id === ',') { - advance(','); - nonadjacent(token, nexttoken); - } else { - advance(')', t); - nospace(prevtoken, token); - return p.join(', '); - } - } - } - - function doFunction(i) { - var s = scope; - scope = object(s); - funct = { - '(name)' : i || '"' + anonname + '"', - '(line)' : nexttoken.line + 1, - '(context)' : funct, - '(scope)' : scope - }; - functions.push(funct); - if (i) { - addlabel(i, 'function'); - } - funct['(params)'] = functionparams(); - - block(false); - scope = s; - funct = funct['(context)']; - } - - - blockstmt('function', function () { - if (inblock) { - warning( -"Function statements cannot be placed in blocks. Use a function expression or move the statement to the top of the outer function.", token); - - } - var i = identifier(); - adjacent(token, nexttoken); - addlabel(i, 'unused'); - doFunction(i); - if (nexttoken.id === '(' && nexttoken.line === token.line) { - error( -"Function statements are not invocable. Wrap the function expression in parens."); - } - }); - - prefix('function', function () { - var i = optionalidentifier(); - if (i) { - adjacent(token, nexttoken); - } else { - nonadjacent(token, nexttoken); - } - doFunction(i); - }); - - blockstmt('if', function () { - var t = nexttoken; - advance('('); - nonadjacent(this, t); - nospace(); - parse(20); - if (nexttoken.id === '=') { - warning("Assignment in control part."); - advance('='); - parse(20); - } - advance(')', t); - nospace(prevtoken, token); - block(true); - if (nexttoken.id === 'else') { - nonadjacent(token, nexttoken); - advance('else'); - if (nexttoken.id === 'if' || nexttoken.id === 'switch') { - statement(true); - } else { - block(true); - } - } - return this; - }); - - blockstmt('try', function () { - var b, e, s; - block(false); - if (nexttoken.id === 'catch') { - advance('catch'); - nonadjacent(token, nexttoken); - advance('('); - s = scope; - scope = object(s); - e = nexttoken.value; - if (nexttoken.type !== '(identifier)') { - warning("Expected an identifier and instead saw '{a}'.", - nexttoken, e); - } else { - addlabel(e, 'unused'); - } - advance(); - advance(')'); - block(false); - b = true; - scope = s; - } - if (nexttoken.id === 'finally') { - advance('finally'); - block(false); - return; - } else if (!b) { - error("Expected '{a}' and instead saw '{b}'.", - nexttoken, 'catch', nexttoken.value); - } - }); - - blockstmt('while', function () { - var t = nexttoken; - advance('('); - nonadjacent(this, t); - nospace(); - parse(20); - if (nexttoken.id === '=') { - warning("Assignment in control part."); - advance('='); - parse(20); - } - advance(')', t); - nospace(prevtoken, token); - block(true); - }).labelled = true; - - reserve('with'); - - blockstmt('switch', function () { - var t = nexttoken; - var g = false; - advance('('); - nonadjacent(this, t); - nospace(); - this.condition = parse(20); - advance(')', t); - nospace(prevtoken, token); - nonadjacent(token, nexttoken); - t = nexttoken; - advance('{'); - nonadjacent(token, nexttoken); - indent += 4; - this.cases = []; - for (;;) { - switch (nexttoken.id) { - case 'case': - switch (funct['(verb)']) { - case 'break': - case 'case': - case 'continue': - case 'return': - case 'switch': - case 'throw': - break; - default: - warning( - "Expected a 'break' statement before 'case'.", - token); - } - indentation(-4); - advance('case'); - this.cases.push(parse(20)); - g = true; - advance(':'); - funct['(verb)'] = 'case'; - break; - case 'default': - switch (funct['(verb)']) { - case 'break': - case 'continue': - case 'return': - case 'throw': - break; - default: - warning( - "Expected a 'break' statement before 'default'.", - token); - } - indentation(-4); - advance('default'); - g = true; - advance(':'); - break; - case '}': - indent -= 4; - indentation(); - advance('}', t); - if (this.cases.length === 1 || this.condition.id === 'true' || - this.condition.id === 'false') { - warning("This 'switch' should be an 'if'.", this); - } - return; - case '(end)': - error("Missing '{a}'.", nexttoken, '}'); - return; - default: - if (g) { - switch (token.id) { - case ',': - error("Each value should have its own case label."); - return; - case ':': - statements(); - break; - default: - error("Missing ':' on a case clause.", token); - } - } else { - error("Expected '{a}' and instead saw '{b}'.", - nexttoken, 'case', nexttoken.value); - } - } - } - }).labelled = true; - - stmt('debugger', function () { - if (!option.debug) { - warning("All 'debugger' statements should be removed."); - } - }); - - stmt('do', function () { - block(true); - advance('while'); - var t = nexttoken; - nonadjacent(token, t); - advance('('); - nospace(); - parse(20); - advance(')', t); - nospace(prevtoken, token); - }).labelled = true; - - blockstmt('for', function () { - var s, t = nexttoken; - advance('('); - nonadjacent(this, t); - nospace(); - if (peek(nexttoken.id === 'var' ? 1 : 0).id === 'in') { - if (nexttoken.id === 'var') { - advance('var'); - addlabel(identifier(), 'var'); - } else { - advance(); - } - advance('in'); - parse(20); - advance(')', t); - if (nexttoken.id === 'if') { - nolinebreak(token); - statement(true); - } else { - s = block(true); - if (!option.forin && (s.length > 1 || typeof s[0] !== 'object' || - s[0].value !== 'if')) { - warning("The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.", this); - } - } - return this; - } else { - if (nexttoken.id !== ';') { - if (nexttoken.id === 'var') { - advance('var'); - varstatement(); - } else { - for (;;) { - parse(0); - if (nexttoken.id !== ',') { - break; - } - advance(','); - } - } - } - advance(';'); - if (nexttoken.id !== ';') { - parse(20); - } - advance(';'); - if (nexttoken.id === ';') { - error("Expected '{a}' and instead saw '{b}'.", - nexttoken, ')', ';'); - } - if (nexttoken.id !== ')') { - for (;;) { - parse(0); - if (nexttoken.id !== ',') { - break; - } - advance(','); - } - } - advance(')', t); - nospace(prevtoken, token); - block(true); - } - }).labelled = true; - - - stmt('break', function () { - var v = nexttoken.value; - nolinebreak(this); - if (nexttoken.id !== ';') { - if (funct[v] !== 'label') { - warning("'{a}' is not a statement label.", nexttoken, v); - } else if (scope[v] !== funct) { - warning("'{a}' is out of scope.", nexttoken, v); - } - advance(); - } - reachable('break'); - }); - - - stmt('continue', function () { - var v = nexttoken.value; - nolinebreak(this); - if (nexttoken.id !== ';') { - if (funct[v] !== 'label') { - warning("'{a}' is not a statement label.", nexttoken, v); - } else if (scope[v] !== funct) { - warning("'{a}' is out of scope.", nexttoken, v); - } - advance(); - } - reachable('continue'); - }); - - - stmt('return', function () { - nolinebreak(this); - if (nexttoken.id !== ';' && !nexttoken.reach) { - nonadjacent(token, nexttoken); - parse(20); - } - reachable('return'); - }); - - - stmt('throw', function () { - nolinebreak(this); - nonadjacent(token, nexttoken); - parse(20); - reachable('throw'); - }); - - -// Superfluous reserved words - - reserve('abstract'); - reserve('boolean'); - reserve('byte'); - reserve('char'); - reserve('class'); - reserve('const'); - reserve('double'); - reserve('enum'); - reserve('export'); - reserve('extends'); - reserve('final'); - reserve('float'); - reserve('goto'); - reserve('implements'); - reserve('import'); - reserve('int'); - reserve('interface'); - reserve('long'); - reserve('native'); - reserve('package'); - reserve('private'); - reserve('protected'); - reserve('public'); - reserve('short'); - reserve('static'); - reserve('super'); - reserve('synchronized'); - reserve('throws'); - reserve('transient'); - reserve('void'); - reserve('volatile'); - - - function jsonValue() { - - function jsonObject() { - var t = nexttoken; - advance('{'); - if (nexttoken.id !== '}') { - for (;;) { - if (nexttoken.id === '(end)') { - error("Missing '}' to match '{' from line {a}.", - nexttoken, t.line + 1); - } else if (nexttoken.id === '}') { - warning("Unexpected comma.", token); - break; - } else if (nexttoken.id === ',') { - error("Unexpected comma.", nexttoken); - } else if (nexttoken.id !== '(string)') { - warning("Expected a string and instead saw {a}.", - nexttoken, nexttoken.value); - } - advance(); - advance(':'); - jsonValue(); - if (nexttoken.id !== ',') { - break; - } - advance(','); - } - } - advance('}'); - } - - function jsonArray() { - var t = nexttoken; - advance('['); - if (nexttoken.id !== ']') { - for (;;) { - if (nexttoken.id === '(end)') { - error("Missing ']' to match '[' from line {a}.", - nexttoken, t.line + 1); - } else if (nexttoken.id === ']') { - warning("Unexpected comma.", token); - break; - } else if (nexttoken.id === ',') { - error("Unexpected comma.", nexttoken); - } - jsonValue(); - if (nexttoken.id !== ',') { - break; - } - advance(','); - } - } - advance(']'); - } - - switch (nexttoken.id) { - case '{': - jsonObject(); - break; - case '[': - jsonArray(); - break; - case 'true': - case 'false': - case 'null': - case '(number)': - case '(string)': - advance(); - break; - case '-': - advance('-'); - if (token.character !== nexttoken.from) { - warning("Unexpected space after '-'.", token); - } - adjacent(token, nexttoken); - advance('(number)'); - break; - default: - error("Expected a JSON value.", nexttoken); - } - } - - -// The actual JSLINT function itself. - - var itself = function (s, o) { - if (o) { - if (o.adsafe) { - o.browser = false; - o.debug = false; - o.eqeqeq = true; - o.evil = false; - o.forin = false; - o.on = false; - o.rhino = false; - o.undef = true; - o.widget = false; - } - option = o; - } else { - option = {}; - } - globals = option.adsafe ? {} : object(standard); - JSLINT.errors = []; - global = object(globals); - scope = global; - funct = {'(global)': true, '(name)': '(global)', '(scope)': scope}; - functions = []; - src = false; - xmode = false; - xtype = ''; - stack = null; - member = {}; - membersOnly = null; - implied = {}; - inblock = false; - lookahead = []; - indent = 0; - jsonmode = false; - warnings = 0; - lex.init(s); - prereg = true; - - prevtoken = token = nexttoken = syntax['(begin)']; - populateGlobals(); - - try { - advance(); - if (nexttoken.value.charAt(0) === '<') { - xml(); - } else if (nexttoken.id === '{' || nexttoken.id === '[') { - option.laxbreak = true; - jsonmode = true; - jsonValue(); - } else { - statements(); - } - advance('(end)'); - } catch (e) { - if (e) { - JSLINT.errors.push({ - reason : e.message, - line : e.line || nexttoken.line, - character : e.character || nexttoken.from - }, null); - } - } - return JSLINT.errors.length === 0; - }; - - function to_array(o) { - var a = [], k; - for (k in o) if (o.hasOwnProperty(k)) { - a.push(k); - } - return a; - } - -// Report generator. - - itself.report = function (option) { - var a = [], c, e, f, i, k, l, m = '', n, o = [], s, v, cl, va, un, ou, gl, la; - - function detail(h, s) { - if (s.length) { - o.push('
' + h + ' ' + - s.sort().join(', ') + '
'); - } - } - - s = to_array(implied); - - k = JSLINT.errors.length; - if (k || s.length > 0) { - o.push('
Error:'); - if (s.length > 0) { - s.sort(); - for (i = 0; i < s.length; i += 1) { - s[i] = '' + s[i] + ' ' + - implied[s[i]].join(' ') + - ''; - } - o.push('

Implied global: ' + s.join(', ') + '

'); - c = true; - } - for (i = 0; i < k; i += 1) { - c = JSLINT.errors[i]; - if (c) { - e = c.evidence || ''; - o.push('

Problem' + (isFinite(c.line) ? ' at line ' + (c.line + 1) + - ' character ' + (c.character + 1) : '') + - ': ' + c.reason.entityify() + - '

' + - (e && (e.length > 80 ? e.slice(0, 77) + '...' : - e).entityify()) + '

'); - } - } - o.push('
'); - if (!c) { - return o.join(''); - } - } - - if (!option) { - - o.push('
'); - - s = to_array(scope); - if (s.length === 0) { - o.push('
No new global variables introduced.
'); - } else { - o.push('
Global ' + s.sort().join(', ') + '
'); - } - - for (i = 0; i < functions.length; i += 1) { - f = functions[i]; - cl = []; - va = []; - un = []; - ou = []; - gl = []; - la = []; - for (k in f) if (f.hasOwnProperty(k)) { - v = f[k]; - switch (v) { - case 'closure': - cl.push(k); - break; - case 'var': - va.push(k); - break; - case 'unused': - un.push(k); - break; - case 'label': - la.push(k); - break; - case 'outer': - ou.push(k); - break; - case true: - if (k !== '(context)') { - gl.push(k); - } - break; - } - } - o.push('
' + f['(line)'] + ' ' + - (f['(name)'] || '') + '(' + - (f['(params)'] || '') + ')
'); - detail('Closure', cl); - detail('Variable', va); - detail('Unused', un); - detail('Label', la); - detail('Outer', ou); - detail('Global', gl); - } - a = []; - for (k in member) { - if (typeof member[k] === 'number') { - a.push(k); - } - } - if (a.length) { - a = a.sort(); - m = '
/*members ';
-                l = 10;
-                for (i = 0; i < a.length; i += 1) {
-                    k = a[i];
-                    n = k.name();
-                    if (l + n.length > 72) {
-                        o.push(m + '
'); - m = ' '; - l = 1; - } - l += n.length + 2; - if (member[k] === 1) { - n = '' + n + ''; - } - if (i < a.length - 1) { - n += ', '; - } - m += n; - } - o.push(m + '
*/
'); - } - o.push('
'); - } - return o.join(''); - }; - - return itself; - -}(); \ No newline at end of file diff --git a/license.txt b/license.txt deleted file mode 100644 index bdbd99b..0000000 --- a/license.txt +++ /dev/null @@ -1,21 +0,0 @@ -EJS - Embedded JavaScript - -Copyright (c) 2007 Edward Benson - -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. \ No newline at end of file diff --git a/script/production.bat b/script/production.bat deleted file mode 100644 index 257913f..0000000 --- a/script/production.bat +++ /dev/null @@ -1,4 +0,0 @@ -type ..\src\ejs.js > ..\src\ejs_production_collection.js -type ..\src\view.js >> ..\src\ejs_production_collection.js -java -jar yuicompressor-2.2.4.jar ..\src\ejs_production_collection.js -o ..\src\ejs_production.js -del ..\src\ejs_production_collection.js \ No newline at end of file diff --git a/script/yuicompressor-2.2.4.jar b/script/yuicompressor-2.2.4.jar deleted file mode 100644 index 0e363e9..0000000 Binary files a/script/yuicompressor-2.2.4.jar and /dev/null differ diff --git a/src/ejs.js b/src/ejs.js deleted file mode 100644 index 49d9525..0000000 --- a/src/ejs.js +++ /dev/null @@ -1,505 +0,0 @@ -(function(){ - - -var rsplit = function(string, regex) { - var result = regex.exec(string),retArr = new Array(), first_idx, last_idx, first_bit; - while (result != null) - { - first_idx = result.index; last_idx = regex.lastIndex; - if ((first_idx) != 0) - { - first_bit = string.substring(0,first_idx); - retArr.push(string.substring(0,first_idx)); - string = string.slice(first_idx); - } - retArr.push(result[0]); - string = string.slice(result[0].length); - result = regex.exec(string); - } - if (! string == '') - { - retArr.push(string); - } - return retArr; -}, -chop = function(string){ - return string.substr(0, string.length - 1); -}, -extend = function(d, s){ - for(var n in s){ - if(s.hasOwnProperty(n)) d[n] = s[n] - } -} - - -EJS = function( options ){ - options = typeof options == "string" ? {view: options} : options - this.set_options(options); - if(options.precompiled){ - this.template = {}; - this.template.process = options.precompiled; - EJS.update(this.name, this); - return; - } - if(options.element) - { - if(typeof options.element == 'string'){ - var name = options.element - options.element = document.getElementById( options.element ) - if(options.element == null) throw name+'does not exist!' - } - if(options.element.value){ - this.text = options.element.value - }else{ - this.text = options.element.innerHTML - } - this.name = options.element.id - this.type = '[' - }else if(options.url){ - options.url = EJS.endExt(options.url, this.extMatch); - this.name = this.name ? this.name : options.url; - var url = options.url - //options.view = options.absolute_url || options.view || options.; - var template = EJS.get(this.name /*url*/, this.cache); - if (template) return template; - if (template == EJS.INVALID_PATH) return null; - try{ - this.text = EJS.request( url+(this.cache ? '' : '?'+Math.random() )); - }catch(e){} - - if(this.text == null){ - throw( {type: 'EJS', message: 'There is no template at '+url} ); - } - //this.name = url; - } - var template = new EJS.Compiler(this.text, this.type); - - template.compile(options, this.name); - - - EJS.update(this.name, this); - this.template = template; -}; -/* @Prototype*/ -EJS.prototype = { - /** - * Renders an object with extra view helpers attached to the view. - * @param {Object} object data to be rendered - * @param {Object} extra_helpers an object with additonal view helpers - * @return {String} returns the result of the string - */ - render : function(object, extra_helpers){ - object = object || {}; - this._extra_helpers = extra_helpers; - var v = new EJS.Helpers(object, extra_helpers || {}); - return this.template.process.call(object, object,v); - }, - update : function(element, options){ - if(typeof element == 'string'){ - element = document.getElementById(element) - } - if(options == null){ - _template = this; - return function(object){ - EJS.prototype.update.call(_template, element, object) - } - } - if(typeof options == 'string'){ - params = {} - params.url = options - _template = this; - params.onComplete = function(request){ - var object = eval( request.responseText ) - EJS.prototype.update.call(_template, element, object) - } - EJS.ajax_request(params) - }else - { - element.innerHTML = this.render(options) - } - }, - out : function(){ - return this.template.out; - }, - /** - * Sets options on this view to be rendered with. - * @param {Object} options - */ - set_options : function(options){ - this.type = options.type || EJS.type; - this.cache = options.cache != null ? options.cache : EJS.cache; - this.text = options.text || null; - this.name = options.name || null; - this.ext = options.ext || EJS.ext; - this.extMatch = new RegExp(this.ext.replace(/\./, '\.')); - } -}; -EJS.endExt = function(path, match){ - if(!path) return null; - match.lastIndex = 0 - return path+ (match.test(path) ? '' : this.ext ) -} - - - - -/* @Static*/ -EJS.Scanner = function(source, left, right) { - - extend(this, - {left_delimiter: left +'%', - right_delimiter: '%'+right, - double_left: left+'%%', - double_right: '%%'+right, - left_equal: left+'%=', - left_comment: left+'%#'}) - - this.SplitRegexp = left=='[' ? /(\[%%)|(%%\])|(\[%=)|(\[%#)|(\[%)|(%\]\n)|(%\])|(\n)/ : new RegExp('('+this.double_left+')|(%%'+this.double_right+')|('+this.left_equal+')|('+this.left_comment+')|('+this.left_delimiter+')|('+this.right_delimiter+'\n)|('+this.right_delimiter+')|(\n)') ; - - this.source = source; - this.stag = null; - this.lines = 0; -}; - -EJS.Scanner.to_text = function(input){ - if(input == null || input === undefined) - return ''; - if(input instanceof Date) - return input.toDateString(); - if(input.toString) - return input.toString(); - return ''; -}; - -EJS.Scanner.prototype = { - scan: function(block) { - scanline = this.scanline; - regex = this.SplitRegexp; - if (! this.source == '') - { - var source_split = rsplit(this.source, /\n/); - for(var i=0; i 0) - { - for (var i=0; i 0) - { - buff.push(put_cmd + '"' + clean(content) + '")'); - } - content = ''; - break; - case scanner.double_left: - content = content + scanner.left_delimiter; - break; - default: - content = content + token; - break; - } - } - else { - switch(token) { - case scanner.right_delimiter: - switch(scanner.stag) { - case scanner.left_delimiter: - if (content[content.length - 1] == '\n') - { - content = chop(content); - buff.push(content); - buff.cr(); - } - else { - buff.push(content); - } - break; - case scanner.left_equal: - buff.push(insert_cmd + "(EJS.Scanner.to_text(" + content + ")))"); - break; - } - scanner.stag = null; - content = ''; - break; - case scanner.double_right: - content = content + scanner.right_delimiter; - break; - default: - content = content + token; - break; - } - } - }); - if (content.length > 0) - { - // Chould be content.dump in Ruby - buff.push(put_cmd + '"' + clean(content) + '")'); - } - buff.close(); - this.out = buff.script + ";"; - var to_be_evaled = '/*'+name+'*/this.process = function(_CONTEXT,_VIEW) { try { with(_VIEW) { with (_CONTEXT) {'+this.out+" return ___ViewO.join('');}}}catch(e){e.lineNumber=null;throw e;}};"; - - try{ - eval(to_be_evaled); - }catch(e){ - if(typeof JSLINT != 'undefined'){ - JSLINT(this.out); - for(var i = 0; i < JSLINT.errors.length; i++){ - var error = JSLINT.errors[i]; - if(error.reason != "Unnecessary semicolon."){ - error.line++; - var e = new Error(); - e.lineNumber = error.line; - e.message = error.reason; - if(options.view) - e.fileName = options.view; - throw e; - } - } - }else{ - throw e; - } - } - } -}; - - -//type, cache, folder -/** - * Sets default options for all views - * @param {Object} options Set view with the following options - * - - - - - - - - - - - -
OptionDefaultDescription
type'<'type of magic tags. Options are '<' or '[' -
cachetrue in production mode, false in other modestrue to cache template. -
- * - */ -EJS.config = function(options){ - EJS.cache = options.cache != null ? options.cache : EJS.cache; - EJS.type = options.type != null ? options.type : EJS.type; - EJS.ext = options.ext != null ? options.ext : EJS.ext; - - var templates_directory = EJS.templates_directory || {}; //nice and private container - EJS.templates_directory = templates_directory; - EJS.get = function(path, cache){ - if(cache == false) return null; - if(templates_directory[path]) return templates_directory[path]; - return null; - }; - - EJS.update = function(path, template) { - if(path == null) return; - templates_directory[path] = template ; - }; - - EJS.INVALID_PATH = -1; -}; -EJS.config( {cache: true, type: '<', ext: '.ejs' } ); - - - -/** - * @constructor - * By adding functions to EJS.Helpers.prototype, those functions will be available in the - * views. - * @init Creates a view helper. This function is called internally. You should never call it. - * @param {Object} data The data passed to the view. Helpers have access to it through this._data - */ -EJS.Helpers = function(data, extras){ - this._data = data; - this._extras = extras; - extend(this, extras ); -}; -/* @prototype*/ -EJS.Helpers.prototype = { - /** - * Renders a new view. If data is passed in, uses that to render the view. - * @param {Object} options standard options passed to a new view. - * @param {optional:Object} data - * @return {String} - */ - view: function(options, data, helpers){ - if(!helpers) helpers = this._extras - if(!data) data = this._data; - return new EJS(options).render(data, helpers); - }, - /** - * For a given value, tries to create a human representation. - * @param {Object} input the value being converted. - * @param {Object} null_text what text should be present if input == null or undefined, defaults to '' - * @return {String} - */ - to_text: function(input, null_text) { - if(input == null || input === undefined) return null_text || ''; - if(input instanceof Date) return input.toDateString(); - if(input.toString) return input.toString().replace(/\n/g, '
').replace(/''/g, "'"); - return ''; - } -}; - EJS.newRequest = function(){ - var factories = [function() { return new ActiveXObject("Msxml2.XMLHTTP"); },function() { return new XMLHttpRequest(); },function() { return new ActiveXObject("Microsoft.XMLHTTP"); }]; - for(var i = 0; i < factories.length; i++) { - try { - var request = factories[i](); - if (request != null) return request; - } - catch(e) { continue;} - } - } - - EJS.request = function(path){ - var request = new EJS.newRequest() - request.open("GET", path, false); - - try{request.send(null);} - catch(e){return null;} - - if ( request.status == 404 || request.status == 2 ||(request.status == 0 && request.responseText == '') ) return null; - - return request.responseText - } - EJS.ajax_request = function(params){ - params.method = ( params.method ? params.method : 'GET') - - var request = new EJS.newRequest(); - request.onreadystatechange = function(){ - if(request.readyState == 4){ - if(request.status == 200){ - params.onComplete(request) - }else - { - params.onComplete(request) - } - } - } - request.open(params.method, params.url) - request.send(null) - } - - -})(); \ No newline at end of file diff --git a/src/view.js b/src/view.js deleted file mode 100644 index e8c0eee..0000000 --- a/src/view.js +++ /dev/null @@ -1,200 +0,0 @@ -EJS.Helpers.prototype.date_tag = function(name, value , html_options) { - if(! (value instanceof Date)) - value = new Date() - - var month_names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; - var years = [], months = [], days =[]; - var year = value.getFullYear(); - var month = value.getMonth(); - var day = value.getDate(); - for(var y = year - 15; y < year+15 ; y++) - { - years.push({value: y, text: y}) - } - for(var m = 0; m < 12; m++) - { - months.push({value: (m), text: month_names[m]}) - } - for(var d = 0; d < 31; d++) - { - days.push({value: (d+1), text: (d+1)}) - } - var year_select = this.select_tag(name+'[year]', year, years, {id: name+'[year]'} ) - var month_select = this.select_tag(name+'[month]', month, months, {id: name+'[month]'}) - var day_select = this.select_tag(name+'[day]', day, days, {id: name+'[day]'}) - - return year_select+month_select+day_select; -} - -EJS.Helpers.prototype.form_tag = function(action, html_options) { - - - html_options = html_options || {}; - html_options.action = action - if(html_options.multipart == true) { - html_options.method = 'post'; - html_options.enctype = 'multipart/form-data'; - } - - return this.start_tag_for('form', html_options) -} - -EJS.Helpers.prototype.form_tag_end = function() { return this.tag_end('form'); } - -EJS.Helpers.prototype.hidden_field_tag = function(name, value, html_options) { - return this.input_field_tag(name, value, 'hidden', html_options); -} - -EJS.Helpers.prototype.input_field_tag = function(name, value , inputType, html_options) { - - html_options = html_options || {}; - html_options.id = html_options.id || name; - html_options.value = value || ''; - html_options.type = inputType || 'text'; - html_options.name = name; - - return this.single_tag_for('input', html_options) -} - -EJS.Helpers.prototype.is_current_page = function(url) { - return (window.location.href == url || window.location.pathname == url ? true : false); -} - -EJS.Helpers.prototype.link_to = function(name, url, html_options) { - if(!name) var name = 'null'; - if(!html_options) var html_options = {} - - if(html_options.confirm){ - html_options.onclick = - " var ret_confirm = confirm(\""+html_options.confirm+"\"); if(!ret_confirm){ return false;} " - html_options.confirm = null; - } - html_options.href=url - return this.start_tag_for('a', html_options)+name+ this.tag_end('a'); -} - -EJS.Helpers.prototype.submit_link_to = function(name, url, html_options){ - if(!name) var name = 'null'; - if(!html_options) var html_options = {} - html_options.onclick = html_options.onclick || '' ; - - if(html_options.confirm){ - html_options.onclick = - " var ret_confirm = confirm(\""+html_options.confirm+"\"); if(!ret_confirm){ return false;} " - html_options.confirm = null; - } - - html_options.value = name; - html_options.type = 'submit' - html_options.onclick=html_options.onclick+ - (url ? this.url_for(url) : '')+'return false;'; - //html_options.href='#'+(options ? Routes.url_for(options) : '') - return this.start_tag_for('input', html_options) -} - -EJS.Helpers.prototype.link_to_if = function(condition, name, url, html_options, post, block) { - return this.link_to_unless((condition == false), name, url, html_options, post, block); -} - -EJS.Helpers.prototype.link_to_unless = function(condition, name, url, html_options, block) { - html_options = html_options || {}; - if(condition) { - if(block && typeof block == 'function') { - return block(name, url, html_options, block); - } else { - return name; - } - } else - return this.link_to(name, url, html_options); -} - -EJS.Helpers.prototype.link_to_unless_current = function(name, url, html_options, block) { - html_options = html_options || {}; - return this.link_to_unless(this.is_current_page(url), name, url, html_options, block) -} - - -EJS.Helpers.prototype.password_field_tag = function(name, value, html_options) { return this.input_field_tag(name, value, 'password', html_options); } - -EJS.Helpers.prototype.select_tag = function(name, value, choices, html_options) { - html_options = html_options || {}; - html_options.id = html_options.id || name; - html_options.value = value; - html_options.name = name; - - var txt = '' - txt += this.start_tag_for('select', html_options) - - for(var i = 0; i < choices.length; i++) - { - var choice = choices[i]; - var optionOptions = {value: choice.value} - if(choice.value == value) - optionOptions.selected ='selected' - txt += this.start_tag_for('option', optionOptions )+choice.text+this.tag_end('option') - } - txt += this.tag_end('select'); - return txt; -} - -EJS.Helpers.prototype.single_tag_for = function(tag, html_options) { return this.tag(tag, html_options, '/>');} - -EJS.Helpers.prototype.start_tag_for = function(tag, html_options) { return this.tag(tag, html_options); } - -EJS.Helpers.prototype.submit_tag = function(name, html_options) { - html_options = html_options || {}; - //html_options.name = html_options.id || 'commit'; - html_options.type = html_options.type || 'submit'; - html_options.value = name || 'Submit'; - return this.single_tag_for('input', html_options); -} - -EJS.Helpers.prototype.tag = function(tag, html_options, end) { - if(!end) var end = '>' - var txt = ' ' - for(var attr in html_options) { - if(html_options[attr] != null) - var value = html_options[attr].toString(); - else - var value='' - if(attr == "Class") // special case because "class" is a reserved word in IE - attr = "class"; - if( value.indexOf("'") != -1 ) - txt += attr+'=\"'+value+'\" ' - else - txt += attr+"='"+value+"' " - } - return '<'+tag+txt+end; -} - -EJS.Helpers.prototype.tag_end = function(tag) { return ''; } - -EJS.Helpers.prototype.text_area_tag = function(name, value, html_options) { - html_options = html_options || {}; - html_options.id = html_options.id || name; - html_options.name = html_options.name || name; - value = value || '' - if(html_options.size) { - html_options.cols = html_options.size.split('x')[0] - html_options.rows = html_options.size.split('x')[1]; - delete html_options.size - } - - html_options.cols = html_options.cols || 50; - html_options.rows = html_options.rows || 4; - - return this.start_tag_for('textarea', html_options)+value+this.tag_end('textarea') -} -EJS.Helpers.prototype.text_tag = EJS.Helpers.prototype.text_area_tag - -EJS.Helpers.prototype.text_field_tag = function(name, value, html_options) { return this.input_field_tag(name, value, 'text', html_options); } - -EJS.Helpers.prototype.url_for = function(url) { - return 'window.location="'+url+'";' -} -EJS.Helpers.prototype.img_tag = function(image_location, alt, options){ - options = options || {}; - options.src = image_location - options.alt = alt - return this.single_tag_for('img', options) -} diff --git a/test/included/prototype.js b/test/included/prototype.js deleted file mode 100644 index 5c73462..0000000 --- a/test/included/prototype.js +++ /dev/null @@ -1,4184 +0,0 @@ -/* Prototype JavaScript framework, version 1.6.0 - * (c) 2005-2007 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.6.0', - - Browser: { - IE: !!(window.attachEvent && !window.opera), - Opera: !!window.opera, - WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1, - Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1, - MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/) - }, - - BrowserFeatures: { - XPath: !!document.evaluate, - ElementExtensions: !!window.HTMLElement, - SpecificElementExtensions: - document.createElement('div').__proto__ && - document.createElement('div').__proto__ !== - document.createElement('form').__proto__ - }, - - ScriptFragment: ']*>([\\S\\s]*?)<\/script>', - JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/, - - emptyFunction: function() { }, - K: function(x) { return x } -}; - -if (Prototype.Browser.MobileSafari) - Prototype.BrowserFeatures.SpecificElementExtensions = false; - -if (Prototype.Browser.WebKit) - Prototype.BrowserFeatures.XPath = false; - -/* Based on Alex Arnell's inheritance implementation. */ -var Class = { - create: function() { - 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) { - var subclass = function() { }; - subclass.prototype = parent.prototype; - klass.prototype = new subclass; - parent.subclasses.push(klass); - } - - for (var i = 0; i < properties.length; i++) - klass.addMethods(properties[i]); - - if (!klass.prototype.initialize) - klass.prototype.initialize = Prototype.emptyFunction; - - klass.prototype.constructor = klass; - - return klass; - } -}; - -Class.Methods = { - addMethods: function(source) { - var ancestor = this.superclass && this.superclass.prototype; - var properties = Object.keys(source); - - if (!Object.keys({ toString: true }).length) - properties.push("toString", "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().first() == "$super") { - var method = value, value = Object.extend((function(m) { - return function() { return ancestor[m].apply(this, arguments) }; - })(property).wrap(method), { - valueOf: function() { return method }, - toString: function() { return method.toString() } - }); - } - this.prototype[property] = value; - } - - return this; - } -}; - -var Abstract = { }; - -Object.extend = function(destination, source) { - for (var property in source) - destination[property] = source[property]; - return destination; -}; - -Object.extend(Object, { - inspect: function(object) { - try { - if (object === undefined) return 'undefined'; - if (object === null) return 'null'; - return object.inspect ? object.inspect() : object.toString(); - } catch (e) { - if (e instanceof RangeError) return '...'; - throw e; - } - }, - - toJSON: function(object) { - var type = typeof object; - switch (type) { - case 'undefined': - case 'function': - case 'unknown': return; - case 'boolean': return object.toString(); - } - - if (object === null) return 'null'; - if (object.toJSON) return object.toJSON(); - if (Object.isElement(object)) return; - - var results = []; - for (var property in object) { - var value = Object.toJSON(object[property]); - if (value !== undefined) - results.push(property.toJSON() + ': ' + value); - } - - return '{' + results.join(', ') + '}'; - }, - - toQueryString: function(object) { - return $H(object).toQueryString(); - }, - - toHTML: function(object) { - return object && object.toHTML ? object.toHTML() : String.interpret(object); - }, - - keys: function(object) { - var keys = []; - for (var property in object) - keys.push(property); - return keys; - }, - - values: function(object) { - var values = []; - for (var property in object) - values.push(object[property]); - return values; - }, - - clone: function(object) { - return Object.extend({ }, object); - }, - - isElement: function(object) { - return object && object.nodeType == 1; - }, - - isArray: function(object) { - return object && object.constructor === Array; - }, - - isHash: function(object) { - return object instanceof Hash; - }, - - isFunction: function(object) { - return typeof object == "function"; - }, - - isString: function(object) { - return typeof object == "string"; - }, - - isNumber: function(object) { - return typeof object == "number"; - }, - - isUndefined: function(object) { - return typeof object == "undefined"; - } -}); - -Object.extend(Function.prototype, { - argumentNames: function() { - var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip"); - return names.length == 1 && !names[0] ? [] : names; - }, - - bind: function() { - if (arguments.length < 2 && arguments[0] === undefined) return this; - var __method = this, args = $A(arguments), object = args.shift(); - return function() { - return __method.apply(object, args.concat($A(arguments))); - } - }, - - bindAsEventListener: function() { - var __method = this, args = $A(arguments), object = args.shift(); - return function(event) { - return __method.apply(object, [event || window.event].concat(args)); - } - }, - - curry: function() { - if (!arguments.length) return this; - var __method = this, args = $A(arguments); - return function() { - return __method.apply(this, args.concat($A(arguments))); - } - }, - - delay: function() { - var __method = this, args = $A(arguments), timeout = args.shift() * 1000; - return window.setTimeout(function() { - return __method.apply(__method, args); - }, timeout); - }, - - wrap: function(wrapper) { - var __method = this; - return function() { - return wrapper.apply(this, [__method.bind(this)].concat($A(arguments))); - } - }, - - methodize: function() { - if (this._methodized) return this._methodized; - var __method = this; - return this._methodized = function() { - return __method.apply(null, [this].concat($A(arguments))); - }; - } -}); - -Function.prototype.defer = Function.prototype.delay.curry(0.01); - -Date.prototype.toJSON = function() { - 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"'; -}; - -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; - } -}; - -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(); - } finally { - this.currentlyExecuting = false; - } - } - } -}); -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, { - gsub: function(pattern, replacement) { - var result = '', source = this, match; - replacement = arguments.callee.prepareReplacement(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; - }, - - sub: function(pattern, replacement, count) { - replacement = this.gsub.prepareReplacement(replacement); - count = count === undefined ? 1 : count; - - return this.gsub(pattern, function(match) { - if (--count < 0) return match[0]; - return replacement(match); - }); - }, - - scan: function(pattern, iterator) { - this.gsub(pattern, iterator); - return String(this); - }, - - truncate: function(length, truncation) { - length = length || 30; - truncation = truncation === undefined ? '...' : truncation; - return this.length > length ? - this.slice(0, length - truncation.length) + truncation : String(this); - }, - - strip: function() { - return this.replace(/^\s+/, '').replace(/\s+$/, ''); - }, - - stripTags: function() { - return this.replace(/<\/?[^>]+>/gi, ''); - }, - - stripScripts: function() { - return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); - }, - - extractScripts: function() { - var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); - var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); - return (this.match(matchAll) || []).map(function(scriptTag) { - return (scriptTag.match(matchOne) || ['', ''])[1]; - }); - }, - - evalScripts: function() { - return this.extractScripts().map(function(script) { return eval(script) }); - }, - - escapeHTML: function() { - var self = arguments.callee; - self.text.data = this; - return self.div.innerHTML; - }, - - unescapeHTML: function() { - var div = new Element('div'); - div.innerHTML = this.stripTags(); - return div.childNodes[0] ? (div.childNodes.length > 1 ? - $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) : - div.childNodes[0].nodeValue) : ''; - }, - - toQueryParams: function(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()); - var 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; - }); - }, - - toArray: function() { - return this.split(''); - }, - - succ: function() { - return this.slice(0, this.length - 1) + - String.fromCharCode(this.charCodeAt(this.length - 1) + 1); - }, - - times: function(count) { - return count < 1 ? '' : new Array(count + 1).join(this); - }, - - camelize: function() { - var parts = this.split('-'), len = parts.length; - if (len == 1) return parts[0]; - - var camelized = this.charAt(0) == '-' - ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) - : parts[0]; - - for (var i = 1; i < len; i++) - camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1); - - return camelized; - }, - - capitalize: function() { - return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); - }, - - underscore: function() { - return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase(); - }, - - dasherize: function() { - return this.gsub(/_/,'-'); - }, - - inspect: function(useDoubleQuotes) { - var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) { - var character = String.specialChar[match[0]]; - return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16); - }); - if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"'; - return "'" + escapedString.replace(/'/g, '\\\'') + "'"; - }, - - toJSON: function() { - return this.inspect(true); - }, - - unfilterJSON: function(filter) { - return this.sub(filter || Prototype.JSONFilter, '#{1}'); - }, - - isJSON: function() { - var str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''); - return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str); - }, - - evalJSON: function(sanitize) { - var json = this.unfilterJSON(); - try { - if (!sanitize || json.isJSON()) return eval('(' + json + ')'); - } catch (e) { } - throw new SyntaxError('Badly formed JSON string: ' + this.inspect()); - }, - - include: function(pattern) { - return this.indexOf(pattern) > -1; - }, - - startsWith: function(pattern) { - return this.indexOf(pattern) === 0; - }, - - endsWith: function(pattern) { - var d = this.length - pattern.length; - return d >= 0 && this.lastIndexOf(pattern) === d; - }, - - empty: function() { - return this == ''; - }, - - blank: function() { - return /^\s*$/.test(this); - }, - - interpolate: function(object, pattern) { - return new Template(this, pattern).evaluate(object); - } -}); - -if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, { - escapeHTML: function() { - return this.replace(/&/g,'&').replace(//g,'>'); - }, - unescapeHTML: function() { - return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); - } -}); - -String.prototype.gsub.prepareReplacement = function(replacement) { - if (Object.isFunction(replacement)) return replacement; - var template = new Template(replacement); - return function(match) { return template.evaluate(match) }; -}; - -String.prototype.parseQuery = String.prototype.toQueryParams; - -Object.extend(String.prototype.escapeHTML, { - div: document.createElement('div'), - text: document.createTextNode('') -}); - -with (String.prototype.escapeHTML) div.appendChild(text); - -var Template = Class.create({ - initialize: function(template, pattern) { - this.template = template.toString(); - this.pattern = pattern || Template.Pattern; - }, - - evaluate: function(object) { - if (Object.isFunction(object.toTemplateReplacements)) - object = object.toTemplateReplacements(); - - return this.template.gsub(this.pattern, function(match) { - if (object == null) return ''; - - var before = match[1] || ''; - if (before == '\\') return match[2]; - - var ctx = object, expr = match[3]; - var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/, match = pattern.exec(expr); - if (match == null) return before; - - while (match != null) { - var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : 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); - }.bind(this)); - } -}); -Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; - -var $break = { }; - -var Enumerable = { - each: function(iterator, context) { - var index = 0; - iterator = iterator.bind(context); - try { - this._each(function(value) { - iterator(value, index++); - }); - } catch (e) { - if (e != $break) throw e; - } - return this; - }, - - eachSlice: function(number, iterator, context) { - iterator = iterator ? iterator.bind(context) : Prototype.K; - var index = -number, slices = [], array = this.toArray(); - while ((index += number) < array.length) - slices.push(array.slice(index, index+number)); - return slices.collect(iterator, context); - }, - - all: function(iterator, context) { - iterator = iterator ? iterator.bind(context) : Prototype.K; - var result = true; - this.each(function(value, index) { - result = result && !!iterator(value, index); - if (!result) throw $break; - }); - return result; - }, - - any: function(iterator, context) { - iterator = iterator ? iterator.bind(context) : Prototype.K; - var result = false; - this.each(function(value, index) { - if (result = !!iterator(value, index)) - throw $break; - }); - return result; - }, - - collect: function(iterator, context) { - iterator = iterator ? iterator.bind(context) : Prototype.K; - var results = []; - this.each(function(value, index) { - results.push(iterator(value, index)); - }); - return results; - }, - - detect: function(iterator, context) { - iterator = iterator.bind(context); - var result; - this.each(function(value, index) { - if (iterator(value, index)) { - result = value; - throw $break; - } - }); - return result; - }, - - findAll: function(iterator, context) { - iterator = iterator.bind(context); - var results = []; - this.each(function(value, index) { - if (iterator(value, index)) - results.push(value); - }); - return results; - }, - - grep: function(filter, iterator, context) { - iterator = iterator ? iterator.bind(context) : Prototype.K; - var results = []; - - if (Object.isString(filter)) - filter = new RegExp(filter); - - this.each(function(value, index) { - if (filter.match(value)) - results.push(iterator(value, index)); - }); - return results; - }, - - include: function(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; - }, - - inGroupsOf: function(number, fillWith) { - fillWith = fillWith === undefined ? null : fillWith; - return this.eachSlice(number, function(slice) { - while(slice.length < number) slice.push(fillWith); - return slice; - }); - }, - - inject: function(memo, iterator, context) { - iterator = iterator.bind(context); - this.each(function(value, index) { - memo = iterator(memo, value, index); - }); - return memo; - }, - - invoke: function(method) { - var args = $A(arguments).slice(1); - return this.map(function(value) { - return value[method].apply(value, args); - }); - }, - - max: function(iterator, context) { - iterator = iterator ? iterator.bind(context) : Prototype.K; - var result; - this.each(function(value, index) { - value = iterator(value, index); - if (result == undefined || value >= result) - result = value; - }); - return result; - }, - - min: function(iterator, context) { - iterator = iterator ? iterator.bind(context) : Prototype.K; - var result; - this.each(function(value, index) { - value = iterator(value, index); - if (result == undefined || value < result) - result = value; - }); - return result; - }, - - partition: function(iterator, context) { - iterator = iterator ? iterator.bind(context) : Prototype.K; - var trues = [], falses = []; - this.each(function(value, index) { - (iterator(value, index) ? - trues : falses).push(value); - }); - return [trues, falses]; - }, - - pluck: function(property) { - var results = []; - this.each(function(value) { - results.push(value[property]); - }); - return results; - }, - - reject: function(iterator, context) { - iterator = iterator.bind(context); - var results = []; - this.each(function(value, index) { - if (!iterator(value, index)) - results.push(value); - }); - return results; - }, - - sortBy: function(iterator, context) { - iterator = iterator.bind(context); - return this.map(function(value, index) { - return {value: value, criteria: iterator(value, index)}; - }).sort(function(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }).pluck('value'); - }, - - toArray: function() { - return this.map(); - }, - - zip: function() { - 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)); - }); - }, - - size: function() { - return this.toArray().length; - }, - - inspect: function() { - return '#'; - } -}; - -Object.extend(Enumerable, { - map: Enumerable.collect, - find: Enumerable.detect, - select: Enumerable.findAll, - filter: Enumerable.findAll, - member: Enumerable.include, - entries: Enumerable.toArray, - every: Enumerable.all, - some: Enumerable.any -}); -function $A(iterable) { - if (!iterable) return []; - if (iterable.toArray) return iterable.toArray(); - var length = iterable.length, results = new Array(length); - while (length--) results[length] = iterable[length]; - return results; -} - -if (Prototype.Browser.WebKit) { - function $A(iterable) { - if (!iterable) return []; - if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') && - iterable.toArray) return iterable.toArray(); - var length = iterable.length, results = new Array(length); - while (length--) results[length] = iterable[length]; - return results; - } -} - -Array.from = $A; - -Object.extend(Array.prototype, Enumerable); - -if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse; - -Object.extend(Array.prototype, { - _each: function(iterator) { - for (var i = 0, length = this.length; i < length; i++) - iterator(this[i]); - }, - - clear: function() { - this.length = 0; - return this; - }, - - first: function() { - return this[0]; - }, - - last: function() { - return this[this.length - 1]; - }, - - compact: function() { - return this.select(function(value) { - return value != null; - }); - }, - - flatten: function() { - return this.inject([], function(array, value) { - return array.concat(Object.isArray(value) ? - value.flatten() : [value]); - }); - }, - - without: function() { - var values = $A(arguments); - return this.select(function(value) { - return !values.include(value); - }); - }, - - reverse: function(inline) { - return (inline !== false ? this : this.toArray())._reverse(); - }, - - reduce: function() { - return this.length > 1 ? this : this[0]; - }, - - uniq: function(sorted) { - return this.inject([], function(array, value, index) { - if (0 == index || (sorted ? array.last() != value : !array.include(value))) - array.push(value); - return array; - }); - }, - - intersect: function(array) { - return this.uniq().findAll(function(item) { - return array.detect(function(value) { return item === value }); - }); - }, - - clone: function() { - return [].concat(this); - }, - - size: function() { - return this.length; - }, - - inspect: function() { - return '[' + this.map(Object.inspect).join(', ') + ']'; - }, - - toJSON: function() { - var results = []; - this.each(function(object) { - var value = Object.toJSON(object); - if (value !== undefined) results.push(value); - }); - return '[' + results.join(', ') + ']'; - } -}); - -// use native browser JS 1.6 implementation if available -if (Object.isFunction(Array.prototype.forEach)) - Array.prototype._each = Array.prototype.forEach; - -if (!Array.prototype.indexOf) Array.prototype.indexOf = function(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; -}; - -if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(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; -}; - -Array.prototype.toArray = Array.prototype.clone; - -function $w(string) { - if (!Object.isString(string)) return []; - string = string.strip(); - return string ? string.split(/\s+/) : []; -} - -if (Prototype.Browser.Opera){ - Array.prototype.concat = function() { - var array = []; - for (var i = 0, length = this.length; i < length; i++) array.push(this[i]); - for (var i = 0, length = arguments.length; i < length; i++) { - if (Object.isArray(arguments[i])) { - for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++) - array.push(arguments[i][j]); - } else { - array.push(arguments[i]); - } - } - return array; - }; -} -Object.extend(Number.prototype, { - toColorPart: function() { - return this.toPaddedString(2, 16); - }, - - succ: function() { - return this + 1; - }, - - times: function(iterator) { - $R(0, this, true).each(iterator); - return this; - }, - - toPaddedString: function(length, radix) { - var string = this.toString(radix || 10); - return '0'.times(length - string.length) + string; - }, - - toJSON: function() { - return isFinite(this) ? this.toString() : 'null'; - } -}); - -$w('abs round ceil floor').each(function(method){ - Number.prototype[method] = Math[method].methodize(); -}); -function $H(object) { - return new Hash(object); -}; - -var Hash = Class.create(Enumerable, (function() { - if (function() { - var i = 0, Test = function(value) { this.key = value }; - Test.prototype.key = 'foo'; - for (var property in new Test('bar')) i++; - return i > 1; - }()) { - function each(iterator) { - var cache = []; - for (var key in this._object) { - var value = this._object[key]; - if (cache.include(key)) continue; - cache.push(key); - var pair = [key, value]; - pair.key = key; - pair.value = value; - iterator(pair); - } - } - } else { - 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 toQueryPair(key, value) { - if (Object.isUndefined(value)) return key; - return key + '=' + encodeURIComponent(String.interpret(value)); - } - - return { - initialize: function(object) { - this._object = Object.isHash(object) ? object.toObject() : Object.clone(object); - }, - - _each: each, - - set: function(key, value) { - return this._object[key] = value; - }, - - get: function(key) { - return this._object[key]; - }, - - unset: function(key) { - var value = this._object[key]; - delete this._object[key]; - return value; - }, - - toObject: function() { - return Object.clone(this._object); - }, - - keys: function() { - return this.pluck('key'); - }, - - values: function() { - return this.pluck('value'); - }, - - index: function(value) { - var match = this.detect(function(pair) { - return pair.value === value; - }); - return match && match.key; - }, - - merge: function(object) { - return this.clone().update(object); - }, - - update: function(object) { - return new Hash(object).inject(this, function(result, pair) { - result.set(pair.key, pair.value); - return result; - }); - }, - - toQueryString: function() { - return this.map(function(pair) { - var key = encodeURIComponent(pair.key), values = pair.value; - - if (values && typeof values == 'object') { - if (Object.isArray(values)) - return values.map(toQueryPair.curry(key)).join('&'); - } - return toQueryPair(key, values); - }).join('&'); - }, - - inspect: function() { - return '#'; - }, - - toJSON: function() { - return Object.toJSON(this.toObject()); - }, - - clone: function() { - return new Hash(this); - } - } -})()); - -Hash.prototype.toTemplateReplacements = Hash.prototype.toObject; -Hash.from = $H; -var ObjectRange = Class.create(Enumerable, { - initialize: function(start, end, exclusive) { - this.start = start; - this.end = end; - this.exclusive = exclusive; - }, - - _each: function(iterator) { - var value = this.start; - while (this.include(value)) { - iterator(value); - value = value.succ(); - } - }, - - include: function(value) { - if (value < this.start) - return false; - if (this.exclusive) - return value < this.end; - return value <= this.end; - } -}); - -var $R = function(start, end, exclusive) { - return new ObjectRange(start, end, exclusive); -}; - -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.isString(this.options.parameters)) - this.options.parameters = this.options.parameters.toQueryParams(); - } -}); - -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.clone(this.options.parameters); - - if (!['get', 'post'].include(this.method)) { - // simulate other verbs over post - params['_method'] = this.method; - this.method = 'post'; - } - - this.parameters = params; - - if (params = Object.toQueryString(params)) { - // when GET, append parameters to URL - if (this.method == 'get') - this.url += (this.url.include('?') ? '&' : '?') + params; - else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) - params += '&_='; - } - - 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'; - } - - // user-defined headers - 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); - }, - - getStatus: function() { - try { - 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 && 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') { - // avoid memory leak in MSIE: clean up - this.transport.onreadystatechange = Prototype.emptyFunction; - } - }, - - getHeader: function(name) { - try { - return this.transport.getResponseHeader(name); - } 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 = xml === undefined ? 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); - } 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'))) - return null; - try { - return this.transport.responseText.evalJSON(options.sanitizeJSON); - } 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 = options || { }; - var onComplete = options.onComplete; - options.onComplete = (function(response, param) { - this.updateContent(response.responseText); - if (Object.isFunction(onComplete)) onComplete(response, param); - }).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); - } - - if (this.success()) { - if (this.onComplete) this.onComplete.bind(this).defer(); - } - } -}); - -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 (!window.Node) var Node = { }; - -if (!Node.ELEMENT_NODE) { - // DOM level 2 ECMAScript Language Binding - 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() { - var element = this.Element; - this.Element = function(tagName, attributes) { - attributes = attributes || { }; - tagName = tagName.toLowerCase(); - var cache = Element.cache; - if (Prototype.Browser.IE && 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)); - return Element.writeAttribute(cache[tagName].cloneNode(false), attributes); - }; - Object.extend(this.Element, element || { }); -}).call(window); - -Element.cache = { }; - -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).style.display = 'none'; - return element; - }, - - show: function(element) { - $(element).style.display = ''; - return element; - }, - - remove: function(element) { - element = $(element); - element.parentNode.removeChild(element); - return element; - }, - - update: function(element, content) { - element = $(element); - if (content && content.toElement) content = content.toElement(); - if (Object.isElement(content)) return element.update().insert(content); - content = Object.toHTML(content); - element.innerHTML = content.stripScripts(); - content.evalScripts.bind(content).defer(); - return element; - }, - - 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, t, range; - - for (position in insertions) { - content = insertions[position]; - position = position.toLowerCase(); - t = Element._insertionTranslations[position]; - - if (content && content.toElement) content = content.toElement(); - if (Object.isElement(content)) { - t.insert(element, content); - continue; - } - - content = Object.toHTML(content); - - range = element.ownerDocument.createRange(); - t.initializeRange(element, range); - t.insert(element, range.createContextualFragment(content.stripScripts())); - - 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(); - var value = (element[property] || '').toString(); - if (value) result += ' ' + attribute + '=' + value.inspect(true); - }); - return result + '>'; - }, - - recursivelyCollect: function(element, property) { - element = $(element); - var elements = []; - while (element = element[property]) - if (element.nodeType == 1) - elements.push(Element.extend(element)); - return elements; - }, - - ancestors: function(element) { - return $(element).recursivelyCollect('parentNode'); - }, - - descendants: function(element) { - return $A($(element).getElementsByTagName('*')).each(Element.extend); - }, - - firstDescendant: function(element) { - element = $(element).firstChild; - while (element && element.nodeType != 1) element = element.nextSibling; - return $(element); - }, - - immediateDescendants: function(element) { - if (!(element = $(element).firstChild)) return []; - while (element && element.nodeType != 1) element = element.nextSibling; - if (element) return [element].concat($(element).nextSiblings()); - return []; - }, - - previousSiblings: function(element) { - return $(element).recursivelyCollect('previousSibling'); - }, - - nextSiblings: function(element) { - return $(element).recursivelyCollect('nextSibling'); - }, - - siblings: function(element) { - element = $(element); - return element.previousSiblings().reverse().concat(element.nextSiblings()); - }, - - match: function(element, selector) { - if (Object.isString(selector)) - selector = new Selector(selector); - return selector.match($(element)); - }, - - up: function(element, expression, index) { - element = $(element); - if (arguments.length == 1) return $(element.parentNode); - var ancestors = element.ancestors(); - return expression ? Selector.findElement(ancestors, expression, index) : - ancestors[index || 0]; - }, - - down: function(element, expression, index) { - element = $(element); - if (arguments.length == 1) return element.firstDescendant(); - var descendants = element.descendants(); - return expression ? Selector.findElement(descendants, expression, index) : - descendants[index || 0]; - }, - - previous: function(element, expression, index) { - element = $(element); - if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element)); - var previousSiblings = element.previousSiblings(); - return expression ? Selector.findElement(previousSiblings, expression, index) : - previousSiblings[index || 0]; - }, - - next: function(element, expression, index) { - element = $(element); - if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element)); - var nextSiblings = element.nextSiblings(); - return expression ? Selector.findElement(nextSiblings, expression, index) : - nextSiblings[index || 0]; - }, - - select: function() { - var args = $A(arguments), element = $(args.shift()); - return Selector.findChildElements(element, args); - }, - - adjacent: function() { - var args = $A(arguments), element = $(args.shift()); - return Selector.findChildElements(element.parentNode, args).without(element); - }, - - identify: function(element) { - element = $(element); - var id = element.readAttribute('id'), self = arguments.callee; - if (id) return id; - do { id = 'anonymous_element_' + self.counter++ } while ($(id)); - element.writeAttribute('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] = value === undefined ? true : value; - - for (var attr in attributes) { - var 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().height; - }, - - getWidth: function(element) { - return $(element).getDimensions().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(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(className) ? - 'removeClassName' : 'addClassName'](className); - }, - - // removes whitespace-only text node children - 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 (element.sourceIndex && !Prototype.Browser.Opera) { - var e = element.sourceIndex, a = ancestor.sourceIndex, - nextAncestor = ancestor.nextSibling; - if (!nextAncestor) { - do { ancestor = ancestor.parentNode; } - while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode); - } - if (nextAncestor) return (e > a && e < nextAncestor.sourceIndex); - } - - while (element = element.parentNode) - if (element == ancestor) return true; - return false; - }, - - scrollTo: function(element) { - element = $(element); - var pos = element.cumulativeOffset(); - 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) { - 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') ? - (elementStyle.styleFloat === undefined ? '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; - }, - - getDimensions: function(element) { - element = $(element); - var display = $(element).getStyle('display'); - if (display != 'none' && display != null) // Safari bug - return {width: element.offsetWidth, height: element.offsetHeight}; - - // All *Width and *Height properties give 0 on elements with display none, - // so enable the element temporarily - var els = element.style; - var originalVisibility = els.visibility; - var originalPosition = els.position; - var originalDisplay = els.display; - els.visibility = 'hidden'; - els.position = 'absolute'; - els.display = 'block'; - var originalWidth = element.clientWidth; - var originalHeight = element.clientHeight; - els.display = originalDisplay; - els.position = originalPosition; - els.visibility = originalVisibility; - return {width: originalWidth, height: originalHeight}; - }, - - makePositioned: function(element) { - element = $(element); - var pos = Element.getStyle(element, 'position'); - if (pos == 'static' || !pos) { - element._madePositioned = true; - element.style.position = 'relative'; - // Opera returns the offset relative to the positioning context, when an - // element is position relative but top and left have not been defined - if (window.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; - }, - - cumulativeOffset: function(element) { - var valueT = 0, valueL = 0; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - element = element.offsetParent; - } while (element); - return Element._returnOffset(valueL, valueT); - }, - - positionedOffset: function(element) { - var valueT = 0, valueL = 0; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - element = element.offsetParent; - if (element) { - if (element.tagName == 'BODY') break; - var p = Element.getStyle(element, 'position'); - if (p == 'relative' || p == 'absolute') break; - } - } while (element); - return Element._returnOffset(valueL, valueT); - }, - - absolutize: function(element) { - element = $(element); - if (element.getStyle('position') == 'absolute') return; - // Position.prepare(); // To be done manually by Scripty when it needs it. - - var offsets = element.positionedOffset(); - var top = offsets[1]; - var left = offsets[0]; - var width = element.clientWidth; - var height = element.clientHeight; - - element._originalLeft = left - parseFloat(element.style.left || 0); - element._originalTop = top - parseFloat(element.style.top || 0); - element._originalWidth = element.style.width; - element._originalHeight = element.style.height; - - element.style.position = 'absolute'; - element.style.top = top + 'px'; - element.style.left = left + 'px'; - element.style.width = width + 'px'; - element.style.height = height + 'px'; - return element; - }, - - relativize: function(element) { - element = $(element); - if (element.getStyle('position') == 'relative') return; - // Position.prepare(); // To be done manually by Scripty when it needs it. - - element.style.position = 'relative'; - var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); - var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); - - element.style.top = top + 'px'; - element.style.left = left + 'px'; - element.style.height = element._originalHeight; - element.style.width = element._originalWidth; - return element; - }, - - cumulativeScrollOffset: function(element) { - var valueT = 0, valueL = 0; - do { - valueT += element.scrollTop || 0; - valueL += element.scrollLeft || 0; - element = element.parentNode; - } while (element); - return Element._returnOffset(valueL, valueT); - }, - - getOffsetParent: function(element) { - if (element.offsetParent) return $(element.offsetParent); - if (element == document.body) return $(element); - - while ((element = element.parentNode) && element != document.body) - if (Element.getStyle(element, 'position') != 'static') - return $(element); - - return $(document.body); - }, - - viewportOffset: function(forElement) { - var valueT = 0, valueL = 0; - - var element = forElement; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - - // Safari fix - if (element.offsetParent == document.body && - Element.getStyle(element, 'position') == 'absolute') break; - - } while (element = element.offsetParent); - - element = forElement; - do { - if (!Prototype.Browser.Opera || element.tagName == 'BODY') { - valueT -= element.scrollTop || 0; - valueL -= element.scrollLeft || 0; - } - } while (element = element.parentNode); - - return Element._returnOffset(valueL, valueT); - }, - - clonePosition: function(element, source) { - var options = Object.extend({ - setLeft: true, - setTop: true, - setWidth: true, - setHeight: true, - offsetTop: 0, - offsetLeft: 0 - }, arguments[2] || { }); - - // find page position of source - source = $(source); - var p = source.viewportOffset(); - - // find coordinate system to use - element = $(element); - var delta = [0, 0]; - var parent = null; - // delta [0,0] will do fine with position: fixed elements, - // position:absolute needs offsetParent deltas - if (Element.getStyle(element, 'position') == 'absolute') { - parent = element.getOffsetParent(); - delta = parent.viewportOffset(); - } - - // correct by body offsets (fixes Safari) - if (parent == document.body) { - delta[0] -= document.body.offsetLeft; - delta[1] -= document.body.offsetTop; - } - - // set position - 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; - } -}; - -Element.Methods.identify.counter = 1; - -Object.extend(Element.Methods, { - getElementsBySelector: Element.Methods.select, - childElements: Element.Methods.immediateDescendants -}); - -Element._attributeTranslations = { - write: { - names: { - className: 'class', - htmlFor: 'for' - }, - values: { } - } -}; - - -if (!document.createRange || Prototype.Browser.Opera) { - Element.Methods.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 t = Element._insertionTranslations, content, position, pos, tagName; - - for (position in insertions) { - content = insertions[position]; - position = position.toLowerCase(); - pos = t[position]; - - if (content && content.toElement) content = content.toElement(); - if (Object.isElement(content)) { - pos.insert(element, content); - continue; - } - - content = Object.toHTML(content); - tagName = ((position == 'before' || position == 'after') - ? element.parentNode : element).tagName.toUpperCase(); - - if (t.tags[tagName]) { - var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); - if (position == 'top' || position == 'after') fragments.reverse(); - fragments.each(pos.insert.curry(element)); - } - else element.insertAdjacentHTML(pos.adjacency, content.stripScripts()); - - content.evalScripts.bind(content).defer(); - } - - return element; - }; -} - -if (Prototype.Browser.Opera) { - Element.Methods._getStyle = Element.Methods.getStyle; - Element.Methods.getStyle = function(element, style) { - switch(style) { - case 'left': - case 'top': - case 'right': - case 'bottom': - if (Element._getStyle(element, 'position') == 'static') return null; - default: return Element._getStyle(element, style); - } - }; - Element.Methods._readAttribute = Element.Methods.readAttribute; - Element.Methods.readAttribute = function(element, attribute) { - if (attribute == 'title') return element.title; - return Element._readAttribute(element, attribute); - }; -} - -else if (Prototype.Browser.IE) { - $w('positionedOffset getOffsetParent viewportOffset').each(function(method) { - Element.Methods[method] = Element.Methods[method].wrap( - function(proceed, element) { - element = $(element); - var position = element.getStyle('position'); - if (position != 'static') return proceed(element); - element.setStyle({ position: 'relative' }); - var value = proceed(element); - element.setStyle({ position: position }); - return value; - } - ); - }); - - Element.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 = { - read: { - names: { - 'class': 'className', - 'for': 'htmlFor' - }, - values: { - _getAttr: function(element, attribute) { - return element.getAttribute(attribute, 2); - }, - _getAttrNode: function(element, attribute) { - var node = element.getAttributeNode(attribute); - return node ? node.value : ""; - }, - _getEv: function(element, attribute) { - var attribute = element.getAttribute(attribute); - return attribute ? attribute.toString().slice(23, -2) : null; - }, - _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.clone(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').each(function(attr) { - Element._attributeTranslations.write.names[attr.toLowerCase()] = attr; - Element._attributeTranslations.has[attr.toLowerCase()] = attr; - }); - - (function(v) { - Object.extend(v, { - href: v._getAttr, - src: v._getAttr, - 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); -} - -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 == 'IMG' && element.width) { - element.width++; element.width--; - } else try { - var n = document.createTextNode(' '); - element.appendChild(n); - element.removeChild(n); - } catch (e) { } - - return element; - }; - - // Safari returns margins on body which is incorrect if the child is absolutely - // positioned. For performance reasons, redefine Position.cumulativeOffset for - // KHTML/WebKit only. - Element.Methods.cumulativeOffset = function(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 Element._returnOffset(valueL, valueT); - }; -} - -if (Prototype.Browser.IE || Prototype.Browser.Opera) { - // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements - Element.Methods.update = function(element, content) { - element = $(element); - - 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 in Element._insertionTranslations.tags) { - $A(element.childNodes).each(function(node) { element.removeChild(node) }); - Element._getContentFromAnonymousElement(tagName, content.stripScripts()) - .each(function(node) { element.appendChild(node) }); - } - else element.innerHTML = content.stripScripts(); - - content.evalScripts.bind(content).defer(); - return element; - }; -} - -if (document.createElement('div').outerHTML) { - 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(); - var 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) { - var div = new Element('div'), t = Element._insertionTranslations.tags[tagName]; - div.innerHTML = t[0] + html + t[1]; - t[2].times(function() { div = div.firstChild }); - return $A(div.childNodes); -}; - -Element._insertionTranslations = { - before: { - adjacency: 'beforeBegin', - insert: function(element, node) { - element.parentNode.insertBefore(node, element); - }, - initializeRange: function(element, range) { - range.setStartBefore(element); - } - }, - top: { - adjacency: 'afterBegin', - insert: function(element, node) { - element.insertBefore(node, element.firstChild); - }, - initializeRange: function(element, range) { - range.selectNodeContents(element); - range.collapse(true); - } - }, - bottom: { - adjacency: 'beforeEnd', - insert: function(element, node) { - element.appendChild(node); - } - }, - after: { - adjacency: 'afterEnd', - insert: function(element, node) { - element.parentNode.insertBefore(node, element.nextSibling); - }, - initializeRange: function(element, range) { - range.setStartAfter(element); - } - }, - tags: { - TABLE: ['', '
', 1], - TBODY: ['', '
', 2], - TR: ['', '
', 3], - TD: ['
', '
', 4], - SELECT: ['', 1] - } -}; - -(function() { - this.bottom.initializeRange = this.top.initializeRange; - Object.extend(this.tags, { - THEAD: this.tags.TBODY, - TFOOT: this.tags.TBODY, - TH: this.tags.TD - }); -}).call(Element._insertionTranslations); - -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); - -if (!Prototype.BrowserFeatures.ElementExtensions && - document.createElement('div').__proto__) { - window.HTMLElement = { }; - window.HTMLElement.prototype = document.createElement('div').__proto__; - Prototype.BrowserFeatures.ElementExtensions = true; -} - -Element.extend = (function() { - if (Prototype.BrowserFeatures.SpecificElementExtensions) - return Prototype.K; - - var Methods = { }, ByTag = Element.Methods.ByTag; - - var extend = Object.extend(function(element) { - if (!element || element._extendedByPrototype || - element.nodeType != 1 || element == window) return element; - - var methods = Object.clone(Methods), - tagName = element.tagName, property, value; - - // extend methods for specific tags - if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]); - - for (property in methods) { - value = methods[property]; - if (Object.isFunction(value) && !(property in element)) - element[property] = value.methodize(); - } - - element._extendedByPrototype = Prototype.emptyFunction; - return element; - - }, { - refresh: function() { - // extend methods for all tags (Safari doesn't need this) - if (!Prototype.BrowserFeatures.ElementExtensions) { - Object.extend(Methods, Element.Methods); - Object.extend(Methods, Element.Methods.Simulated); - } - } - }); - - extend.refresh(); - return extend; -})(); - -Element.hasAttribute = function(element, attribute) { - if (element.hasAttribute) return element.hasAttribute(attribute); - return Element.Methods.Simulated.hasAttribute(element, attribute); -}; - -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) - }); - } - - 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]; - - window[klass] = { }; - window[klass].prototype = document.createElement(tagName).__proto__; - return window[klass]; - } - - if (F.ElementExtensions) { - copy(Element.Methods, HTMLElement.prototype); - copy(Element.Methods.Simulated, HTMLElement.prototype, 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() { - var dimensions = { }; - $w('width height').each(function(d) { - var D = d.capitalize(); - dimensions[d] = self['inner' + D] || - (document.documentElement['client' + D] || document.body['client' + D]); - }); - return dimensions; - }, - - getWidth: function() { - return this.getDimensions().width; - }, - - getHeight: function() { - return this.getDimensions().height; - }, - - getScrollOffsets: function() { - return Element._returnOffset( - window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, - window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop); - } -}; -/* Portions of the Selector class are derived from Jack Slocum’s DomQuery, - * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style - * license. Please see http://www.yui-ext.com/ for more information. */ - -var Selector = Class.create({ - initialize: function(expression) { - this.expression = expression.strip(); - this.compileMatcher(); - }, - - compileMatcher: function() { - // Selectors with namespaced attributes can't use the XPath version - if (Prototype.BrowserFeatures.XPath && !(/(\[[\w-]*?:|:checked)/).test(this.expression)) - return this.compileXPathMatcher(); - - var e = this.expression, ps = Selector.patterns, h = Selector.handlers, - c = Selector.criteria, le, p, m; - - if (Selector._cache[e]) { - this.matcher = Selector._cache[e]; - return; - } - - this.matcher = ["this.matcher = function(root) {", - "var r = root, h = Selector.handlers, c = false, n;"]; - - while (e && le != e && (/\S/).test(e)) { - le = e; - for (var i in ps) { - p = ps[i]; - if (m = e.match(p)) { - this.matcher.push(Object.isFunction(c[i]) ? c[i](m) : - new Template(c[i]).evaluate(m)); - e = e.replace(m[0], ''); - break; - } - } - } - - this.matcher.push("return h.unique(n);\n}"); - eval(this.matcher.join('\n')); - Selector._cache[this.expression] = this.matcher; - }, - - compileXPathMatcher: function() { - var e = this.expression, ps = Selector.patterns, - x = Selector.xpath, le, m; - - if (Selector._cache[e]) { - this.xpath = Selector._cache[e]; return; - } - - this.matcher = ['.//*']; - while (e && le != e && (/\S/).test(e)) { - le = e; - for (var i in ps) { - if (m = e.match(ps[i])) { - this.matcher.push(Object.isFunction(x[i]) ? x[i](m) : - new Template(x[i]).evaluate(m)); - e = e.replace(m[0], ''); - break; - } - } - } - - this.xpath = this.matcher.join(''); - Selector._cache[this.expression] = this.xpath; - }, - - findElements: function(root) { - root = root || document; - if (this.xpath) return document._getElementsByXPath(this.xpath, root); - return this.matcher(root); - }, - - match: function(element) { - this.tokens = []; - - var e = this.expression, ps = Selector.patterns, as = Selector.assertions; - var le, p, m; - - while (e && le !== e && (/\S/).test(e)) { - le = e; - for (var i in ps) { - p = ps[i]; - if (m = e.match(p)) { - // use the Selector.assertions methods unless the selector - // is too complex. - if (as[i]) { - this.tokens.push([i, Object.clone(m)]); - e = e.replace(m[0], ''); - } else { - // reluctantly do a document-wide search - // and look for a match in the array - return this.findElements(document).include(element); - } - } - } - } - - var match = true, name, matches; - for (var i = 0, token; token = this.tokens[i]; i++) { - name = token[0], matches = token[1]; - if (!Selector.assertions[name](element, matches)) { - match = false; break; - } - } - - return match; - }, - - toString: function() { - return this.expression; - }, - - inspect: function() { - return "#"; - } -}); - -Object.extend(Selector, { - _cache: { }, - - xpath: { - descendant: "//*", - child: "/*", - adjacent: "/following-sibling::*[1]", - laterSibling: '/following-sibling::*', - tagName: function(m) { - if (m[1] == '*') return ''; - return "[local-name()='" + m[1].toLowerCase() + - "' or local-name()='" + m[1].toUpperCase() + "']"; - }, - className: "[contains(concat(' ', @class, ' '), ' #{1} ')]", - id: "[@id='#{1}']", - attrPresence: "[@#{1}]", - attr: function(m) { - m[3] = m[5] || m[6]; - return new Template(Selector.xpath.operators[m[2]]).evaluate(m); - }, - pseudo: function(m) { - var h = Selector.xpath.pseudos[m[1]]; - if (!h) return ''; - if (Object.isFunction(h)) return h(m); - return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m); - }, - operators: { - '=': "[@#{1}='#{3}']", - '!=': "[@#{1}!='#{3}']", - '^=': "[starts-with(@#{1}, '#{3}')]", - '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']", - '*=': "[contains(@#{1}, '#{3}')]", - '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]", - '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]" - }, - pseudos: { - 'first-child': '[not(preceding-sibling::*)]', - 'last-child': '[not(following-sibling::*)]', - 'only-child': '[not(preceding-sibling::* or following-sibling::*)]', - 'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]", - 'checked': "[@checked]", - 'disabled': "[@disabled]", - 'enabled': "[not(@disabled)]", - 'not': function(m) { - var e = m[6], p = Selector.patterns, - x = Selector.xpath, le, m, v; - - var exclusion = []; - while (e && le != e && (/\S/).test(e)) { - le = e; - for (var i in p) { - if (m = e.match(p[i])) { - v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m); - exclusion.push("(" + v.substring(1, v.length - 1) + ")"); - e = e.replace(m[0], ''); - break; - } - } - } - return "[not(" + exclusion.join(" and ") + ")]"; - }, - 'nth-child': function(m) { - return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m); - }, - 'nth-last-child': function(m) { - return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m); - }, - 'nth-of-type': function(m) { - return Selector.xpath.pseudos.nth("position() ", m); - }, - 'nth-last-of-type': function(m) { - return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m); - }, - 'first-of-type': function(m) { - m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m); - }, - 'last-of-type': function(m) { - m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m); - }, - 'only-of-type': function(m) { - var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m); - }, - nth: function(fragment, m) { - var mm, formula = m[6], predicate; - if (formula == 'even') formula = '2n+0'; - if (formula == 'odd') formula = '2n+1'; - if (mm = formula.match(/^(\d+)$/)) // digit only - return '[' + fragment + "= " + mm[1] + ']'; - if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b - if (mm[1] == "-") mm[1] = -1; - var a = mm[1] ? Number(mm[1]) : 1; - var b = mm[2] ? Number(mm[2]) : 0; - predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " + - "((#{fragment} - #{b}) div #{a} >= 0)]"; - return new Template(predicate).evaluate({ - fragment: fragment, a: a, b: b }); - } - } - } - }, - - criteria: { - tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;', - className: 'n = h.className(n, r, "#{1}", c); c = false;', - id: 'n = h.id(n, r, "#{1}", c); c = false;', - attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;', - attr: function(m) { - m[3] = (m[5] || m[6]); - return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m); - }, - pseudo: function(m) { - if (m[6]) m[6] = m[6].replace(/"/g, '\\"'); - return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m); - }, - descendant: 'c = "descendant";', - child: 'c = "child";', - adjacent: 'c = "adjacent";', - laterSibling: 'c = "laterSibling";' - }, - - patterns: { - // combinators must be listed first - // (and descendant needs to be last combinator) - laterSibling: /^\s*~\s*/, - child: /^\s*>\s*/, - adjacent: /^\s*\+\s*/, - descendant: /^\s/, - - // selectors follow - tagName: /^\s*(\*|[\w\-]+)(\b|$)?/, - id: /^#([\w\-\*]+)(\b|$)/, - className: /^\.([\w\-\*]+)(\b|$)/, - pseudo: /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s)|(?=:))/, - attrPresence: /^\[([\w]+)\]/, - attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/ - }, - - // for Selector.match and Element#match - assertions: { - tagName: function(element, matches) { - return matches[1].toUpperCase() == element.tagName.toUpperCase(); - }, - - className: function(element, matches) { - return Element.hasClassName(element, matches[1]); - }, - - id: function(element, matches) { - return element.id === matches[1]; - }, - - attrPresence: function(element, matches) { - return Element.hasAttribute(element, matches[1]); - }, - - attr: function(element, matches) { - var nodeValue = Element.readAttribute(element, matches[1]); - return Selector.operators[matches[2]](nodeValue, matches[3]); - } - }, - - handlers: { - // UTILITY FUNCTIONS - // joins two collections - concat: function(a, b) { - for (var i = 0, node; node = b[i]; i++) - a.push(node); - return a; - }, - - // marks an array of nodes for counting - mark: function(nodes) { - for (var i = 0, node; node = nodes[i]; i++) - node._counted = true; - return nodes; - }, - - unmark: function(nodes) { - for (var i = 0, node; node = nodes[i]; i++) - node._counted = undefined; - return nodes; - }, - - // mark each child node with its position (for nth calls) - // "ofType" flag indicates whether we're indexing for nth-of-type - // rather than nth-child - index: function(parentNode, reverse, ofType) { - parentNode._counted = true; - if (reverse) { - for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) { - var node = nodes[i]; - if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++; - } - } else { - for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++) - if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++; - } - }, - - // filters out duplicates and extends all nodes - unique: function(nodes) { - if (nodes.length == 0) return nodes; - var results = [], n; - for (var i = 0, l = nodes.length; i < l; i++) - if (!(n = nodes[i])._counted) { - n._counted = true; - results.push(Element.extend(n)); - } - return Selector.handlers.unmark(results); - }, - - // COMBINATOR FUNCTIONS - descendant: function(nodes) { - var h = Selector.handlers; - for (var i = 0, results = [], node; node = nodes[i]; i++) - h.concat(results, node.getElementsByTagName('*')); - return results; - }, - - child: function(nodes) { - var h = Selector.handlers; - for (var i = 0, results = [], node; node = nodes[i]; i++) { - for (var j = 0, children = [], child; child = node.childNodes[j]; j++) - if (child.nodeType == 1 && child.tagName != '!') results.push(child); - } - return results; - }, - - adjacent: function(nodes) { - for (var i = 0, results = [], node; node = nodes[i]; i++) { - var next = this.nextElementSibling(node); - if (next) results.push(next); - } - return results; - }, - - laterSibling: function(nodes) { - var h = Selector.handlers; - for (var i = 0, results = [], node; node = nodes[i]; i++) - h.concat(results, Element.nextSiblings(node)); - return results; - }, - - nextElementSibling: function(node) { - while (node = node.nextSibling) - if (node.nodeType == 1) return node; - return null; - }, - - previousElementSibling: function(node) { - while (node = node.previousSibling) - if (node.nodeType == 1) return node; - return null; - }, - - // TOKEN FUNCTIONS - tagName: function(nodes, root, tagName, combinator) { - tagName = tagName.toUpperCase(); - var results = [], h = Selector.handlers; - if (nodes) { - if (combinator) { - // fastlane for ordinary descendant combinators - if (combinator == "descendant") { - for (var i = 0, node; node = nodes[i]; i++) - h.concat(results, node.getElementsByTagName(tagName)); - return results; - } else nodes = this[combinator](nodes); - if (tagName == "*") return nodes; - } - for (var i = 0, node; node = nodes[i]; i++) - if (node.tagName.toUpperCase() == tagName) results.push(node); - return results; - } else return root.getElementsByTagName(tagName); - }, - - id: function(nodes, root, id, combinator) { - var targetNode = $(id), h = Selector.handlers; - if (!targetNode) return []; - if (!nodes && root == document) return [targetNode]; - if (nodes) { - if (combinator) { - if (combinator == 'child') { - for (var i = 0, node; node = nodes[i]; i++) - if (targetNode.parentNode == node) return [targetNode]; - } else if (combinator == 'descendant') { - for (var i = 0, node; node = nodes[i]; i++) - if (Element.descendantOf(targetNode, node)) return [targetNode]; - } else if (combinator == 'adjacent') { - for (var i = 0, node; node = nodes[i]; i++) - if (Selector.handlers.previousElementSibling(targetNode) == node) - return [targetNode]; - } else nodes = h[combinator](nodes); - } - for (var i = 0, node; node = nodes[i]; i++) - if (node == targetNode) return [targetNode]; - return []; - } - return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : []; - }, - - className: function(nodes, root, className, combinator) { - if (nodes && combinator) nodes = this[combinator](nodes); - return Selector.handlers.byClassName(nodes, root, className); - }, - - byClassName: function(nodes, root, className) { - if (!nodes) nodes = Selector.handlers.descendant([root]); - var needle = ' ' + className + ' '; - for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) { - nodeClassName = node.className; - if (nodeClassName.length == 0) continue; - if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle)) - results.push(node); - } - return results; - }, - - attrPresence: function(nodes, root, attr) { - if (!nodes) nodes = root.getElementsByTagName("*"); - var results = []; - for (var i = 0, node; node = nodes[i]; i++) - if (Element.hasAttribute(node, attr)) results.push(node); - return results; - }, - - attr: function(nodes, root, attr, value, operator) { - if (!nodes) nodes = root.getElementsByTagName("*"); - var handler = Selector.operators[operator], results = []; - for (var i = 0, node; node = nodes[i]; i++) { - var nodeValue = Element.readAttribute(node, attr); - if (nodeValue === null) continue; - if (handler(nodeValue, value)) results.push(node); - } - return results; - }, - - pseudo: function(nodes, name, value, root, combinator) { - if (nodes && combinator) nodes = this[combinator](nodes); - if (!nodes) nodes = root.getElementsByTagName("*"); - return Selector.pseudos[name](nodes, value, root); - } - }, - - pseudos: { - 'first-child': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) { - if (Selector.handlers.previousElementSibling(node)) continue; - results.push(node); - } - return results; - }, - 'last-child': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) { - if (Selector.handlers.nextElementSibling(node)) continue; - results.push(node); - } - return results; - }, - 'only-child': function(nodes, value, root) { - var h = Selector.handlers; - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (!h.previousElementSibling(node) && !h.nextElementSibling(node)) - results.push(node); - return results; - }, - 'nth-child': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, formula, root); - }, - 'nth-last-child': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, formula, root, true); - }, - 'nth-of-type': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, formula, root, false, true); - }, - 'nth-last-of-type': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, formula, root, true, true); - }, - 'first-of-type': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, "1", root, false, true); - }, - 'last-of-type': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, "1", root, true, true); - }, - 'only-of-type': function(nodes, formula, root) { - var p = Selector.pseudos; - return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root); - }, - - // handles the an+b logic - getIndices: function(a, b, total) { - if (a == 0) return b > 0 ? [b] : []; - return $R(1, total).inject([], function(memo, i) { - if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i); - return memo; - }); - }, - - // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type - nth: function(nodes, formula, root, reverse, ofType) { - if (nodes.length == 0) return []; - if (formula == 'even') formula = '2n+0'; - if (formula == 'odd') formula = '2n+1'; - var h = Selector.handlers, results = [], indexed = [], m; - h.mark(nodes); - for (var i = 0, node; node = nodes[i]; i++) { - if (!node.parentNode._counted) { - h.index(node.parentNode, reverse, ofType); - indexed.push(node.parentNode); - } - } - if (formula.match(/^\d+$/)) { // just a number - formula = Number(formula); - for (var i = 0, node; node = nodes[i]; i++) - if (node.nodeIndex == formula) results.push(node); - } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b - if (m[1] == "-") m[1] = -1; - var a = m[1] ? Number(m[1]) : 1; - var b = m[2] ? Number(m[2]) : 0; - var indices = Selector.pseudos.getIndices(a, b, nodes.length); - for (var i = 0, node, l = indices.length; node = nodes[i]; i++) { - for (var j = 0; j < l; j++) - if (node.nodeIndex == indices[j]) results.push(node); - } - } - h.unmark(nodes); - h.unmark(indexed); - return results; - }, - - 'empty': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) { - // IE treats comments as element nodes - if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue; - results.push(node); - } - return results; - }, - - 'not': function(nodes, selector, root) { - var h = Selector.handlers, selectorType, m; - var exclusions = new Selector(selector).findElements(root); - h.mark(exclusions); - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (!node._counted) results.push(node); - h.unmark(exclusions); - return results; - }, - - 'enabled': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (!node.disabled) results.push(node); - return results; - }, - - 'disabled': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (node.disabled) results.push(node); - return results; - }, - - 'checked': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (node.checked) results.push(node); - return results; - } - }, - - operators: { - '=': function(nv, v) { return nv == v; }, - '!=': function(nv, v) { return nv != v; }, - '^=': function(nv, v) { return nv.startsWith(v); }, - '$=': function(nv, v) { return nv.endsWith(v); }, - '*=': function(nv, v) { return nv.include(v); }, - '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); }, - '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); } - }, - - matchElements: function(elements, expression) { - var matches = new Selector(expression).findElements(), h = Selector.handlers; - h.mark(matches); - for (var i = 0, results = [], element; element = elements[i]; i++) - if (element._counted) results.push(element); - h.unmark(matches); - return results; - }, - - findElement: function(elements, expression, index) { - if (Object.isNumber(expression)) { - index = expression; expression = false; - } - return Selector.matchElements(elements, expression || '*')[index || 0]; - }, - - findChildElements: function(element, expressions) { - var exprs = expressions.join(','), expressions = []; - exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) { - expressions.push(m[1].strip()); - }); - var results = [], h = Selector.handlers; - for (var i = 0, l = expressions.length, selector; i < l; i++) { - selector = new Selector(expressions[i].strip()); - h.concat(results, selector.findElements(element)); - } - return (l > 1) ? h.unique(results) : results; - } -}); - -function $$() { - return Selector.findChildElements(document, $A(arguments)); -} -var Form = { - reset: function(form) { - $(form).reset(); - return form; - }, - - serializeElements: function(elements, options) { - if (typeof options != 'object') options = { hash: !!options }; - else if (options.hash === undefined) options.hash = true; - var key, value, submitted = false, submit = options.submit; - - var data = elements.inject({ }, function(result, element) { - if (!element.disabled && element.name) { - key = element.name; value = $(element).getValue(); - if (value != null && (element.type != 'submit' || (!submitted && - submit !== false && (!submit || key == submit) && (submitted = true)))) { - if (key in result) { - // a key is already present; construct an array of values - if (!Object.isArray(result[key])) result[key] = [result[key]]; - result[key].push(value); - } - else result[key] = value; - } - } - return result; - }); - - return options.hash ? data : Object.toQueryString(data); - } -}; - -Form.Methods = { - serialize: function(form, options) { - return Form.serializeElements(Form.getElements(form), options); - }, - - getElements: function(form) { - return $A($(form).getElementsByTagName('*')).inject([], - function(elements, child) { - if (Form.Element.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'].include(element.tagName.toLowerCase()); - }); - }, - - focusFirstElement: function(form) { - form = $(form); - form.findFirstElement().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'].include(element.type))) - element.select(); - } catch (e) { } - return element; - }, - - disable: function(element) { - element = $(element); - element.blur(); - 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 = { - input: function(element, value) { - switch (element.type.toLowerCase()) { - case 'checkbox': - case 'radio': - return Form.Element.Serializers.inputSelector(element, value); - default: - return Form.Element.Serializers.textarea(element, value); - } - }, - - inputSelector: function(element, value) { - if (value === undefined) return element.checked ? element.value : null; - else element.checked = !!value; - }, - - textarea: function(element, value) { - if (value === undefined) return element.value; - else element.value = value; - }, - - select: function(element, index) { - if (index === undefined) - return this[element.type == 'select-one' ? - 'selectOne' : 'selectMany'](element); - else { - var opt, value, single = !Object.isArray(index); - for (var i = 0, length = element.length; i < length; i++) { - opt = element.options[i]; - value = this.optionValue(opt); - if (single) { - if (value == index) { - opt.selected = true; - return; - } - } - else opt.selected = index.include(value); - } - } - }, - - selectOne: function(element) { - var index = element.selectedIndex; - return index >= 0 ? this.optionValue(element.options[index]) : null; - }, - - selectMany: function(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(this.optionValue(opt)); - } - return values; - }, - - optionValue: function(opt) { - // extend element because hasAttribute may not be native - return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text; - } -}; - -/*--------------------------------------------------------------------------*/ - -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); - } -}); -if (!window.Event) var Event = { }; - -Object.extend(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: { }, - - relatedTarget: function(event) { - var element; - switch(event.type) { - case 'mouseover': element = event.fromElement; break; - case 'mouseout': element = event.toElement; break; - default: return null; - } - return Element.extend(element); - } -}); - -Event.Methods = (function() { - var isButton; - - if (Prototype.Browser.IE) { - var buttonMap = { 0: 1, 1: 4, 2: 2 }; - isButton = function(event, code) { - return event.button == buttonMap[code]; - }; - - } else if (Prototype.Browser.WebKit) { - isButton = function(event, code) { - switch (code) { - case 0: return event.which == 1 && !event.metaKey; - case 1: return event.which == 1 && event.metaKey; - default: return false; - } - }; - - } else { - isButton = function(event, code) { - return event.which ? (event.which === code + 1) : (event.button === code); - }; - } - - return { - isLeftClick: function(event) { return isButton(event, 0) }, - isMiddleClick: function(event) { return isButton(event, 1) }, - isRightClick: function(event) { return isButton(event, 2) }, - - element: function(event) { - var node = Event.extend(event).target; - return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node); - }, - - findElement: function(event, expression) { - var element = Event.element(event); - return element.match(expression) ? element : element.up(expression); - }, - - pointer: function(event) { - return { - x: event.pageX || (event.clientX + - (document.documentElement.scrollLeft || document.body.scrollLeft)), - y: event.pageY || (event.clientY + - (document.documentElement.scrollTop || document.body.scrollTop)) - }; - }, - - pointerX: function(event) { return Event.pointer(event).x }, - pointerY: function(event) { return Event.pointer(event).y }, - - stop: function(event) { - Event.extend(event); - event.preventDefault(); - event.stopPropagation(); - event.stopped = true; - } - }; -})(); - -Event.extend = (function() { - var methods = Object.keys(Event.Methods).inject({ }, function(m, name) { - m[name] = Event.Methods[name].methodize(); - return m; - }); - - if (Prototype.Browser.IE) { - Object.extend(methods, { - stopPropagation: function() { this.cancelBubble = true }, - preventDefault: function() { this.returnValue = false }, - inspect: function() { return "[object Event]" } - }); - - return function(event) { - if (!event) return false; - if (event._extendedByPrototype) return event; - - event._extendedByPrototype = Prototype.emptyFunction; - var pointer = Event.pointer(event); - Object.extend(event, { - target: event.srcElement, - relatedTarget: Event.relatedTarget(event), - pageX: pointer.x, - pageY: pointer.y - }); - return Object.extend(event, methods); - }; - - } else { - Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__; - Object.extend(Event.prototype, methods); - return Prototype.K; - } -})(); - -Object.extend(Event, (function() { - var cache = Event.cache; - - function getEventID(element) { - if (element._eventID) return element._eventID; - arguments.callee.id = arguments.callee.id || 1; - return element._eventID = ++arguments.callee.id; - } - - function getDOMEventName(eventName) { - if (eventName && eventName.include(':')) return "dataavailable"; - return eventName; - } - - function getCacheForID(id) { - return cache[id] = cache[id] || { }; - } - - function getWrappersForEventName(id, eventName) { - var c = getCacheForID(id); - return c[eventName] = c[eventName] || []; - } - - function createWrapper(element, eventName, handler) { - var id = getEventID(element); - var c = getWrappersForEventName(id, eventName); - if (c.pluck("handler").include(handler)) return false; - - var wrapper = function(event) { - if (!Event || !Event.extend || - (event.eventName && event.eventName != eventName)) - return false; - - Event.extend(event); - handler.call(element, event) - }; - - wrapper.handler = handler; - c.push(wrapper); - return wrapper; - } - - function findWrapper(id, eventName, handler) { - var c = getWrappersForEventName(id, eventName); - return c.find(function(wrapper) { return wrapper.handler == handler }); - } - - function destroyWrapper(id, eventName, handler) { - var c = getCacheForID(id); - if (!c[eventName]) return false; - c[eventName] = c[eventName].without(findWrapper(id, eventName, handler)); - } - - function destroyCache() { - for (var id in cache) - for (var eventName in cache[id]) - cache[id][eventName] = null; - } - - if (window.attachEvent) { - window.attachEvent("onunload", destroyCache); - } - - return { - observe: function(element, eventName, handler) { - element = $(element); - var name = getDOMEventName(eventName); - - var wrapper = createWrapper(element, eventName, handler); - if (!wrapper) return element; - - if (element.addEventListener) { - element.addEventListener(name, wrapper, false); - } else { - element.attachEvent("on" + name, wrapper); - } - - return element; - }, - - stopObserving: function(element, eventName, handler) { - element = $(element); - var id = getEventID(element), name = getDOMEventName(eventName); - - if (!handler && eventName) { - getWrappersForEventName(id, eventName).each(function(wrapper) { - element.stopObserving(eventName, wrapper.handler); - }); - return element; - - } else if (!eventName) { - Object.keys(getCacheForID(id)).each(function(eventName) { - element.stopObserving(eventName); - }); - return element; - } - - var wrapper = findWrapper(id, eventName, handler); - if (!wrapper) return element; - - if (element.removeEventListener) { - element.removeEventListener(name, wrapper, false); - } else { - element.detachEvent("on" + name, wrapper); - } - - destroyWrapper(id, eventName, handler); - - return element; - }, - - fire: function(element, eventName, memo) { - element = $(element); - if (element == document && document.createEvent && !element.dispatchEvent) - element = document.documentElement; - - if (document.createEvent) { - var event = document.createEvent("HTMLEvents"); - event.initEvent("dataavailable", true, true); - } else { - var event = document.createEventObject(); - event.eventType = "ondataavailable"; - } - - event.eventName = eventName; - event.memo = memo || { }; - - if (document.createEvent) { - element.dispatchEvent(event); - } else { - element.fireEvent(event.eventType, event); - } - - return event; - } - }; -})()); - -Object.extend(Event, Event.Methods); - -Element.addMethods({ - fire: Event.fire, - observe: Event.observe, - stopObserving: Event.stopObserving -}); - -Object.extend(document, { - fire: Element.Methods.fire.methodize(), - observe: Element.Methods.observe.methodize(), - stopObserving: Element.Methods.stopObserving.methodize() -}); - -(function() { - /* Support for the DOMContentLoaded event is based on work by Dan Webb, - Matthias Miller, Dean Edwards and John Resig. */ - - var timer, fired = false; - - function fireContentLoadedEvent() { - if (fired) return; - if (timer) window.clearInterval(timer); - document.fire("dom:loaded"); - fired = true; - } - - if (document.addEventListener) { - if (Prototype.Browser.WebKit) { - timer = window.setInterval(function() { - if (/loaded|complete/.test(document.readyState)) - fireContentLoadedEvent(); - }, 0); - - Event.observe(window, "load", fireContentLoadedEvent); - - } else { - document.addEventListener("DOMContentLoaded", - fireContentLoadedEvent, false); - } - - } else { - document.write(" - - - - - -

-

- -
- -
- -
- -
-
- - - - - - - - \ No newline at end of file diff --git a/test/sidebar.html b/test/sidebar.html deleted file mode 100644 index ef35b21..0000000 --- a/test/sidebar.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - EJS Tests - - - -

EJS Tests

- -

- -

Rendering

- -

Templating

- -

Views

- - - - - \ No newline at end of file diff --git a/test/templates/test.ejs b/test/templates/test.ejs deleted file mode 100644 index d0ee012..0000000 --- a/test/templates/test.ejs +++ /dev/null @@ -1,3 +0,0 @@ -
    <% animals.each(function(animal){%> -
  • <%= animal %>
  • -<%});%>
\ No newline at end of file diff --git a/test/tests/rendering.js b/test/tests/rendering.js deleted file mode 100644 index dddb54e..0000000 --- a/test/tests/rendering.js +++ /dev/null @@ -1,94 +0,0 @@ -JMVCTest = { - APPLICATION_NAME : 'EJS', - TEST_DESCRIPTION : 'This tests ejs', - perform_test : function() { - new Test.Unit.Runner({ - - setup: function() { - this.animals = ['sloth', 'bear', 'monkey'] - this.square_brackets = "
    [% this.animals.each(function(animal){%]" + - "
  • [%= animal %]
  • " + - "[%});%]
" - this.square_brackets_no_this = "
    [% animals.each(function(animal){%]" + - "
  • [%= animal %]
  • " + - "[%});%]
" - this.angle_brackets_no_this = "
    <% animals.each(function(animal){%>" + - "
  • <%= animal %>
  • " + - "<%});%>
"; - }, - teardown: function() { - }, - test_render_with_left_bracket: function() { with(this) { - var compiled = new EJS({text: this.square_brackets, type: '['}).render({animals: this.animals}) - assertEqual("
  • sloth
  • bear
  • monkey
", compiled) - }}, - test_render_with_process: function() { with(this) { - var compiled = new EJS({text: this.square_brackets_no_this, type: '['}).render({animals: this.animals}) ; - assertEqual("
  • sloth
  • bear
  • monkey
", compiled) - }}, - test_render_with_carrot: function() { with(this) { - var compiled = new EJS({text: this.angle_brackets_no_this}).render({animals: this.animals}) ; - - assertEqual("
  • sloth
  • bear
  • monkey
", compiled) - }}, - test_update : function() { with(this) { - var compiled = new EJS({text: this.angle_brackets_no_this}).update( 'update_me', {animals: this.animals} ); - assertEqual("
  • sloth
  • bear
  • monkey
", document.getElementById('update_me').innerHTML.toLowerCase().replace(/\r\n/g, '') ) - }}, - test_render_with_double: function() { with(this) { - var text = "<%% replace_me %>"+ - "
    <% animals.each(function(animal){%>" + - "
  • <%= animal %>
  • " + - "<%});%>
"; - var compiled = new EJS({text: text}).render({animals: this.animals}) ; - assertEqual("<% replace_me %>
  • sloth
  • bear
  • monkey
", compiled) - }}, - test_render_with_comment: function() { with(this) { - - var text = "<%# replace_me %>"+ - "
    <% animals.each(function(animal){%>" + - "
  • <%= animal %>
  • " + - "<%});%>
"; - var compiled = new EJS({text: text}).render({animals: this.animals}) ; - assertEqual("
  • sloth
  • bear
  • monkey
", compiled) - }}, - test_render_with_double_equal: function() { with(this) { - var text = "<%%= replace_me %>"+ - "
    <% animals.each(function(animal){%>" + - "
  • <%= animal %>
  • " + - "<%});%>
"; - var compiled = new EJS({text: text}).render({animals: this.animals}) ; - assertEqual("<%= replace_me %>
  • sloth
  • bear
  • monkey
", compiled) - }}, - test_error_forgot_opening_carrot: function() { with(this) { - - var text = "
    <% animals.each(function(animal){%>" + - "
  • animal %>
  • " + - "<%});%>
"; - var compiled = new EJS({text: text}).render({animals: this.animals}) ; - assertEqual("
  • animal %>
  • animal %>
  • animal %>
", compiled) - }}, - test_with_elements : function(){with(this){ - var compiled = new EJS({element: 'test_template'}).render({animals: this.animals}) ; - assertEqual("
    \n\t
  • sloth
  • \n\n\t
  • bear
  • \n\n\t
  • monkey
  • \n
", compiled) - - var compiled = new EJS({element: document.getElementById('test_template') }).render({animals: this.animals}) ; - assertEqual("
    \n\t
  • sloth
  • \n\n\t
  • bear
  • \n\n\t
  • monkey
  • \n
", compiled) - - }}, - test_error_forgot_closing_carrot: function() { with(this) { - - var text = "
    <% animals.each(function(animal){%>\n" + - "
  • <% animal %
  • \n" + - "<%});%>
"; - try{ - var compiled = new EJS({text: text}) ; - assert(false,'An error should have been reported') - }catch(e){ - assertEqual(2, e.lineNumber) - } - }} - - }, "testlog"); - } -} \ No newline at end of file diff --git a/test/tests/templating.js b/test/tests/templating.js deleted file mode 100644 index cd2211e..0000000 --- a/test/tests/templating.js +++ /dev/null @@ -1,43 +0,0 @@ -JMVCTest = { - APPLICATION_NAME : 'EJS', - TEST_DESCRIPTION : 'This tests templating', - perform_test : function() { - new Test.Unit.Runner({ - - setup: function() { - this.animals = ['sloth', 'bear', 'monkey'] - }, - teardown: function() { - }, - test_find_and_process: function() { with(this) { - var result = new EJS({url: 'templates/test.ejs'}).render({animals: this.animals}) ; - assertEqual("
    \n
  • sloth
  • \n\n
  • bear
  • \n\n
  • monkey
  • \n
", result) - - }}, - test_caching: function() { with(this) { - // create a basic template to insert - var ejs = "<%% replace_me %>"+ - "
    <% animals.each(function(animal){%>" + - "
  • <%= animal %>
  • " + - "<%});%>
"; - - EJS.update('templates/test.ejs', new EJS({text: ejs}) ) - - var result = new EJS({url: 'templates/test.ejs'}).render({animals: this.animals}) ; - assertEqual("<% replace_me %>
  • sloth
  • bear
  • monkey
", result) - }}, - test_template_not_found : function() { with(this) { - try{ - new EJS({url: 'templates/test_not_found.ejs'}) ; - assert(false, 'an error should have happened') - }catch(e){ - assert(true) - } - - }} - - //error - - }, "testlog"); - } -} \ No newline at end of file diff --git a/test/tests/views.js b/test/tests/views.js deleted file mode 100644 index cf611ef..0000000 --- a/test/tests/views.js +++ /dev/null @@ -1,100 +0,0 @@ -JMVCTest = { - APPLICATION_NAME : 'EJS', - TEST_DESCRIPTION : 'This tests templating', - perform_test : function() { - new Test.Unit.Runner({ - - setup: function() { - this.view = new EJS.Helpers({}); - this.animals = ['sloth', 'bear', 'monkey']; - }, - teardown: function() { - }, - test_link_to: function() { with(this) { - assertEqual( "hello world", - this.view.link_to('hello world', '/something/here' ) ) - - var compiled = new EJS({text: "<%= link_to('hello world', '/something/here' ) %>"}).render({}) ; - assertEqual("hello world", compiled) - }}, - test_date_tag: function() { with(this) { - var date = new Date(2007,10,20,1,1,1,1) - assertEqual( "", - this.view.date_tag('Installation[date]', date) ) - }}, - test_form_tag: function() { with(this) { - assertEqual( "
", - this.view.form_tag('/myaction') ) - }}, - test_end_form_tag: function() { with(this) { - assertEqual( "
", - this.view.form_tag_end() ) - }}, - test_hidden_field_tag: function() { with(this) { - assertEqual( "", - this.view.hidden_field_tag('something[interesting]', 5) ) - }}, - test_input_field_tag: function() { with(this) { - assertEqual( "", - this.view.input_field_tag('something[interesting]', 5) ) - }}, - test_current_page : function(){with (this){ - assert( this.view.is_current_page(window.location.href) ); - assert( this.view.is_current_page(window.location.pathname) ); - assertEqual(false, this.view.is_current_page('juptierit.com') ); - }}, - test_submit_link_to : function(){with (this){ - - assertEqual( "", - this.view.submit_link_to('holla', '/new/location') ) - }}, - test_link_to_unless : function(){with (this){ - assertEqual( "Reply", this.view.link_to_unless(false, 'Reply', '/reply' ) ) - assertEqual( "Reply", this.view.link_to_unless(true, 'Reply', '/reply' ) ) - }}, - test_link_to_if : function(){with (this){ - assertEqual( "Reply", this.view.link_to_if(true, 'Reply', '/reply' ) ) - assertEqual( "Reply", this.view.link_to_if(false, 'Reply', '/reply' ) ) - }}, - test_link_to_unless_current : function(){with (this){ - assertEqual( "Reply", this.view.link_to_unless_current('Reply', '/reply' ) ) - assertEqual( "Reply", this.view.link_to_unless_current('Reply', window.location.pathname ) ) - }}, - test_password_field_tag : function(){with (this){ - assertEqual( "", - this.view.password_field_tag('something[interesting]', 5) ) - }}, - test_password_field_tag : function(){with (this){ - assertEqual( "", - this.view.password_field_tag('something[interesting]', 5) ) - }}, - test_select_tag : function(){with (this){ - var choices = [ {value: 1, text: 'First Choice' }, - {value: 2, text: 'Second Choice'}, - {value: '3', text: 'Third Choice'} ] - assertEqual( "", - this.view.select_tag('mySelectElement', 2, choices) ) - }}, - test_text_area_tag : function(){with (this){ - assertEqual( "", - this.view.text_area_tag('task[description]', 'Here is some text.\nA new line.') ) - }}, - test_text_field_tag : function(){with (this){ - assertEqual( "", - this.view.text_field_tag('something[interesting]', 5) ) - }}, - test_text_img_tag : function(){with (this){ - assertEqual( "something", - this.view.img_tag('/some.png', 'something') ) - }}, - test_submit_tag : function(){with (this){ - assertEqual( "", - this.view.submit_tag('Submit') ) - }} - - - //error - - }, "testlog"); - } -} \ No newline at end of file