`
isiqi
  • 浏览: 15950242 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论
阅读更多

jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'json_test.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script language="javascript" src="<%=path%>/jsonjs/prototype.js"></script>
<script language="javascript" src="<%=path%>/jsonjs/json.js"></script>
<script type="text/javascript">
function sendJson(){

var userName = "helloUserName";
var userPwd = "helloPwd";
var url = "<%=path%>/userServlet";
var params = "userName="+userName+"&userPwd="+userPwd;
var myAjax = new Ajax.Request(url,
{method:'post',
parameters: params,
onComplete:showResultResponse,
asynchronous: false});
}

function showResultResponse(responseObj){
var resText = responseObj.responseText;
var result= resText.parseJSON(); //转化成对象

//获得List方式1: result.list[0]
alert(""+result.list[0].stuPwd);

//获得List的方式2 (list为对象的属性名):
var listVal = result.list;
alert("listVal="+listVal);

for(var i = 0 ; i < listVal.length;i++){
//var val = eval('"+listVal[i]+"');
var val = listVal[i];
alert(val.stuName);//打印其值
}

//获得Map方式 OK
var mapVal = result.map;
alert(mapVal);
var i=0;
for (var k in mapVal) {
//alert('k='+k);
//alert("k.toStirng="+k.toString());
//alert('mapVal()='+mapVal[k.toString()]);
//alert('mapVal() 属性='+mapVal[k.toString()].stuName);
//注意:要用hasOwnProperty遍历才会正确
if (mapVal.hasOwnProperty(k)){
alert("stuName属性值为="+mapVal[k.toString()].stuName);
i++;
alert("i="+i);
}

}
var resDiv = document.getElementById("resultDiv");
resDiv.innerHTML = 'id='+result.id+' '+result.userName+' '+result.userPwd
}
</script>
</head>

<body>
This is my JSP page. <br>
<input type="button" name="btn" onclick="sendJson()" value="发送json测试"/>
<div>
返回对象的结果: <div id="resultDiv"></div>
</div>

<div id="mapDiv"></div>
</body>
</html>

js文件: json.js

/*
json.js
2008-11-21

Public Domain

No warranty expressed or implied. Use at your own risk.

This file has been superceded by http://www.JSON.org/json2.js

See http://www.JSON.org/js.html

This file adds these methods to JavaScript:

object.toJSONString(whitelist)
This method produce a JSON text from a JavaScript value.
It must not contain any cyclical references. Illegal values
will be excluded.

The default conversion for dates is to an ISO string. You can
add a toJSONString method to any date object to get a different
representation.

The object and array methods can take an optional whitelist
argument. A whitelist is an array of strings. If it is provided,
keys in objects not found in the whitelist are excluded.

string.parseJSON(filter)
This method parses a JSON text to produce an object or
array. It can throw a SyntaxError exception.

The optional filter parameter is a function which can filter and
transform the results. It receives each of the keys and values, and
its return value is used instead of the original value. If it
returns what it received, then structure is not modified. If it
returns undefined then the member is deleted.

Example:

// Parse the text. If a key contains the string 'date' then
// convert the value to a date.

myData = text.parseJSON(function (key, value) {
return key.indexOf('date') >= 0 ? new Date(value) : value;
});

This file will break programs with improper for..in loops. See
http://yuiblog.com/blog/2006/09/26/for-in-intrigue/

This file creates a global JSON object containing two methods: stringify
and parse.

JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.

replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.

space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.

This method produces a JSON text from a JavaScript value.

When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the object holding the key.

For example, this would serialize Dates as ISO strings.

Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}

return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};

You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.

If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.

Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.

The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.

If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.

Example:

text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'


text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'


JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.

The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.

Example:

// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.

myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});

myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});


This is a reference implementation. You are free to copy, modify, or
redistribute.

This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html

USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
*/

/*jslint evil: true */

/*global JSON */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, parseJSON, prototype, push, replace, slice,
stringify, test, toJSON, toJSONString, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
JSON = {};
}
(function () {

function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}

if (typeof Date.prototype.toJSON !== 'function') {

Date.prototype.toJSON = function (key) {

return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};

String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}

var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;


function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

escapable.lastIndex = 0;
return escapable.test(string) ?
'"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' :
'"' + string + '"';
}


function str(key, holder) {

// Produce a string from holder[key].

var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}

// What happens next depends on the value's type.

switch (typeof value) {
case 'string':
return quote(value);

case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

return isFinite(value) ? String(value) : 'null';

case 'boolean':
case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

if (!value) {
return 'null';
}

// Make an array to hold the partial results of stringifying this object value.

gap += indent;
partial = [];

// Is the value an array?

if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

v = partial.length === 0 ? '[]' :
gap ? '[\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}

// If the replacer is an array, use it to select the members to be stringified.

if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
k = rep[i];
if (typeof k === 'string') {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {

// Otherwise, iterate through all of the keys in the object.

for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

v = partial.length === 0 ? '{}' :
gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
mind + '}' : '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}

// If the JSON object does not yet have a stringify method, give it one.

if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

var i;
gap = '';
indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}

// If the space parameter is a string, it will be used as the indent string.

} else if (typeof space === 'string') {
indent = space;
}

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

return str('', {'': value});
};
}


// If the JSON object does not yet have a parse method, give it one.

if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

var j;

function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}

// If the text is not JSON parseable, then a SyntaxError is thrown.

throw new SyntaxError('JSON.parse');
};
}
})();


// Augment the basic prototypes if they have not already been augmented.
// These forms are obsolete. It is recommended that JSON.stringify and
// JSON.parse be used instead.

if (!Object.prototype.toJSONString) {
Object.prototype.toJSONString = function (filter) {
return JSON.stringify(this, filter);
};
Object.prototype.parseJSON = function (filter) {
return JSON.parse(this, filter);
};
}

------------------------------------------------------------

prototype.js文件

/* Prototype JavaScript framework, version 1.5.0_rc1
* (c) 2005 Sam Stephenson <sam@conio.net>
*
* Prototype is freely distributable under the terms of an MIT-style license.
* For details, see the Prototype web site: http://prototype.conio.net/
*
/*--------------------------------------------------------------------------*/

var Prototype = {
Version: '1.5.0_rc1',
ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',

emptyFunction: function() {},
K: function(x) {return x}
}

var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}

var Abstract = new Object();

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;
}
},

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);
}
});

Function.prototype.bind = function() {
var __method = this, args = $A(arguments), object = args.shift();
return function() {
return __method.apply(object, args.concat($A(arguments)));
}
}

Function.prototype.bindAsEventListener = function(object) {
var __method = this, args = $A(arguments), object = args.shift();
return function(event) {
return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
}
}

Object.extend(Number.prototype, {
toColorPart: function() {
var digits = this.toString(16);
if (this < 16) return '0' + digits;
return digits;
},

succ: function() {
return this + 1;
},

times: function(iterator) {
$R(0, this, true).each(iterator);
return this;
}
});

var Try = {
these: function() {
var returnValue;

for (var i = 0; i < arguments.length; i++) {
var lambda = arguments[i];
try {
returnValue = lambda();
break;
} catch (e) {}
}

return returnValue;
}
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
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);
},

stop: function() {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = null;
},

onTimerEvent: function() {
if (!this.currentlyExecuting) {
try {
this.currentlyExecuting = true;
this.callback(this);
} finally {
this.currentlyExecuting = false;
}
}
}
}
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 += (replacement(match) || '').toString();
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 this;
},

truncate: function(length, truncation) {
length = length || 30;
truncation = truncation === undefined ? '...' : truncation;
return this.length > length ?
this.slice(0, length - truncation.length) + truncation : 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 div = document.createElement('div');
var text = document.createTextNode(this);
div.appendChild(text);
return div.innerHTML;
},

unescapeHTML: function() {
var div = document.createElement('div');
div.innerHTML = this.stripTags();
return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
},

toQueryParams: function() {
var pairs = this.match(/^\??(.*)$/)[1].split('&');
return pairs.inject({}, function(params, pairString) {
var pair = pairString.split('=');
var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
params[decodeURIComponent(pair[0])] = value;
return params;
});
},

toArray: function() {
return this.split('');
},

camelize: function() {
var oStringList = this.split('-');
if (oStringList.length == 1) return oStringList[0];

var camelizedString = this.indexOf('-') == 0
? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
: oStringList[0];

for (var i = 1, len = oStringList.length; i < len; i++) {
var s = oStringList[i];
camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
}

return camelizedString;
},

inspect: function(useDoubleQuotes) {
var escapedString = this.replace(/\\/g, '\\\\');
if (useDoubleQuotes)
return '"' + escapedString.replace(/"/g, '\\"') + '"';
else
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
}
});

String.prototype.gsub.prepareReplacement = function(replacement) {
if (typeof replacement == 'function') return replacement;
var template = new Template(replacement);
return function(match) { return template.evaluate(match) };
}

String.prototype.parseQuery = String.prototype.toQueryParams;

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
initialize: function(template, pattern) {
this.template = template.toString();
this.pattern = pattern || Template.Pattern;
},

evaluate: function(object) {
return this.template.gsub(this.pattern, function(match) {
var before = match[1];
if (before == '\\') return match[2];
return before + (object[match[3]] || '').toString();
});
}
}

var $break = new Object();
var $continue = new Object();

var Enumerable = {
each: function(iterator) {
var index = 0;
try {
this._each(function(value) {
try {
iterator(value, index++);
} catch (e) {
if (e != $continue) throw e;
}
});
} catch (e) {
if (e != $break) throw e;
}
},

all: function(iterator) {
var result = true;
this.each(function(value, index) {
result = result && !!(iterator || Prototype.K)(value, index);
if (!result) throw $break;
});
return result;
},

any: function(iterator) {
var result = false;
this.each(function(value, index) {
if (result = !!(iterator || Prototype.K)(value, index))
throw $break;
});
return result;
},

collect: function(iterator) {
var results = [];
this.each(function(value, index) {
results.push(iterator(value, index));
});
return results;
},

detect: function (iterator) {
var result;
this.each(function(value, index) {
if (iterator(value, index)) {
result = value;
throw $break;
}
});
return result;
},

findAll: function(iterator) {
var results = [];
this.each(function(value, index) {
if (iterator(value, index))
results.push(value);
});
return results;
},

grep: function(pattern, iterator) {
var results = [];
this.each(function(value, index) {
var stringValue = value.toString();
if (stringValue.match(pattern))
results.push((iterator || Prototype.K)(value, index));
})
return results;
},

include: function(object) {
var found = false;
this.each(function(value) {
if (value == object) {
found = true;
throw $break;
}
});
return found;
},

inject: function(memo, iterator) {
this.each(function(value, index) {
memo = iterator(memo, value, index);
});
return memo;
},

invoke: function(method) {
var args = $A(arguments).slice(1);
return this.collect(function(value) {
return value[method].apply(value, args);
});
},

max: function(iterator) {
var result;
this.each(function(value, index) {
value = (iterator || Prototype.K)(value, index);
if (result == undefined || value >= result)
result = value;
});
return result;
},

min: function(iterator) {
var result;
this.each(function(value, index) {
value = (iterator || Prototype.K)(value, index);
if (result == undefined || value < result)
result = value;
});
return result;
},

partition: function(iterator) {
var trues = [], falses = [];
this.each(function(value, index) {
((iterator || Prototype.K)(value, index) ?
trues : falses).push(value);
});
return [trues, falses];
},

pluck: function(property) {
var results = [];
this.each(function(value, index) {
results.push(value[property]);
});
return results;
},

reject: function(iterator) {
var results = [];
this.each(function(value, index) {
if (!iterator(value, index))
results.push(value);
});
return results;
},

sortBy: function(iterator) {
return this.collect(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.collect(Prototype.K);
},

zip: function() {
var iterator = Prototype.K, args = $A(arguments);
if (typeof args.last() == 'function')
iterator = args.pop();

var collections = [this].concat(args).map($A);
return this.map(function(value, index) {
return iterator(collections.pluck(index));
});
},

inspect: function() {
return '#<Enumerable:' + this.toArray().inspect() + '>';
}
}

Object.extend(Enumerable, {
map: Enumerable.collect,
find: Enumerable.detect,
select: Enumerable.findAll,
member: Enumerable.include,
entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) {
return iterable.toArray();
} else {
var results = [];
for (var i = 0; i < iterable.length; i++)
results.push(iterable[i]);
return results;
}
}

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; i < this.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 != undefined || value != null;
});
},

flatten: function() {
return this.inject([], function(array, value) {
return array.concat(value && value.constructor == Array ?
value.flatten() : [value]);
});
},

without: function() {
var values = $A(arguments);
return this.select(function(value) {
return !values.include(value);
});
},

indexOf: function(object) {
for (var i = 0; i < this.length; i++)
if (this[i] == object) return i;
return -1;
},

reverse: function(inline) {
return (inline !== false ? this : this.toArray())._reverse();
},

reduce: function() {
return this.length > 1 ? this : this[0];
},

uniq: function() {
return this.inject([], function(array, value) {
return array.include(value) ? array : array.concat([value]);
});
},

inspect: function() {
return '[' + this.map(Object.inspect).join(', ') + ']';
}
});
var Hash = {
_each: function(iterator) {
for (var key in this) {
var value = this[key];
if (typeof value == 'function') continue;

var pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
}
},

keys: function() {
return this.pluck('key');
},

values: function() {
return this.pluck('value');
},

merge: function(hash) {
return $H(hash).inject($H(this), function(mergedHash, pair) {
mergedHash[pair.key] = pair.value;
return mergedHash;
});
},

toQueryString: function() {
return this.map(function(pair) {
return pair.map(encodeURIComponent).join('=');
}).join('&');
},

inspect: function() {
return '#<Hash:{' + this.map(function(pair) {
return pair.map(Object.inspect).join(': ');
}).join(', ') + '}>';
}
}

function $H(object) {
var hash = Object.extend({}, object || {});
Object.extend(hash, Enumerable);
Object.extend(hash, Hash);
return hash;
}
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
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(responderToAdd) {
if (!this.include(responderToAdd))
this.responders.push(responderToAdd);
},

unregister: function(responderToRemove) {
this.responders = this.responders.without(responderToRemove);
},

dispatch: function(callback, request, transport, json) {
this.each(function(responder) {
if (responder[callback] && typeof responder[callback] == 'function') {
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 = function() {};
Ajax.Base.prototype = {
setOptions: function(options) {
this.options = {
method: 'post',
asynchronous: true,
contentType: 'application/x-www-form-urlencoded',
parameters: ''
}
Object.extend(this.options, options || {});
},

responseIsSuccess: function() {
return this.transport.status == undefined
|| this.transport.status == 0
|| (this.transport.status >= 200 && this.transport.status < 300);
},

responseIsFailure: function() {
return !this.responseIsSuccess();
}
}

Ajax.Request = Class.create();
Ajax.Request.Events =
['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
initialize: function(url, options) {
this.transport = Ajax.getTransport();
this.setOptions(options);
this.request(url);
},

request: function(url) {
var parameters = this.options.parameters || '';
if (parameters.length > 0) parameters += '&_=';

/* Simulate other verbs over post */
if (this.options.method != 'get' && this.options.method != 'post') {
parameters += (parameters.length > 0 ? '&' : '') + '_method=' + this.options.method;
this.options.method = 'post';
}

try {
this.url = url;
if (this.options.method == 'get' && parameters.length > 0)
this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;

Ajax.Responders.dispatch('onCreate', this, this.transport);

this.transport.open(this.options.method, this.url,
this.options.asynchronous);

if (this.options.asynchronous)
setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

this.transport.onreadystatechange = this.onStateChange.bind(this);
this.setRequestHeaders();

var body = this.options.postBody ? this.options.postBody : parameters;
this.transport.send(this.options.method == 'post' ? body : null);

/* Force Firefox to handle ready state 4 for synchronous requests */
if (!this.options.asynchronous && this.transport.overrideMimeType)
this.onStateChange();

} catch (e) {
this.dispatchException(e);
}
},

setRequestHeaders: function() {
var requestHeaders =
['X-Requested-With', 'XMLHttpRequest',
'X-Prototype-Version', Prototype.Version,
'Accept', 'text/javascript, text/html, application/xml, text/xml, */*'];

if (this.options.method == 'post') {
requestHeaders.push('Content-type', this.options.contentType);

/* Force "Connection: close" for Mozilla browsers to work around
* a bug where XMLHttpReqeuest sends an incorrect Content-length
* header. See Mozilla Bugzilla #246651.
*/
if (this.transport.overrideMimeType)
requestHeaders.push('Connection', 'close');
}

if (this.options.requestHeaders)
requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);

for (var i = 0; i < requestHeaders.length; i += 2)
this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
},

onStateChange: function() {
var readyState = this.transport.readyState;
if (readyState != 1)
this.respondToReadyState(this.transport.readyState);
},

header: function(name) {
try {
return this.transport.getResponseHeader(name);
} catch (e) {}
},

evalJSON: function() {
try {
return eval('(' + this.header('X-JSON') + ')');
} catch (e) {}
},

evalResponse: function() {
try {
return eval(this.transport.responseText);
} catch (e) {
this.dispatchException(e);
}
},

respondToReadyState: function(readyState) {
var event = Ajax.Request.Events[readyState];
var transport = this.transport, json = this.evalJSON();

if (event == 'Complete') {
try {
(this.options['on' + this.transport.status]
|| this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
|| Prototype.emptyFunction)(transport, json);
} catch (e) {
this.dispatchException(e);
}

if ((this.header('Content-type') || '').match(/^text\/javascript/i))
this.evalResponse();
}

try {
(this.options['on' + event] || Prototype.emptyFunction)(transport, json);
Ajax.Responders.dispatch('on' + event, this, transport, json);
} catch (e) {
this.dispatchException(e);
}

/* Avoid memory leak in MSIE: clean up the oncomplete event handler */
if (event == 'Complete')
this.transport.onreadystatechange = Prototype.emptyFunction;
},

dispatchException: function(exception) {
(this.options.onException || Prototype.emptyFunction)(this, exception);
Ajax.Responders.dispatch('onException', this, exception);
}
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
initialize: function(container, url, options) {
this.containers = {
success: container.success ? $(container.success) : $(container),
failure: container.failure ? $(container.failure) :
(container.success ? null : $(container))
}

this.transport = Ajax.getTransport();
this.setOptions(options);

var onComplete = this.options.onComplete || Prototype.emptyFunction;
this.options.onComplete = (function(transport, object) {
this.updateContent();
onComplete(transport, object);
}).bind(this);

this.request(url);
},

updateContent: function() {
var receiver = this.responseIsSuccess() ?
this.containers.success : this.containers.failure;
var response = this.transport.responseText;

if (!this.options.evalScripts)
response = response.stripScripts();

if (receiver) {
if (this.options.insertion) {
new this.options.insertion(receiver, response);
} else {
Element.update(receiver, response);
}
}

if (this.responseIsSuccess()) {
if (this.onComplete)
setTimeout(this.onComplete.bind(this), 10);
}
}
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
initialize: function(container, url, options) {
this.setOptions(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(request) {
if (this.options.decay) {
this.decay = (request.responseText == this.lastText ?
this.decay * this.options.decay : 1);

this.lastText = request.responseText;
}
this.timer = setTimeout(this.onTimerEvent.bind(this),
this.decay * this.frequency * 1000);
},

onTimerEvent: function() {
this.updater = new Ajax.Updater(this.container, this.url, this.options);
}
});
function $() {
var results = [], element;
for (var i = 0; i < arguments.length; i++) {
element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
results.push(Element.extend(element));
}
return results.reduce();
}

document.getElementsByClassName = function(className, parentElement) {
var children = ($(parentElement) || document.body).getElementsByTagName('*');
return $A(children).inject([], function(elements, child) {
if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
elements.push(Element.extend(child));
return elements;
});
}

/*--------------------------------------------------------------------------*/

if (!window.Element)
var Element = new Object();

Element.extend = function(element) {
if (!element) return;
if (_nativeExtensions || element.nodeType == 3) return element;

if (!element._extended && element.tagName && element != window) {
var methods = Object.clone(Element.Methods), cache = Element.extend.cache;

if (element.tagName == 'FORM')
Object.extend(methods, Form.Methods);
if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
Object.extend(methods, Form.Element.Methods);

for (var property in methods) {
var value = methods[property];
if (typeof value == 'function')
element[property] = cache.findOrStore(value);
}
}

element._extended = true;
return element;
}

Element.extend.cache = {
findOrStore: function(value) {
return this[value] = this[value] || function() {
return value.apply(null, [this].concat($A(arguments)));
}
}
}

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, html) {
$(element).innerHTML = html.stripScripts();
setTimeout(function() {html.evalScripts()}, 10);
return element;
},

replace: function(element, html) {
element = $(element);
if (element.outerHTML) {
element.outerHTML = html.stripScripts();
} else {
var range = element.ownerDocument.createRange();
range.selectNodeContents(element);
element.parentNode.replaceChild(
range.createContextualFragment(html.stripScripts()), element);
}
setTimeout(function() {html.evalScripts()}, 10);
return element;
},

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) {
element = $(element);
return $A(element.getElementsByTagName('*'));
},

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) {
element = $(element);
if (typeof selector == 'string')
selector = new Selector(selector);
return selector.match(element);
},

up: function(element, expression, index) {
return Selector.findElement($(element).ancestors(), expression, index);
},

down: function(element, expression, index) {
return Selector.findElement($(element).descendants(), expression, index);
},

previous: function(element, expression, index) {
return Selector.findElement($(element).previousSiblings(), expression, index);
},

next: function(element, expression, index) {
return Selector.findElement($(element).nextSiblings(), expression, index);
},

getElementsBySelector: function() {
var args = $A(arguments), element = $(args.shift());
return Selector.findChildElements(element, args);
},

getElementsByClassName: function(element, className) {
element = $(element);
return document.getElementsByClassName(className, element);
},

getHeight: function(element) {
element = $(element);
return element.offsetHeight;
},

classNames: function(element) {
return new Element.ClassNames(element);
},

hasClassName: function(element, className) {
if (!(element = $(element))) return;
return Element.classNames(element).include(className);
},

addClassName: function(element, className) {
if (!(element = $(element))) return;
Element.classNames(element).add(className);
return element;
},

removeClassName: function(element, className) {
if (!(element = $(element))) return;
Element.classNames(element).remove(className);
return element;
},

observe: function() {
Event.observe.apply(Event, arguments);
return $A(arguments).first();
},

stopObserving: function() {
Event.stopObserving.apply(Event, arguments);
return $A(arguments).first();
},

// 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.match(/^\s*$/);
},

childOf: function(element, ancestor) {
element = $(element), ancestor = $(ancestor);
while (element = element.parentNode)
if (element == ancestor) return true;
return false;
},

scrollTo: function(element) {
element = $(element);
var x = element.x ? element.x : element.offsetLeft,
y = element.y ? element.y : element.offsetTop;
window.scrollTo(x, y);
return element;
},

getStyle: function(element, style) {
element = $(element);
var value = element.style[style.camelize()];
if (!value) {
if (document.defaultView && document.defaultView.getComputedStyle) {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css.getPropertyValue(style) : null;
} else if (element.currentStyle) {
value = element.currentStyle[style.camelize()];
}
}

if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
if (Element.getStyle(element, 'position') == 'static') value = 'auto';

return value == 'auto' ? null : value;
},

setStyle: function(element, style) {
element = $(element);
for (var name in style)
element.style[name.camelize()] = style[name];
return element;
},

getDimensions: function(element) {
element = $(element);
if (Element.getStyle(element, 'display') != 'none')
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;
els.visibility = 'hidden';
els.position = 'absolute';
els.display = '';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
els.display = 'none';
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._overflow = element.style.overflow || 'auto';
if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
element.style.overflow = 'hidden';
return element;
},

undoClipping: function(element) {
element = $(element);
if (!element._overflow) return;
element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
element._overflow = null;
return element;
}
}

// IE is missing .innerHTML support for TABLE-related elements
if(document.all){
Element.Methods.update = function(element, html) {
element = $(element);
var tagName = element.tagName.toUpperCase();
if (['THEAD','TBODY','TR','TD'].indexOf(tagName) > -1) {
var div = document.createElement('div');
switch (tagName) {
case 'THEAD':
case 'TBODY':
div.innerHTML = '<table><tbody>' + html.stripScripts() + '</tbody></table>';
depth = 2;
break;
case 'TR':
div.innerHTML = '<table><tbody><tr>' + html.stripScripts() + '</tr></tbody></table>';
depth = 3;
break;
case 'TD':
div.innerHTML = '<table><tbody><tr><td>' + html.stripScripts() + '</td></tr></tbody></table>';
depth = 4;
}
$A(element.childNodes).each(function(node){
element.removeChild(node)
});
depth.times(function(){ div = div.firstChild });

$A(div.childNodes).each(
function(node){ element.appendChild(node) });
} else {
element.innerHTML = html.stripScripts();
}
setTimeout(function() {html.evalScripts()}, 10);
return element;
}
}

Object.extend(Element, Element.Methods);

var _nativeExtensions = false;

if (!window.HTMLElement && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
/* Emulate HTMLElement, HTMLFormElement, HTMLInputElement, HTMLTextAreaElement,
and HTMLSelectElement in Safari */
['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
var klass = window['HTML' + tag + 'Element'] = {};
klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
});
}

Element.addMethods = function(methods) {
Object.extend(Element.Methods, methods || {});

function copy(methods, destination) {
var cache = Element.extend.cache;
for (var property in methods) {
var value = methods[property];
destination[property] = cache.findOrStore(value);
}
}

if (typeof HTMLElement != 'undefined') {
copy(Element.Methods, HTMLElement.prototype);
copy(Form.Methods, HTMLFormElement.prototype);
[HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
copy(Form.Element.Methods, klass.prototype);
});
_nativeExtensions = true;
}
}

var Toggle = new Object();
Toggle.display = Element.toggle;

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
initialize: function(element, content) {
this.element = $(element);
this.content = content.stripScripts();

if (this.adjacency && this.element.insertAdjacentHTML) {
try {
this.element.insertAdjacentHTML(this.adjacency, this.content);
} catch (e) {
var tagName = this.element.tagName.toLowerCase();
if (tagName == 'tbody' || tagName == 'tr') {
this.insertContent(this.contentFromAnonymousTable());
} else {
throw e;
}
}
} else {
this.range = this.element.ownerDocument.createRange();
if (this.initializeRange) this.initializeRange();
this.insertContent([this.range.createContextualFragment(this.content)]);
}

setTimeout(function() {content.evalScripts()}, 10);
},

contentFromAnonymousTable: function() {
var div = document.createElement('div');
div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
return $A(div.childNodes[0].childNodes[0].childNodes);
}
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
initializeRange: function() {
this.range.setStartBefore(this.element);
},

insertContent: function(fragments) {
fragments.each((function(fragment) {
this.element.parentNode.insertBefore(fragment, this.element);
}).bind(this));
}
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
initializeRange: function() {
this.range.selectNodeContents(this.element);
this.range.collapse(true);
},

insertContent: function(fragments) {
fragments.reverse(false).each((function(fragment) {
this.element.insertBefore(fragment, this.element.firstChild);
}).bind(this));
}
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
initializeRange: function() {
this.range.selectNodeContents(this.element);
this.range.collapse(this.element);
},

insertContent: function(fragments) {
fragments.each((function(fragment) {
this.element.appendChild(fragment);
}).bind(this));
}
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
initializeRange: function() {
this.range.setStartAfter(this.element);
},

insertContent: function(fragments) {
fragments.each((function(fragment) {
this.element.parentNode.insertBefore(fragment,
this.element.nextSibling);
}).bind(this));
}
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
initialize: function(element) {
this.element = $(element);
},

_each: function(iterator) {
this.element.className.split(/\s+/).select(function(name) {
return name.length > 0;
})._each(iterator);
},

set: function(className) {
this.element.className = className;
},

add: function(classNameToAdd) {
if (this.include(classNameToAdd)) return;
this.set(this.toArray().concat(classNameToAdd).join(' '));
},

remove: function(classNameToRemove) {
if (!this.include(classNameToRemove)) return;
this.set(this.select(function(className) {
return className != classNameToRemove;
}).join(' '));
},

toString: function() {
return this.toArray().join(' ');
}
}

Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
Selector.prototype = {
initialize: function(expression) {
this.params = {classNames: []};
this.expression = expression.toString().strip();
this.parseExpression();
this.compileMatcher();
},

parseExpression: function() {
function abort(message) { throw 'Parse error in selector: ' + message; }

if (this.expression == '') abort('empty expression');

var params = this.params, expr = this.expression, match, modifier, clause, rest;
while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
params.attributes = params.attributes || [];
params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
expr = match[1];
}

if (expr == '*') return this.params.wildcard = true;

while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
modifier = match[1], clause = match[2], rest = match[3];
switch (modifier) {
case '#': params.id = clause; break;
case '.': params.classNames.push(clause); break;
case '':
case undefined: params.tagName = clause.toUpperCase(); break;
default: abort(expr.inspect());
}
expr = rest;
}

if (expr.length > 0) abort(expr.inspect());
},

buildMatchExpression: function() {
var params = this.params, conditions = [], clause;

if (params.wildcard)
conditions.push('true');
if (clause = params.id)
conditions.push('element.id == ' + clause.inspect());
if (clause = params.tagName)
conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
if ((clause = params.classNames).length > 0)
for (var i = 0; i < clause.length; i++)
conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')');
if (clause = params.attributes) {
clause.each(function(attribute) {
var value = 'element.getAttribute(' + attribute.name.inspect() + ')';
var splitValueBy = function(delimiter) {
return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
}

switch (attribute.operator) {
case '=': conditions.push(value + ' == ' + attribute.value.inspect()); break;
case '~=': conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
case '|=': conditions.push(
splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
); break;
case '!=': conditions.push(value + ' != ' + attribute.value.inspect()); break;
case '':
case undefined: conditions.push(value + ' != null'); break;
default: throw 'Unknown operator ' + attribute.operator + ' in selector';
}
});
}

return conditions.join(' && ');
},

compileMatcher: function() {
this.match = new Function('element', 'if (!element.tagName) return false; \
return ' + this.buildMatchExpression());
},

findElements: function(scope) {
var element;

if (element = $(this.params.id))
if (this.match(element))
if (!scope || Element.childOf(element, scope))
return [element];

scope = (scope || document).getElementsByTagName(this.params.tagName || '*');

var results = [];
for (var i = 0; i < scope.length; i++)
if (this.match(element = scope[i]))
results.push(Element.extend(element));

return results;
},

toString: function() {
return this.expression;
}
}

Object.extend(Selector, {
matchElements: function(elements, expression) {
var selector = new Selector(expression);
return elements.select(selector.match.bind(selector));
},

findElement: function(elements, expression, index) {
if (typeof expression == 'number') index = expression, expression = false;
return Selector.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics