[MRM-987] convert from prototype + scriptaculous to jquery

git-svn-id: https://svn.apache.org/repos/asf/archiva/trunk@707814 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Brett Porter 2008-10-25 06:02:24 +00:00
parent 0e7887712a
commit 6f9ea6ac86
14 changed files with 30 additions and 8871 deletions

View File

@ -77,10 +77,8 @@ public class CopyPasteSnippetTag
if ( TOGGLE.equals( wrapper ) )
{
prefix.append( "<a href=\"#\" onclick=\"Effect.toggle('repoPom" );
prefix.append( repo.getId() ).append( "','slide'); return false;\">Show POM Snippet</a><br/>" );
prefix.append( "<pre class=\"pom\" style=\"display: none;\" id=\"repoPom" ).append( repo.getId() );
prefix.append( "\"><code>" );
prefix.append( "<a href=\"#\" class=\"expand\">Show POM Snippet</a><br/>" );
prefix.append( "<pre class=\"pom\"><code>" );
suffix.append( "</code></pre>" );
}

View File

@ -27,6 +27,19 @@
<head>
<title>Administration - Proxy Connectors</title>
<s:head/>
<script type="text/javascript" src="<c:url value='/js/jquery/jquery-1.2.6.pack.js'/>"></script>
<script type="text/javascript">
$(document).ready(function(){
$("table.settings").hide();
$("a.expand").click(function(event){
event.preventDefault();
$(this).next().toggle("slow");
});
});
</script>
</head>
<body>
@ -161,8 +174,8 @@
<p class="url"><a href="${repoMap[connector.targetRepoId].url}">${repoMap[connector.targetRepoId].url}</a></p>
</div>
<a class="expand" href="#" onclick="Effect.toggle('proxySettings_${connector.sourceRepoId}_${connector.targetRepoId}','slide'); return false;">Expand</a>
<table class="settings" style="display: none;" id="proxySettings_${connector.sourceRepoId}_${connector.targetRepoId}">
<a class="expand" href="#">Settings</a>
<table class="settings">
<tr>
<th nowrap="nowrap">Network Proxy:</th>
<td>

View File

@ -26,6 +26,18 @@
<head>
<title>Administration - Repositories</title>
<s:head/>
<script type="text/javascript" src="<c:url value='/js/jquery/jquery-1.2.6.pack.js'/>"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".pom").hide();
$("a.expand").click(function(event){
event.preventDefault();
$(this).siblings("pre").toggle("slow");
});
});
</script>
</head>
<body>

View File

@ -39,9 +39,8 @@
<link rel="stylesheet" href="<c:url value="/css/site.css"/>" type="text/css" media="all"/>
<link rel="stylesheet" href="<c:url value="/css/print.css"/>" type="text/css" media="print"/>
<link rel="shortcut icon" href="<c:url value="/favicon.ico" />"/>
<script type="text/javascript" src="<c:url value="/js/scriptaculous/prototype.js"/>"></script>
<script type="text/javascript" src="<c:url value="/js/scriptaculous/scriptaculous.js"/>"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<decorator:head />
</head>
<body onload="<decorator:getProperty property="body.onload" />" class="composite">

View File

@ -1,467 +0,0 @@
/*
* Date prototype extensions. Doesn't depend on any
* other code. Doens't overwrite existing methods.
*
* Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear,
* isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear,
* setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods
*
* Copyright (c) 2006 Jörn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
*
* Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString -
* I've added my name to these methods so you know who to blame if they are broken!
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* An Array of day names starting with Sunday.
*
* @example dayNames[0]
* @result 'Sunday'
*
* @name dayNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
/**
* An Array of abbreviated day names starting with Sun.
*
* @example abbrDayNames[0]
* @result 'Sun'
*
* @name abbrDayNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
/**
* An Array of month names starting with Janurary.
*
* @example monthNames[0]
* @result 'January'
*
* @name monthNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
/**
* An Array of abbreviated month names starting with Jan.
*
* @example abbrMonthNames[0]
* @result 'Jan'
*
* @name monthNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
/**
* The first day of the week for this locale.
*
* @name firstDayOfWeek
* @type Number
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.firstDayOfWeek = 1;
/**
* The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc).
*
* @name format
* @type String
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.format = 'dd/mm/yyyy';
//Date.format = 'mm/dd/yyyy';
//Date.format = 'yyyy-mm-dd';
//Date.format = 'dd mmm yy';
/**
* The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear
* only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes.
*
* @name format
* @type String
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.fullYearStart = '20';
(function() {
/**
* Adds a given method under the given name
* to the Date prototype if it doesn't
* currently exist.
*
* @private
*/
function add(name, method) {
if( !Date.prototype[name] ) {
Date.prototype[name] = method;
}
};
/**
* Checks if the year is a leap year.
*
* @example var dtm = new Date("01/12/2008");
* dtm.isLeapYear();
* @result true
*
* @name isLeapYear
* @type Boolean
* @cat Plugins/Methods/Date
*/
add("isLeapYear", function() {
var y = this.getFullYear();
return (y%4==0 && y%100!=0) || y%400==0;
});
/**
* Checks if the day is a weekend day (Sat or Sun).
*
* @example var dtm = new Date("01/12/2008");
* dtm.isWeekend();
* @result false
*
* @name isWeekend
* @type Boolean
* @cat Plugins/Methods/Date
*/
add("isWeekend", function() {
return this.getDay()==0 || this.getDay()==6;
});
/**
* Check if the day is a day of the week (Mon-Fri)
*
* @example var dtm = new Date("01/12/2008");
* dtm.isWeekDay();
* @result false
*
* @name isWeekDay
* @type Boolean
* @cat Plugins/Methods/Date
*/
add("isWeekDay", function() {
return !this.isWeekend();
});
/**
* Gets the number of days in the month.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getDaysInMonth();
* @result 31
*
* @name getDaysInMonth
* @type Number
* @cat Plugins/Methods/Date
*/
add("getDaysInMonth", function() {
return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];
});
/**
* Gets the name of the day.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getDayName();
* @result 'Saturday'
*
* @example var dtm = new Date("01/12/2008");
* dtm.getDayName(true);
* @result 'Sat'
*
* @param abbreviated Boolean When set to true the name will be abbreviated.
* @name getDayName
* @type String
* @cat Plugins/Methods/Date
*/
add("getDayName", function(abbreviated) {
return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
});
/**
* Gets the name of the month.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getMonthName();
* @result 'Janurary'
*
* @example var dtm = new Date("01/12/2008");
* dtm.getMonthName(true);
* @result 'Jan'
*
* @param abbreviated Boolean When set to true the name will be abbreviated.
* @name getDayName
* @type String
* @cat Plugins/Methods/Date
*/
add("getMonthName", function(abbreviated) {
return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
});
/**
* Get the number of the day of the year.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getDayOfYear();
* @result 11
*
* @name getDayOfYear
* @type Number
* @cat Plugins/Methods/Date
*/
add("getDayOfYear", function() {
var tmpdtm = new Date("1/1/" + this.getFullYear());
return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
});
/**
* Get the number of the week of the year.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getWeekOfYear();
* @result 2
*
* @name getWeekOfYear
* @type Number
* @cat Plugins/Methods/Date
*/
add("getWeekOfYear", function() {
return Math.ceil(this.getDayOfYear() / 7);
});
/**
* Set the day of the year.
*
* @example var dtm = new Date("01/12/2008");
* dtm.setDayOfYear(1);
* dtm.toString();
* @result 'Tue Jan 01 2008 00:00:00'
*
* @name setDayOfYear
* @type Date
* @cat Plugins/Methods/Date
*/
add("setDayOfYear", function(day) {
this.setMonth(0);
this.setDate(day);
return this;
});
/**
* Add a number of years to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addYears(1);
* dtm.toString();
* @result 'Mon Jan 12 2009 00:00:00'
*
* @name addYears
* @type Date
* @cat Plugins/Methods/Date
*/
add("addYears", function(num) {
this.setFullYear(this.getFullYear() + num);
return this;
});
/**
* Add a number of months to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addMonths(1);
* dtm.toString();
* @result 'Tue Feb 12 2008 00:00:00'
*
* @name addMonths
* @type Date
* @cat Plugins/Methods/Date
*/
add("addMonths", function(num) {
var tmpdtm = this.getDate();
this.setMonth(this.getMonth() + num);
if (tmpdtm > this.getDate())
this.addDays(-this.getDate());
return this;
});
/**
* Add a number of days to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addDays(1);
* dtm.toString();
* @result 'Sun Jan 13 2008 00:00:00'
*
* @name addDays
* @type Date
* @cat Plugins/Methods/Date
*/
add("addDays", function(num) {
this.setDate(this.getDate() + num);
return this;
});
/**
* Add a number of hours to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addHours(24);
* dtm.toString();
* @result 'Sun Jan 13 2008 00:00:00'
*
* @name addHours
* @type Date
* @cat Plugins/Methods/Date
*/
add("addHours", function(num) {
this.setHours(this.getHours() + num);
return this;
});
/**
* Add a number of minutes to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addMinutes(60);
* dtm.toString();
* @result 'Sat Jan 12 2008 01:00:00'
*
* @name addMinutes
* @type Date
* @cat Plugins/Methods/Date
*/
add("addMinutes", function(num) {
this.setMinutes(this.getMinutes() + num);
return this;
});
/**
* Add a number of seconds to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addSeconds(60);
* dtm.toString();
* @result 'Sat Jan 12 2008 00:01:00'
*
* @name addSeconds
* @type Date
* @cat Plugins/Methods/Date
*/
add("addSeconds", function(num) {
this.setSeconds(this.getSeconds() + num);
return this;
});
/**
* Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant.
*
* @example var dtm = new Date();
* dtm.zeroTime();
* dtm.toString();
* @result 'Sat Jan 12 2008 00:01:00'
*
* @name zeroTime
* @type Date
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
add("zeroTime", function() {
this.setMilliseconds(0);
this.setSeconds(0);
this.setMinutes(0);
this.setHours(0);
return this;
});
/**
* Returns a string representation of the date object according to Date.format.
* (Date.toString may be used in other places so I purposefully didn't overwrite it)
*
* @example var dtm = new Date("01/12/2008");
* dtm.asString();
* @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy'
*
* @name asString
* @type Date
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
add("asString", function() {
var r = Date.format;
return r
.split('yyyy').join(this.getFullYear())
.split('yy').join((this.getFullYear() + '').substring(2))
.split('mmm').join(this.getMonthName(true))
.split('mm').join(_zeroPad(this.getMonth()+1))
.split('dd').join(_zeroPad(this.getDate()));
});
/**
* Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object
* (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere)
*
* @example var dtm = Date.fromString("12/01/2008");
* dtm.toString();
* @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy'
*
* @name fromString
* @type Date
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.fromString = function(s)
{
var f = Date.format;
var d = new Date('01/01/1977');
var iY = f.indexOf('yyyy');
if (iY > -1) {
d.setFullYear(Number(s.substr(iY, 4)));
} else {
// TODO - this doesn't work very well - are there any rules for what is meant by a two digit year?
d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2)));
}
var iM = f.indexOf('mmm');
if (iM > -1) {
var mStr = s.substr(iM, 3);
for (var i=0; i<Date.abbrMonthNames.length; i++) {
if (Date.abbrMonthNames[i] == mStr) break;
}
d.setMonth(i);
} else {
d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1);
}
d.setDate(Number(s.substr(f.indexOf('dd'), 2)));
if (isNaN(d.getTime())) {
return false;
}
return d;
};
// utility method
var _zeroPad = function(num) {
var s = '0'+num;
return s.substring(s.length-2)
//return ('0'+num).substring(-2); // doesn't work on IE :(
};
})();

View File

@ -1,160 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// script.aculo.us builder.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// See scriptaculous.js for full license.
var Builder = {
NODEMAP: {
AREA: 'map',
CAPTION: 'table',
COL: 'table',
COLGROUP: 'table',
LEGEND: 'fieldset',
OPTGROUP: 'select',
OPTION: 'select',
PARAM: 'object',
TBODY: 'table',
TD: 'table',
TFOOT: 'table',
TH: 'table',
THEAD: 'table',
TR: 'table'
},
// note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
// due to a Firefox bug
node: function( elementName )
{
elementName = elementName.toUpperCase();
// try innerHTML approach
var parentTag = this.NODEMAP[elementName] || 'div';
var parentElement = document.createElement(parentTag);
try
{ // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
}
catch( e )
{
}
var element = parentElement.firstChild || null;
// see if browser added wrapping tags
if ( element && (element.tagName != elementName) )
element = element.getElementsByTagName(elementName)[0];
// fallback to createElement approach
if ( !element ) element = document.createElement(elementName);
// abort if nothing could be created
if ( !element ) return;
// attributes (or text)
if ( arguments[1] )
if ( this._isStringOrNumber(arguments[1]) || (arguments[1] instanceof Array) )
{
this._children(element, arguments[1]);
}
else
{
var attrs = this._attributes(arguments[1]);
if ( attrs.length )
{
try
{ // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" + elementName + " " + attrs + "></" + elementName + ">";
}
catch( e )
{
}
element = parentElement.firstChild || null;
// workaround firefox 1.0.X bug
if ( !element )
{
element = document.createElement(elementName);
for ( attr in arguments[1] )
element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
}
if ( element.tagName != elementName )
element = parentElement.getElementsByTagName(elementName)[0];
}
}
// text, or array of children
if ( arguments[2] )
this._children(element, arguments[2]);
return element;
},
_text: function( text )
{
return document.createTextNode(text);
},
_attributes: function( attributes )
{
var attrs = [];
for ( attribute in attributes )
attrs.push((attribute == 'className' ? 'class' : attribute) + '="' +
attributes[attribute].toString().escapeHTML() + '"');
return attrs.join(" ");
},
_children: function( element, children )
{
if ( typeof children == 'object' )
{ // array can hold nodes and text
children.flatten().each(function( e )
{
if ( typeof e == 'object' )
element.appendChild(e)
else
if ( Builder._isStringOrNumber(e) )
element.appendChild(Builder._text(e));
});
}
else
if ( Builder._isStringOrNumber(children) )
element.appendChild(Builder._text(children));
},
_isStringOrNumber: function( param )
{
return(typeof param == 'string' || typeof param == 'number');
},
dump: function( scope )
{
if ( typeof scope != 'object' && typeof scope != 'function' ) scope = window; //global scope
var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
"BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
"FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX " +
"KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P " +
"PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD " +
"TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
tags.each(function( tag )
{
scope[tag] = function()
{
return Builder.node.apply(Builder, [tag].concat($A(arguments)));
}
});
}
}

View File

@ -1,969 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// script.aculo.us controls.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
// (c) 2005 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
// Rob Wills
//
// See scriptaculous.js for full license.
// Autocompleter.Base handles all the autocompletion functionality
// that's independent of the data source for autocompletion. This
// includes drawing the autocompletion menu, observing keyboard
// and mouse events, and similar.
//
// Specific autocompleters need to provide, at the very least,
// a getUpdatedChoices function that will be invoked every time
// the text inside the monitored textbox changes. This method
// should get the text for which to provide autocompletion by
// invoking this.getToken(), NOT by directly accessing
// this.element.value. This is to allow incremental tokenized
// autocompletion. Specific auto-completion logic (AJAX, etc)
// belongs in getUpdatedChoices.
//
// Tokenized incremental autocompletion is enabled automatically
// when an autocompleter is instantiated with the 'tokens' option
// in the options parameter, e.g.:
// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
// will incrementally autocomplete with a comma as the token.
// Additionally, ',' in the above example can be replaced with
// a token array, e.g. { tokens: [',', '\n'] } which
// enables autocompletion on multiple tokens. This is most
// useful when one of the tokens is \n (a newline), as it
// allows smart autocompletion after linebreaks.
if ( typeof Effect == 'undefined' )
throw("controls.js requires including script.aculo.us' effects.js library");
var Autocompleter = {}
Autocompleter.Base = function()
{
};
Autocompleter.Base.prototype = {
baseInitialize: function( element, update, options )
{
this.element = $(element);
this.update = $(update);
this.hasFocus = false;
this.changed = false;
this.active = false;
this.index = 0;
this.entryCount = 0;
if ( this.setOptions )
this.setOptions(options);
else
this.options = options || {};
this.options.paramName = this.options.paramName || this.element.name;
this.options.tokens = this.options.tokens || [];
this.options.frequency = this.options.frequency || 0.4;
this.options.minChars = this.options.minChars || 1;
this.options.onShow = this.options.onShow || function( element, update )
{
if ( !update.style.position || update.style.position == 'absolute' )
{
update.style.position = 'absolute';
Position.clone(element, update, {
setHeight: false,
offsetTop: element.offsetHeight
});
}
Effect.Appear(update, {duration:0.15});
};
this.options.onHide = this.options.onHide || function( element, update )
{
new Effect.Fade(update, {duration:0.15})
};
if ( typeof(this.options.tokens) == 'string' )
this.options.tokens = new Array(this.options.tokens);
this.observer = null;
this.element.setAttribute('autocomplete', 'off');
Element.hide(this.update);
Event.observe(this.element, "blur", this.onBlur.bindAsEventListener(this));
Event.observe(this.element, "keypress", this.onKeyPress.bindAsEventListener(this));
},
show: function()
{
if ( Element.getStyle(this.update, 'display') == 'none' ) this.options.onShow(this.element, this.update);
if ( !this.iefix && (navigator.appVersion.indexOf('MSIE') > 0) && (navigator.userAgent.indexOf('Opera') < 0) &&
(Element.getStyle(this.update, 'position') == 'absolute') )
{
new Insertion.After(this.update, '<iframe id="' + this.update.id + '_iefix" ' +
'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
this.iefix = $(this.update.id + '_iefix');
}
if ( this.iefix ) setTimeout(this.fixIEOverlapping.bind(this), 50);
},
fixIEOverlapping: function()
{
Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
this.iefix.style.zIndex = 1;
this.update.style.zIndex = 2;
Element.show(this.iefix);
},
hide: function()
{
this.stopIndicator();
if ( Element.getStyle(this.update, 'display') != 'none' ) this.options.onHide(this.element, this.update);
if ( this.iefix ) Element.hide(this.iefix);
},
startIndicator: function()
{
if ( this.options.indicator ) Element.show(this.options.indicator);
},
stopIndicator: function()
{
if ( this.options.indicator ) Element.hide(this.options.indicator);
},
onKeyPress: function( event )
{
if ( this.active )
switch ( event.keyCode )
{
case Event.KEY_TAB:
case Event.KEY_RETURN:
this.selectEntry();
Event.stop(event);
case Event.KEY_ESC:
this.hide();
this.active = false;
Event.stop(event);
return;
case Event.KEY_LEFT:
case Event.KEY_RIGHT:
return;
case Event.KEY_UP:
this.markPrevious();
this.render();
if ( navigator.appVersion.indexOf('AppleWebKit') > 0 ) Event.stop(event);
return;
case Event.KEY_DOWN:
this.markNext();
this.render();
if ( navigator.appVersion.indexOf('AppleWebKit') > 0 ) Event.stop(event);
return;
}
else
if ( event.keyCode == Event.KEY_TAB || event.keyCode == Event.KEY_RETURN ||
(navigator.appVersion.indexOf('AppleWebKit') > 0 && event.keyCode == 0) ) return;
this.changed = true;
this.hasFocus = true;
if ( this.observer ) clearTimeout(this.observer);
this.observer = setTimeout(this.onObserverEvent.bind(this), this.options.frequency * 1000);
},
activate: function()
{
this.changed = false;
this.hasFocus = true;
this.getUpdatedChoices();
},
onHover: function( event )
{
var element = Event.findElement(event, 'LI');
if ( this.index != element.autocompleteIndex )
{
this.index = element.autocompleteIndex;
this.render();
}
Event.stop(event);
},
onClick: function( event )
{
var element = Event.findElement(event, 'LI');
this.index = element.autocompleteIndex;
this.selectEntry();
this.hide();
},
onBlur: function( event )
{
// needed to make click events working
setTimeout(this.hide.bind(this), 250);
this.hasFocus = false;
this.active = false;
},
render: function()
{
if ( this.entryCount > 0 )
{
for ( var i = 0; i < this.entryCount; i++ )
this.index == i ? Element.addClassName(this.getEntry(i), "selected")
: Element.removeClassName(this.getEntry(i), "selected");
if ( this.hasFocus )
{
this.show();
this.active = true;
}
}
else
{
this.active = false;
this.hide();
}
},
markPrevious: function()
{
if ( this.index > 0 ) this.index--
else this.index = this.entryCount - 1;
this.getEntry(this.index).scrollIntoView(true);
},
markNext: function()
{
if ( this.index < this.entryCount - 1 ) this.index++
else this.index = 0;
this.getEntry(this.index).scrollIntoView(false);
},
getEntry: function( index )
{
return this.update.firstChild.childNodes[index];
},
getCurrentEntry: function()
{
return this.getEntry(this.index);
},
selectEntry: function()
{
this.active = false;
this.updateElement(this.getCurrentEntry());
},
updateElement: function( selectedElement )
{
if ( this.options.updateElement )
{
this.options.updateElement(selectedElement);
return;
}
var value = '';
if ( this.options.select )
{
var nodes = document.getElementsByClassName(this.options.select, selectedElement) || [];
if ( nodes.length > 0 ) value = Element.collectTextNodes(nodes[0], this.options.select);
}
else
value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
var lastTokenPos = this.findLastToken();
if ( lastTokenPos != -1 )
{
var newValue = this.element.value.substr(0, lastTokenPos + 1);
var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
if ( whitespace )
newValue += whitespace[0];
this.element.value = newValue + value;
}
else
{
this.element.value = value;
}
this.element.focus();
if ( this.options.afterUpdateElement )
this.options.afterUpdateElement(this.element, selectedElement);
},
updateChoices: function( choices )
{
if ( !this.changed && this.hasFocus )
{
this.update.innerHTML = choices;
Element.cleanWhitespace(this.update);
Element.cleanWhitespace(this.update.firstChild);
if ( this.update.firstChild && this.update.firstChild.childNodes )
{
this.entryCount = this.update.firstChild.childNodes.length;
for ( var i = 0; i < this.entryCount; i++ )
{
var entry = this.getEntry(i);
entry.autocompleteIndex = i;
this.addObservers(entry);
}
}
else
{
this.entryCount = 0;
}
this.stopIndicator();
this.index = 0;
if ( this.entryCount == 1 && this.options.autoSelect )
{
this.selectEntry();
this.hide();
}
else
{
this.render();
}
}
},
addObservers: function( element )
{
Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
Event.observe(element, "click", this.onClick.bindAsEventListener(this));
},
onObserverEvent: function()
{
this.changed = false;
if ( this.getToken().length >= this.options.minChars )
{
this.startIndicator();
this.getUpdatedChoices();
}
else
{
this.active = false;
this.hide();
}
},
getToken: function()
{
var tokenPos = this.findLastToken();
if ( tokenPos != -1 )
var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/, '').replace(/\s+$/, '');
else
var ret = this.element.value;
return /\n/.test(ret) ? '' : ret;
},
findLastToken: function()
{
var lastTokenPos = -1;
for ( var i = 0; i < this.options.tokens.length; i++ )
{
var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]);
if ( thisTokenPos > lastTokenPos )
lastTokenPos = thisTokenPos;
}
return lastTokenPos;
}
}
Ajax.Autocompleter = Class.create();
Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), {
initialize: function( element, update, url, options )
{
this.baseInitialize(element, update, options);
this.options.asynchronous = true;
this.options.onComplete = this.onComplete.bind(this);
this.options.defaultParams = this.options.parameters || null;
this.url = url;
},
getUpdatedChoices: function()
{
entry = encodeURIComponent(this.options.paramName) + '=' + encodeURIComponent(this.getToken());
this.options.parameters = this.options.callback ? this.options.callback(this.element, entry) : entry;
if ( this.options.defaultParams )
this.options.parameters += '&' + this.options.defaultParams;
new Ajax.Request(this.url, this.options);
},
onComplete: function( request )
{
this.updateChoices(request.responseText);
}
});
// The local array autocompleter. Used when you'd prefer to
// inject an array of autocompletion options into the page, rather
// than sending out Ajax queries, which can be quite slow sometimes.
//
// The constructor takes four parameters. The first two are, as usual,
// the id of the monitored textbox, and id of the autocompletion menu.
// The third is the array you want to autocomplete from, and the fourth
// is the options block.
//
// Extra local autocompletion options:
// - choices - How many autocompletion choices to offer
//
// - partialSearch - If false, the autocompleter will match entered
// text only at the beginning of strings in the
// autocomplete array. Defaults to true, which will
// match text at the beginning of any *word* in the
// strings in the autocomplete array. If you want to
// search anywhere in the string, additionally set
// the option fullSearch to true (default: off).
//
// - fullSsearch - Search anywhere in autocomplete array strings.
//
// - partialChars - How many characters to enter before triggering
// a partial match (unlike minChars, which defines
// how many characters are required to do any match
// at all). Defaults to 2.
//
// - ignoreCase - Whether to ignore case when autocompleting.
// Defaults to true.
//
// It's possible to pass in a custom function as the 'selector'
// option, if you prefer to write your own autocompletion logic.
// In that case, the other options above will not apply unless
// you support them.
Autocompleter.Local = Class.create();
Autocompleter.Local.prototype = Object.extend(new Autocompleter.Base(), {
initialize: function( element, update, array, options )
{
this.baseInitialize(element, update, options);
this.options.array = array;
},
getUpdatedChoices: function()
{
this.updateChoices(this.options.selector(this));
},
setOptions: function( options )
{
this.options = Object.extend({
choices: 10,
partialSearch: true,
partialChars: 2,
ignoreCase: true,
fullSearch: false,
selector: function( instance )
{
var ret = [];
// Beginning matches
var partial = [];
// Inside matches
var entry = instance.getToken();
var count = 0;
for ( var i = 0; i < instance.options.array.length && ret.length < instance.options.choices; i++ )
{
var elem = instance.options.array[i];
var foundPos = instance.options.ignoreCase ? elem.toLowerCase().indexOf(entry.toLowerCase())
: elem.indexOf(entry);
while ( foundPos != -1 )
{
if ( foundPos == 0 && elem.length != entry.length )
{
ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
elem.substr(entry.length) + "</li>");
break;
}
else if ( entry.length >= instance.options.partialChars && instance.options.partialSearch &&
foundPos != -1 )
{
if ( instance.options.fullSearch || /\s/.test(elem.substr(foundPos - 1, 1)) )
{
partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
elem.substr(foundPos, entry.length) + "</strong>" +
elem.substr(foundPos + entry.length) + "</li>");
break;
}
}
foundPos =
instance.options.ignoreCase ? elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1)
: elem.indexOf(entry, foundPos + 1);
}
}
if ( partial.length )
ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
return "<ul>" + ret.join('') + "</ul>";
}
}, options || {});
}
});
// AJAX in-place editor
//
// see documentation on http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor
// Use this if you notice weird scrolling problems on some browsers,
// the DOM might be a bit confused when this gets called so do this
// waits 1 ms (with setTimeout) until it does the activation
Field.scrollFreeActivate = function( field )
{
setTimeout(function()
{
Field.activate(field);
}, 1);
}
Ajax.InPlaceEditor = Class.create();
Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99";
Ajax.InPlaceEditor.prototype = {
initialize: function( element, url, options )
{
this.url = url;
this.element = $(element);
this.options = Object.extend({
okButton: true,
okText: "ok",
cancelLink: true,
cancelText: "cancel",
savingText: "Saving...",
clickToEditText: "Click to edit",
okText: "ok",
rows: 1,
onComplete: function( transport, element )
{
new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
},
onFailure: function( transport )
{
alert("Error communicating with the server: " + transport.responseText.stripTags());
},
callback: function( form )
{
return Form.serialize(form);
},
handleLineBreaks: true,
loadingText: 'Loading...',
savingClassName: 'inplaceeditor-saving',
loadingClassName: 'inplaceeditor-loading',
formClassName: 'inplaceeditor-form',
highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
highlightendcolor: "#FFFFFF",
externalControl: null,
submitOnBlur: false,
ajaxOptions: {},
evalScripts: false
}, options || {});
if ( !this.options.formId && this.element.id )
{
this.options.formId = this.element.id + "-inplaceeditor";
if ( $(this.options.formId) )
{
// there's already a form with that name, don't specify an id
this.options.formId = null;
}
}
if ( this.options.externalControl )
{
this.options.externalControl = $(this.options.externalControl);
}
this.originalBackground = Element.getStyle(this.element, 'background-color');
if ( !this.originalBackground )
{
this.originalBackground = "transparent";
}
this.element.title = this.options.clickToEditText;
this.onclickListener = this.enterEditMode.bindAsEventListener(this);
this.mouseoverListener = this.enterHover.bindAsEventListener(this);
this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
Event.observe(this.element, 'click', this.onclickListener);
Event.observe(this.element, 'mouseover', this.mouseoverListener);
Event.observe(this.element, 'mouseout', this.mouseoutListener);
if ( this.options.externalControl )
{
Event.observe(this.options.externalControl, 'click', this.onclickListener);
Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
}
},
enterEditMode: function( evt )
{
if ( this.saving ) return;
if ( this.editing ) return;
this.editing = true;
this.onEnterEditMode();
if ( this.options.externalControl )
{
Element.hide(this.options.externalControl);
}
Element.hide(this.element);
this.createForm();
this.element.parentNode.insertBefore(this.form, this.element);
if ( !this.options.loadTextURL ) Field.scrollFreeActivate(this.editField);
// stop the event to avoid a page refresh in Safari
if ( evt )
{
Event.stop(evt);
}
return false;
},
createForm: function()
{
this.form = document.createElement("form");
this.form.id = this.options.formId;
Element.addClassName(this.form, this.options.formClassName)
this.form.onsubmit = this.onSubmit.bind(this);
this.createEditField();
if ( this.options.textarea )
{
var br = document.createElement("br");
this.form.appendChild(br);
}
if ( this.options.okButton )
{
okButton = document.createElement("input");
okButton.type = "submit";
okButton.value = this.options.okText;
okButton.className = 'editor_ok_button';
this.form.appendChild(okButton);
}
if ( this.options.cancelLink )
{
cancelLink = document.createElement("a");
cancelLink.href = "#";
cancelLink.appendChild(document.createTextNode(this.options.cancelText));
cancelLink.onclick = this.onclickCancel.bind(this);
cancelLink.className = 'editor_cancel';
this.form.appendChild(cancelLink);
}
},
hasHTMLLineBreaks: function( string )
{
if ( !this.options.handleLineBreaks ) return false;
return string.match(/<br/i) || string.match(/<p>/i);
},
convertHTMLLineBreaks: function( string )
{
return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, "");
},
createEditField: function()
{
var text;
if ( this.options.loadTextURL )
{
text = this.options.loadingText;
}
else
{
text = this.getText();
}
var obj = this;
if ( this.options.rows == 1 && !this.hasHTMLLineBreaks(text) )
{
this.options.textarea = false;
var textField = document.createElement("input");
textField.obj = this;
textField.type = "text";
textField.name = "value";
textField.value = text;
textField.style.backgroundColor = this.options.highlightcolor;
textField.className = 'editor_field';
var size = this.options.size || this.options.cols || 0;
if ( size != 0 ) textField.size = size;
if ( this.options.submitOnBlur )
textField.onblur = this.onSubmit.bind(this);
this.editField = textField;
}
else
{
this.options.textarea = true;
var textArea = document.createElement("textarea");
textArea.obj = this;
textArea.name = "value";
textArea.value = this.convertHTMLLineBreaks(text);
textArea.rows = this.options.rows;
textArea.cols = this.options.cols || 40;
textArea.className = 'editor_field';
if ( this.options.submitOnBlur )
textArea.onblur = this.onSubmit.bind(this);
this.editField = textArea;
}
if ( this.options.loadTextURL )
{
this.loadExternalText();
}
this.form.appendChild(this.editField);
},
getText: function()
{
return this.element.innerHTML;
},
loadExternalText: function()
{
Element.addClassName(this.form, this.options.loadingClassName);
this.editField.disabled = true;
new Ajax.Request(this.options.loadTextURL, Object.extend({
asynchronous: true,
onComplete: this.onLoadedExternalText.bind(this)
}, this.options.ajaxOptions));
},
onLoadedExternalText: function( transport )
{
Element.removeClassName(this.form, this.options.loadingClassName);
this.editField.disabled = false;
this.editField.value = transport.responseText.stripTags();
Field.scrollFreeActivate(this.editField);
},
onclickCancel: function()
{
this.onComplete();
this.leaveEditMode();
return false;
},
onFailure: function( transport )
{
this.options.onFailure(transport);
if ( this.oldInnerHTML )
{
this.element.innerHTML = this.oldInnerHTML;
this.oldInnerHTML = null;
}
return false;
},
onSubmit: function()
{
// onLoading resets these so we need to save them away for the Ajax call
var form = this.form;
var value = this.editField.value;
// do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
// which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
// to be displayed indefinitely
this.onLoading();
if ( this.options.evalScripts )
{
new Ajax.Request(this.url, Object.extend({
parameters: this.options.callback(form, value),
onComplete: this.onComplete.bind(this),
onFailure: this.onFailure.bind(this),
asynchronous:true,
evalScripts:true
}, this.options.ajaxOptions));
}
else
{
new Ajax.Updater({ success: this.element,
// don't update on failure (this could be an option)
failure: null }, this.url, Object.extend({
parameters: this.options.callback(form, value),
onComplete: this.onComplete.bind(this),
onFailure: this.onFailure.bind(this)
}, this.options.ajaxOptions));
}
// stop the event to avoid a page refresh in Safari
if ( arguments.length > 1 )
{
Event.stop(arguments[0]);
}
return false;
},
onLoading: function()
{
this.saving = true;
this.removeForm();
this.leaveHover();
this.showSaving();
},
showSaving: function()
{
this.oldInnerHTML = this.element.innerHTML;
this.element.innerHTML = this.options.savingText;
Element.addClassName(this.element, this.options.savingClassName);
this.element.style.backgroundColor = this.originalBackground;
Element.show(this.element);
},
removeForm: function()
{
if ( this.form )
{
if ( this.form.parentNode ) Element.remove(this.form);
this.form = null;
}
},
enterHover: function()
{
if ( this.saving ) return;
this.element.style.backgroundColor = this.options.highlightcolor;
if ( this.effect )
{
this.effect.cancel();
}
Element.addClassName(this.element, this.options.hoverClassName)
},
leaveHover: function()
{
if ( this.options.backgroundColor )
{
this.element.style.backgroundColor = this.oldBackground;
}
Element.removeClassName(this.element, this.options.hoverClassName)
if ( this.saving ) return;
this.effect = new Effect.Highlight(this.element, {
startcolor: this.options.highlightcolor,
endcolor: this.options.highlightendcolor,
restorecolor: this.originalBackground
});
},
leaveEditMode: function()
{
Element.removeClassName(this.element, this.options.savingClassName);
this.removeForm();
this.leaveHover();
this.element.style.backgroundColor = this.originalBackground;
Element.show(this.element);
if ( this.options.externalControl )
{
Element.show(this.options.externalControl);
}
this.editing = false;
this.saving = false;
this.oldInnerHTML = null;
this.onLeaveEditMode();
},
onComplete: function( transport )
{
this.leaveEditMode();
this.options.onComplete.bind(this)(transport, this.element);
},
onEnterEditMode: function()
{
},
onLeaveEditMode: function()
{
},
dispose: function()
{
if ( this.oldInnerHTML )
{
this.element.innerHTML = this.oldInnerHTML;
}
this.leaveEditMode();
Event.stopObserving(this.element, 'click', this.onclickListener);
Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
if ( this.options.externalControl )
{
Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
}
}
};
Ajax.InPlaceCollectionEditor = Class.create();
Object.extend(Ajax.InPlaceCollectionEditor.prototype, Ajax.InPlaceEditor.prototype);
Object.extend(Ajax.InPlaceCollectionEditor.prototype, {
createEditField: function()
{
if ( !this.cached_selectTag )
{
var selectTag = document.createElement("select");
var collection = this.options.collection || [];
var optionTag;
collection.each(function( e, i )
{
optionTag = document.createElement("option");
optionTag.value = (e instanceof Array) ? e[0] : e;
if ( (typeof this.options.value == 'undefined') &&
((e instanceof Array) ? this.element.innerHTML == e[1] : e ==
optionTag.value) ) optionTag.selected =
true;
if ( this.options.value == optionTag.value ) optionTag.selected = true;
optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e));
selectTag.appendChild(optionTag);
}.bind(this));
this.cached_selectTag = selectTag;
}
this.editField = this.cached_selectTag;
if ( this.options.loadTextURL ) this.loadExternalText();
this.form.appendChild(this.editField);
this.options.callback = function( form, value )
{
return "value=" + encodeURIComponent(value);
}
}
});
// Delayed observer, like Form.Element.Observer,
// but waits for delay after last key input
// Ideal for live-search fields
Form.Element.DelayedObserver = Class.create();
Form.Element.DelayedObserver.prototype = {
initialize: function( element, delay, callback )
{
this.delay = delay || 0.5;
this.element = $(element);
this.callback = callback;
this.timer = null;
this.lastValue = $F(this.element);
Event.observe(this.element, 'keyup', this.delayedListener.bindAsEventListener(this));
},
delayedListener: function( event )
{
if ( this.lastValue == $F(this.element) ) return;
if ( this.timer ) clearTimeout(this.timer);
this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
this.lastValue = $F(this.element);
},
onTimerEvent: function()
{
this.timer = null;
this.callback(this.element, $F(this.element));
}
};

View File

@ -1,72 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// script.aculo.us scriptaculous.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
var Scriptaculous = {
Version: '1.6.4',
require: function( libraryName )
{
// inserting via DOM fails in Safari 2.0, so brute force approach
document.write('<script type="text/javascript" src="' + libraryName + '"></script>');
},
load: function()
{
if ( (typeof Prototype == 'undefined') || (typeof Element == 'undefined') ||
(typeof Element.Methods == 'undefined') ||
parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1]) < 1.5 )
throw("script.aculo.us requires the Prototype JavaScript framework >= 1.5.0");
$A(document.getElementsByTagName("script")).findAll(function( s )
{
return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
}).each(function( s )
{
var path = s.src.replace(/scriptaculous\.js(\?.*)?$/, '');
var includes = s.src.match(/\?.*load=([a-z,]*)/);
(includes ? includes[1] : 'builder,effects,dragdrop,controls,slider').split(',').each(function( include )
{
Scriptaculous.require(path + include + '.js')
});
});
}
}
Scriptaculous.load();

View File

@ -1,365 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// script.aculo.us slider.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
// Copyright (c) 2005 Marty Haught, Thomas Fuchs
//
// See http://script.aculo.us for more info
//
// 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.
if ( !Control ) var Control = {};
Control.Slider = Class.create();
// options:
// axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
// onChange(value)
// onSlide(value)
Control.Slider.prototype = {
initialize: function( handle, track, options )
{
var slider = this;
if ( handle instanceof Array )
{
this.handles = handle.collect(function( e )
{
return $(e)
});
}
else
{
this.handles = [$(handle)];
}
this.track = $(track);
this.options = options || {};
this.axis = this.options.axis || 'horizontal';
this.increment = this.options.increment || 1;
this.step = parseInt(this.options.step || '1');
this.range = this.options.range || $R(0, 1);
this.value = 0;
// assure backwards compat
this.values = this.handles.map(function()
{
return 0
});
this.spans = this.options.spans ? this.options.spans.map(function( s )
{
return $(s)
}) : false;
this.options.startSpan = $(this.options.startSpan || null);
this.options.endSpan = $(this.options.endSpan || null);
this.restricted = this.options.restricted || false;
this.maximum = this.options.maximum || this.range.end;
this.minimum = this.options.minimum || this.range.start;
// Will be used to align the handle onto the track, if necessary
this.alignX = parseInt(this.options.alignX || '0');
this.alignY = parseInt(this.options.alignY || '0');
this.trackLength = this.maximumOffset() - this.minimumOffset();
this.handleLength = this.isVertical() ? (this.handles[0].offsetHeight != 0 ? this.handles[0].offsetHeight
: this.handles[0].style.height.replace(/px$/, "")) : (this.handles[0].offsetWidth != 0
? this.handles[0].offsetWidth : this.handles[0].style.width.replace(/px$/, ""));
this.active = false;
this.dragging = false;
this.disabled = false;
if ( this.options.disabled ) this.setDisabled();
// Allowed values array
this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
if ( this.allowedValues )
{
this.minimum = this.allowedValues.min();
this.maximum = this.allowedValues.max();
}
this.eventMouseDown = this.startDrag.bindAsEventListener(this);
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.update.bindAsEventListener(this);
// Initialize handles in reverse (make sure first handle is active)
this.handles.each(function( h, i )
{
i = slider.handles.length - 1 - i;
slider.setValue(parseFloat((slider.options.sliderValue instanceof Array ? slider.options.sliderValue[i]
: slider.options.sliderValue) || slider.range.start), i);
Element.makePositioned(h);
// fix IE
Event.observe(h, "mousedown", slider.eventMouseDown);
});
Event.observe(this.track, "mousedown", this.eventMouseDown);
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
this.initialized = true;
},
dispose: function()
{
var slider = this;
Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
this.handles.each(function( h )
{
Event.stopObserving(h, "mousedown", slider.eventMouseDown);
});
},
setDisabled: function()
{
this.disabled = true;
},
setEnabled: function()
{
this.disabled = false;
},
getNearestValue: function( value )
{
if ( this.allowedValues )
{
if ( value >= this.allowedValues.max() ) return(this.allowedValues.max());
if ( value <= this.allowedValues.min() ) return(this.allowedValues.min());
var offset = Math.abs(this.allowedValues[0] - value);
var newValue = this.allowedValues[0];
this.allowedValues.each(function( v )
{
var currentOffset = Math.abs(v - value);
if ( currentOffset <= offset )
{
newValue = v;
offset = currentOffset;
}
});
return newValue;
}
if ( value > this.range.end ) return this.range.end;
if ( value < this.range.start ) return this.range.start;
return value;
},
setValue: function( sliderValue, handleIdx )
{
if ( !this.active )
{
this.activeHandleIdx = handleIdx || 0;
this.activeHandle = this.handles[this.activeHandleIdx];
this.updateStyles();
}
handleIdx = handleIdx || this.activeHandleIdx || 0;
if ( this.initialized && this.restricted )
{
if ( (handleIdx > 0) && (sliderValue < this.values[handleIdx - 1]) )
sliderValue = this.values[handleIdx - 1];
if ( (handleIdx < (this.handles.length - 1)) && (sliderValue > this.values[handleIdx + 1]) )
sliderValue = this.values[handleIdx + 1];
}
sliderValue = this.getNearestValue(sliderValue);
this.values[handleIdx] = sliderValue;
this.value = this.values[0];
// assure backwards compat
this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = this.translateToPx(sliderValue);
this.drawSpans();
if ( !this.dragging || !this.event ) this.updateFinished();
},
setValueBy: function( delta, handleIdx )
{
this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, handleIdx || this.activeHandleIdx ||
0);
},
translateToPx: function( value )
{
return Math.round(((this.trackLength - this.handleLength) / (this.range.end - this.range.start)) *
(value - this.range.start)) + "px";
},
translateToValue: function( offset )
{
return ((offset / (this.trackLength - this.handleLength) * (this.range.end - this.range.start)) +
this.range.start);
},
getRange: function( range )
{
var v = this.values.sortBy(Prototype.K);
range = range || 0;
return $R(v[range], v[range + 1]);
},
minimumOffset: function()
{
return(this.isVertical() ? this.alignY : this.alignX);
},
maximumOffset: function()
{
return(this.isVertical() ? (this.track.offsetHeight != 0 ? this.track.offsetHeight
: this.track.style.height.replace(/px$/, "")) - this.alignY : (this.track.offsetWidth != 0
? this.track.offsetWidth : this.track.style.width.replace(/px$/, "")) - this.alignY);
},
isVertical: function()
{
return (this.axis == 'vertical');
},
drawSpans: function()
{
var slider = this;
if ( this.spans )
$R(0, this.spans.length - 1).each(function( r )
{
slider.setSpan(slider.spans[r], slider.getRange(r))
});
if ( this.options.startSpan )
this.setSpan(this.options.startSpan, $R(0, this.values.length > 1 ? this.getRange(0).min() : this.value));
if ( this.options.endSpan )
this.setSpan(this.options.endSpan, $R(this.values.length > 1 ? this.getRange(this.spans.length - 1).max()
: this.value, this.maximum));
},
setSpan: function( span, range )
{
if ( this.isVertical() )
{
span.style.top = this.translateToPx(range.start);
span.style.height = this.translateToPx(range.end - range.start + this.range.start);
}
else
{
span.style.left = this.translateToPx(range.start);
span.style.width = this.translateToPx(range.end - range.start + this.range.start);
}
},
updateStyles: function()
{
this.handles.each(function( h )
{
Element.removeClassName(h, 'selected')
});
Element.addClassName(this.activeHandle, 'selected');
},
startDrag: function( event )
{
if ( Event.isLeftClick(event) )
{
if ( !this.disabled )
{
this.active = true;
var handle = Event.element(event);
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var track = handle;
if ( track == this.track )
{
var offsets = Position.cumulativeOffset(this.track);
this.event = event;
this.setValue(this.translateToValue((this.isVertical() ? pointer[1] - offsets[1] : pointer[0] -
offsets[0]) -
(this.handleLength / 2)));
var offsets = Position.cumulativeOffset(this.activeHandle);
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
}
else
{
// find the handle (prevents issues with Safari)
while ( (this.handles.indexOf(handle) == -1) && handle.parentNode )
handle = handle.parentNode;
this.activeHandle = handle;
this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
this.updateStyles();
var offsets = Position.cumulativeOffset(this.activeHandle);
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
}
}
Event.stop(event);
}
},
update: function( event )
{
if ( this.active )
{
if ( !this.dragging ) this.dragging = true;
this.draw(event);
// fix AppleWebKit rendering
if ( navigator.appVersion.indexOf('AppleWebKit') > 0 ) window.scrollBy(0, 0);
Event.stop(event);
}
},
draw: function( event )
{
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var offsets = Position.cumulativeOffset(this.track);
pointer[0] -= this.offsetX + offsets[0];
pointer[1] -= this.offsetY + offsets[1];
this.event = event;
this.setValue(this.translateToValue(this.isVertical() ? pointer[1] : pointer[0]));
if ( this.initialized && this.options.onSlide )
this.options.onSlide(this.values.length > 1 ? this.values : this.value, this);
},
endDrag: function( event )
{
if ( this.active && this.dragging )
{
this.finishDrag(event, true);
Event.stop(event);
}
this.active = false;
this.dragging = false;
},
finishDrag: function( event, success )
{
this.active = false;
this.dragging = false;
this.updateFinished();
},
updateFinished: function()
{
if ( this.initialized && this.options.onChange )
this.options.onChange(this.values.length > 1 ? this.values : this.value, this);
this.event = null;
}
}

View File

@ -1,744 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// script.aculo.us unittest.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005 Jon Tirsen (http://www.tirsen.com)
// (c) 2005 Michael Schuerig (http://www.schuerig.de/michael/)
//
// 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.
// experimental, Firefox-only
Event.simulateMouse = function( element, eventName )
{
var options = Object.extend({
pointerX: 0,
pointerY: 0,
buttons: 0
}, arguments[2] || {});
var oEvent = document.createEvent("MouseEvents");
oEvent.initMouseEvent(eventName, true, true, document.defaultView, options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY, false, false, false, false, 0, $(element));
if ( this.mark ) Element.remove(this.mark);
this.mark = document.createElement('div');
this.mark.appendChild(document.createTextNode(" "));
document.body.appendChild(this.mark);
this.mark.style.position = 'absolute';
this.mark.style.top = options.pointerY + "px";
this.mark.style.left = options.pointerX + "px";
this.mark.style.width = "5px";
this.mark.style.height = "5px;";
this.mark.style.borderTop = "1px solid red;"
this.mark.style.borderLeft = "1px solid red;"
if ( this.step )
alert('[' + new Date().getTime().toString() + '] ' + eventName + '/' + Test.Unit.inspect(options));
$(element).dispatchEvent(oEvent);
};
// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
// You need to downgrade to 1.0.4 for now to get this working
// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
Event.simulateKey = function( element, eventName )
{
var options = Object.extend({
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: 0,
charCode: 0
}, arguments[2] || {});
var oEvent = document.createEvent("KeyEvents");
oEvent.initKeyEvent(eventName, true, true, window, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.keyCode, options.charCode);
$(element).dispatchEvent(oEvent);
};
Event.simulateKeys = function( element, command )
{
for ( var i = 0; i < command.length; i++ )
{
Event.simulateKey(element, 'keypress', {charCode:command.charCodeAt(i)});
}
};
var Test = {}
Test.Unit = {};
// security exception workaround
Test.Unit.inspect = Object.inspect;
Test.Unit.Logger = Class.create();
Test.Unit.Logger.prototype = {
initialize: function( log )
{
this.log = $(log);
if ( this.log )
{
this._createLogTable();
}
},
start: function( testName )
{
if ( !this.log ) return;
this.testName = testName;
this.lastLogLine = document.createElement('tr');
this.statusCell = document.createElement('td');
this.nameCell = document.createElement('td');
this.nameCell.appendChild(document.createTextNode(testName));
this.messageCell = document.createElement('td');
this.lastLogLine.appendChild(this.statusCell);
this.lastLogLine.appendChild(this.nameCell);
this.lastLogLine.appendChild(this.messageCell);
this.loglines.appendChild(this.lastLogLine);
},
finish: function( status, summary )
{
if ( !this.log ) return;
this.lastLogLine.className = status;
this.statusCell.innerHTML = status;
this.messageCell.innerHTML = this._toHTML(summary);
},
message: function( message )
{
if ( !this.log ) return;
this.messageCell.innerHTML = this._toHTML(message);
},
summary: function( summary )
{
if ( !this.log ) return;
this.logsummary.innerHTML = this._toHTML(summary);
},
_createLogTable: function()
{
this.log.innerHTML = '<div id="logsummary"></div>' + '<table id="logtable">' +
'<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' +
'<tbody id="loglines"></tbody>' + '</table>';
this.logsummary = $('logsummary')
this.loglines = $('loglines');
},
_toHTML: function( txt )
{
return txt.escapeHTML().replace(/\n/g, "<br/>");
}
}
Test.Unit.Runner = Class.create();
Test.Unit.Runner.prototype = {
initialize: function( testcases )
{
this.options = Object.extend({
testLog: 'testlog'
}, arguments[1] || {});
this.options.resultsURL = this.parseResultsURLQueryParameter();
if ( this.options.testLog )
{
this.options.testLog = $(this.options.testLog) || null;
}
if ( this.options.tests )
{
this.tests = [];
for ( var i = 0; i < this.options.tests.length; i++ )
{
if ( /^test/.test(this.options.tests[i]) )
{
this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
}
}
}
else
{
if ( this.options.test )
{
this.tests =
[new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
}
else
{
this.tests = [];
for ( var testcase in testcases )
{
if ( /^test/.test(testcase) )
{
this.tests.push(new Test.Unit.Testcase(this.options.context ? ' -> ' +
this.options.titles[testcase]
: testcase, testcases[testcase], testcases["setup"], testcases["teardown"]));
}
}
}
}
this.currentTest = 0;
this.logger = new Test.Unit.Logger(this.options.testLog);
setTimeout(this.runTests.bind(this), 1000);
},
parseResultsURLQueryParameter: function()
{
return window.location.search.parseQuery()["resultsURL"];
},
// Returns:
// "ERROR" if there was an error,
// "FAILURE" if there was a failure, or
// "SUCCESS" if there was neither
getResult: function()
{
var hasFailure = false;
for ( var i = 0; i < this.tests.length; i++ )
{
if ( this.tests[i].errors > 0 )
{
return "ERROR";
}
if ( this.tests[i].failures > 0 )
{
hasFailure = true;
}
}
if ( hasFailure )
{
return "FAILURE";
}
else
{
return "SUCCESS";
}
},
postResults: function()
{
if ( this.options.resultsURL )
{
new Ajax.Request(this.options.resultsURL, { method: 'get', parameters: 'result=' +
this.getResult(), asynchronous: false });
}
},
runTests: function()
{
var test = this.tests[this.currentTest];
if ( !test )
{
// finished!
this.postResults();
this.logger.summary(this.summary());
return;
}
if ( !test.isWaiting )
{
this.logger.start(test.name);
}
test.run();
if ( test.isWaiting )
{
this.logger.message("Waiting for " + test.timeToWait + "ms");
setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
}
else
{
this.logger.finish(test.status(), test.summary());
this.currentTest++;
// tail recursive, hopefully the browser will skip the stackframe
this.runTests();
}
},
summary: function()
{
var assertions = 0;
var failures = 0;
var errors = 0;
var messages = [];
for ( var i = 0; i < this.tests.length; i++ )
{
assertions += this.tests[i].assertions;
failures += this.tests[i].failures;
errors += this.tests[i].errors;
}
return (
(this.options.context ? this.options.context + ': ' : '') + this.tests.length + " tests, " + assertions +
" assertions, " + failures + " failures, " + errors + " errors");
}
}
Test.Unit.Assertions = Class.create();
Test.Unit.Assertions.prototype = {
initialize: function()
{
this.assertions = 0;
this.failures = 0;
this.errors = 0;
this.messages = [];
},
summary: function()
{
return (
this.assertions + " assertions, " + this.failures + " failures, " + this.errors + " errors" + "\n" +
this.messages.join("\n"));
},
pass: function()
{
this.assertions++;
},
fail: function( message )
{
this.failures++;
this.messages.push("Failure: " + message);
},
info: function( message )
{
this.messages.push("Info: " + message);
},
error: function( error )
{
this.errors++;
this.messages.push(error.name + ": " + error.message + "(" + Test.Unit.inspect(error) + ")");
},
status: function()
{
if ( this.failures > 0 ) return 'failed';
if ( this.errors > 0 ) return 'error';
return 'passed';
},
assert: function( expression )
{
var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
try
{
expression ? this.pass() : this.fail(message);
}
catch( e )
{
this.error(e);
}
},
assertEqual: function( expected, actual )
{
var message = arguments[2] || "assertEqual";
try
{
(expected == actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"');
}
catch( e )
{
this.error(e);
}
},
assertEnumEqual: function( expected, actual )
{
var message = arguments[2] || "assertEnumEqual";
try
{
$A(expected).length == $A(actual).length && expected.zip(actual).all(function( pair )
{
return pair[0] == pair[1]
}) ? this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) + ', actual ' +
Test.Unit.inspect(actual));
}
catch( e )
{
this.error(e);
}
},
assertNotEqual: function( expected, actual )
{
var message = arguments[2] || "assertNotEqual";
try
{
(expected != actual) ? this.pass() : this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"');
}
catch( e )
{
this.error(e);
}
},
assertIdentical: function( expected, actual )
{
var message = arguments[2] || "assertIdentical";
try
{
(expected === actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"');
}
catch( e )
{
this.error(e);
}
},
assertNotIdentical: function( expected, actual )
{
var message = arguments[2] || "assertNotIdentical";
try
{
!(expected === actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"');
}
catch( e )
{
this.error(e);
}
},
assertNull: function( obj )
{
var message = arguments[1] || 'assertNull'
try
{
(obj == null) ? this.pass() : this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"');
}
catch( e )
{
this.error(e);
}
},
assertMatch: function( expected, actual )
{
var message = arguments[2] || 'assertMatch';
var regex = new RegExp(expected);
try
{
(regex.exec(actual)) ? this.pass() : this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) +
' did not match: ' + Test.Unit.inspect(actual) + '"');
}
catch( e )
{
this.error(e);
}
},
assertHidden: function( element )
{
var message = arguments[1] || 'assertHidden';
this.assertEqual("none", element.style.display, message);
},
assertNotNull: function( object )
{
var message = arguments[1] || 'assertNotNull';
this.assert(object != null, message);
},
assertType: function( expected, actual )
{
var message = arguments[2] || 'assertType';
try
{
(actual.constructor == expected) ? this.pass() : this.fail(message + ': expected "' +
Test.Unit.inspect(expected) + '", actual "' +
(actual.constructor) + '"');
}
catch( e )
{
this.error(e);
}
},
assertNotOfType: function( expected, actual )
{
var message = arguments[2] || 'assertNotOfType';
try
{
(actual.constructor != expected) ? this.pass() : this.fail(message + ': expected "' +
Test.Unit.inspect(expected) + '", actual "' +
(actual.constructor) + '"');
}
catch( e )
{
this.error(e);
}
},
assertInstanceOf: function( expected, actual )
{
var message = arguments[2] || 'assertInstanceOf';
try
{
(actual instanceof expected) ? this.pass() : this.fail(message +
": object was not an instance of the expected type");
}
catch( e )
{
this.error(e);
}
},
assertNotInstanceOf: function( expected, actual )
{
var message = arguments[2] || 'assertNotInstanceOf';
try
{
!(actual instanceof expected) ? this.pass() : this.fail(message +
": object was an instance of the not expected type");
}
catch( e )
{
this.error(e);
}
},
assertRespondsTo: function( method, obj )
{
var message = arguments[2] || 'assertRespondsTo';
try
{
(obj[method] && typeof obj[method] == 'function') ? this.pass() : this.fail(message +
": object doesn't respond to [" +
method + "]");
}
catch( e )
{
this.error(e);
}
},
assertReturnsTrue: function( method, obj )
{
var message = arguments[2] || 'assertReturnsTrue';
try
{
var m = obj[method];
if ( !m ) m = obj['is' + method.charAt(0).toUpperCase() + method.slice(1)];
m() ? this.pass() : this.fail(message + ": method returned false");
}
catch( e )
{
this.error(e);
}
},
assertReturnsFalse: function( method, obj )
{
var message = arguments[2] || 'assertReturnsFalse';
try
{
var m = obj[method];
if ( !m ) m = obj['is' + method.charAt(0).toUpperCase() + method.slice(1)];
!m() ? this.pass() : this.fail(message + ": method returned true");
}
catch( e )
{
this.error(e);
}
},
assertRaise: function( exceptionName, method )
{
var message = arguments[2] || 'assertRaise';
try
{
method();
this.fail(message + ": exception expected but none was raised");
}
catch( e )
{
(e.name == exceptionName) ? this.pass() : this.error(e);
}
},
assertElementsMatch: function()
{
var expressions = $A(arguments), elements = $A(expressions.shift());
if ( elements.length != expressions.length )
{
this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length +
' expressions');
return false;
}
elements.zip(expressions).all(function( pair, index )
{
var element = $(pair.first()), expression = pair.last();
if ( element.match(expression) ) return true;
this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' +
element.inspect());
}.bind(this)) && this.pass();
},
assertElementMatches: function( element, expression )
{
this.assertElementsMatch([element], expression);
},
benchmark: function( operation, iterations )
{
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date()) - startAt);
this.info((arguments[2] || 'Operation') + ' finished ' + iterations + ' iterations in ' + (timeTaken / 1000) +
's');
return timeTaken;
},
_isVisible: function( element )
{
element = $(element);
if ( !element.parentNode ) return true;
this.assertNotNull(element);
if ( element.style && Element.getStyle(element, 'display') == 'none' )
return false;
return this._isVisible(element.parentNode);
},
assertNotVisible: function( element )
{
this.assert(!this._isVisible(element), Test.Unit.inspect(element) +
" was not hidden and didn't have a hidden parent either. " +
("" || arguments[1]));
},
assertVisible: function( element )
{
this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
},
benchmark: function( operation, iterations )
{
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date()) - startAt);
this.info((arguments[2] || 'Operation') + ' finished ' + iterations + ' iterations in ' + (timeTaken / 1000) +
's');
return timeTaken;
}
}
Test.Unit.Testcase = Class.create();
Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
initialize: function( name, test, setup, teardown )
{
Test.Unit.Assertions.prototype.initialize.bind(this)();
this.name = name;
if ( typeof test == 'string' )
{
test = test.gsub(/(\.should[^\(]+\()/, '#{0}this,');
test = test.gsub(/(\.should[^\(]+)\(this,\)/, '#{1}(this)');
this.test = function()
{
eval('with(this){' + test + '}');
}
}
else
{
this.test = test || function()
{
};
}
this.setup = setup || function()
{
};
this.teardown = teardown || function()
{
};
this.isWaiting = false;
this.timeToWait = 1000;
},
wait: function( time, nextPart )
{
this.isWaiting = true;
this.test = nextPart;
this.timeToWait = time;
},
run: function()
{
try
{
try
{
if ( !this.isWaiting ) this.setup.bind(this)();
this.isWaiting = false;
this.test.bind(this)();
}
finally
{
if ( !this.isWaiting )
{
this.teardown.bind(this)();
}
}
}
catch( e )
{
this.error(e);
}
}
});
// *EXPERIMENTAL* BDD-style testing to please non-technical folk
// This draws many ideas from RSpec http://rspec.rubyforge.org/
Test.setupBDDExtensionMethods = function()
{
var METHODMAP = {
shouldEqual: 'assertEqual',
shouldNotEqual: 'assertNotEqual',
shouldEqualEnum: 'assertEnumEqual',
shouldBeA: 'assertType',
shouldNotBeA: 'assertNotOfType',
shouldBeAn: 'assertType',
shouldNotBeAn: 'assertNotOfType',
shouldBeNull: 'assertNull',
shouldNotBeNull: 'assertNotNull',
shouldBe: 'assertReturnsTrue',
shouldNotBe: 'assertReturnsFalse',
shouldRespondTo: 'assertRespondsTo'
};
Test.BDDMethods = {};
for ( m in METHODMAP )
{
Test.BDDMethods[m] =
eval('function(){' + 'var args = $A(arguments);' + 'var scope = args.shift();' + 'scope.' + METHODMAP[m] +
'.apply(scope,(args || []).concat([this])); }');
}
[Array.prototype, String.prototype, Number.prototype].each(function( p )
{
Object.extend(p, Test.BDDMethods)
});
}
Test.context = function( name, spec, log )
{
Test.setupBDDExtensionMethods();
var compiledSpec = {};
var titles = {};
for ( specName in spec )
{
switch ( specName )
{
case "setup":
case "teardown":
compiledSpec[specName] = spec[specName];
break;
default:
var testName = 'test' + specName.gsub(/\s+/, '-').camelize();
var body = spec[specName].toString().split('\n').slice(1);
if ( /^\{/.test(body[0]) ) body = body.slice(1);
body.pop();
body = body.map(function( statement )
{
return statement.strip()
});
compiledSpec[testName] = body.join('\n');
titles[testName] = specName;
}
}
new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
};