prototype.js 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286
  1. /* Prototype JavaScript framework, version 1.5.1.2
  2. * (c) 2005-2008 Sam Stephenson
  3. *
  4. * Prototype is freely distributable under the terms of an MIT-style license.
  5. * For details, see the Prototype web site: http://www.prototypejs.org/
  6. *
  7. /*--------------------------------------------------------------------------*/
  8. var Prototype = {
  9. Version: '1.5.1.2',
  10. Browser: {
  11. IE: !!(window.attachEvent && !window.opera),
  12. Opera: !!window.opera,
  13. WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
  14. Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1
  15. },
  16. BrowserFeatures: {
  17. XPath: !!document.evaluate,
  18. ElementExtensions: !!window.HTMLElement,
  19. SpecificElementExtensions:
  20. (document.createElement('div').__proto__ !==
  21. document.createElement('form').__proto__)
  22. },
  23. ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
  24. JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
  25. emptyFunction: function() { },
  26. K: function(x) { return x }
  27. }
  28. var Class = {
  29. create: function() {
  30. return function() {
  31. this.initialize.apply(this, arguments);
  32. }
  33. }
  34. }
  35. var Abstract = new Object();
  36. Object.extend = function(destination, source) {
  37. for (var property in source) {
  38. destination[property] = source[property];
  39. }
  40. return destination;
  41. }
  42. Object.extend(Object, {
  43. inspect: function(object) {
  44. try {
  45. if (object === undefined) return 'undefined';
  46. if (object === null) return 'null';
  47. return object.inspect ? object.inspect() : object.toString();
  48. } catch (e) {
  49. if (e instanceof RangeError) return '...';
  50. throw e;
  51. }
  52. },
  53. toJSON: function(object) {
  54. var type = typeof object;
  55. switch(type) {
  56. case 'undefined':
  57. case 'function':
  58. case 'unknown': return;
  59. case 'boolean': return object.toString();
  60. }
  61. if (object === null) return 'null';
  62. if (object.toJSON) return object.toJSON();
  63. if (object.ownerDocument === document) return;
  64. var results = [];
  65. for (var property in object) {
  66. var value = Object.toJSON(object[property]);
  67. if (value !== undefined)
  68. results.push(property.toJSON() + ': ' + value);
  69. }
  70. return '{' + results.join(', ') + '}';
  71. },
  72. keys: function(object) {
  73. var keys = [];
  74. for (var property in object)
  75. keys.push(property);
  76. return keys;
  77. },
  78. values: function(object) {
  79. var values = [];
  80. for (var property in object)
  81. values.push(object[property]);
  82. return values;
  83. },
  84. clone: function(object) {
  85. return Object.extend({}, object);
  86. }
  87. });
  88. Function.prototype.bind = function() {
  89. var __method = this, args = $A(arguments), object = args.shift();
  90. return function() {
  91. return __method.apply(object, args.concat($A(arguments)));
  92. }
  93. }
  94. Function.prototype.bindAsEventListener = function(object) {
  95. var __method = this, args = $A(arguments), object = args.shift();
  96. return function(event) {
  97. return __method.apply(object, [event || window.event].concat(args));
  98. }
  99. }
  100. Object.extend(Number.prototype, {
  101. toColorPart: function() {
  102. return this.toPaddedString(2, 16);
  103. },
  104. succ: function() {
  105. return this + 1;
  106. },
  107. times: function(iterator) {
  108. $R(0, this, true).each(iterator);
  109. return this;
  110. },
  111. toPaddedString: function(length, radix) {
  112. var string = this.toString(radix || 10);
  113. return '0'.times(length - string.length) + string;
  114. },
  115. toJSON: function() {
  116. return isFinite(this) ? this.toString() : 'null';
  117. }
  118. });
  119. Date.prototype.toJSON = function() {
  120. return '"' + this.getFullYear() + '-' +
  121. (this.getMonth() + 1).toPaddedString(2) + '-' +
  122. this.getDate().toPaddedString(2) + 'T' +
  123. this.getHours().toPaddedString(2) + ':' +
  124. this.getMinutes().toPaddedString(2) + ':' +
  125. this.getSeconds().toPaddedString(2) + '"';
  126. };
  127. var Try = {
  128. these: function() {
  129. var returnValue;
  130. for (var i = 0, length = arguments.length; i < length; i++) {
  131. var lambda = arguments[i];
  132. try {
  133. returnValue = lambda();
  134. break;
  135. } catch (e) {}
  136. }
  137. return returnValue;
  138. }
  139. }
  140. /*--------------------------------------------------------------------------*/
  141. var PeriodicalExecuter = Class.create();
  142. PeriodicalExecuter.prototype = {
  143. initialize: function(callback, frequency) {
  144. this.callback = callback;
  145. this.frequency = frequency;
  146. this.currentlyExecuting = false;
  147. this.registerCallback();
  148. },
  149. registerCallback: function() {
  150. this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  151. },
  152. stop: function() {
  153. if (!this.timer) return;
  154. clearInterval(this.timer);
  155. this.timer = null;
  156. },
  157. onTimerEvent: function() {
  158. if (!this.currentlyExecuting) {
  159. try {
  160. this.currentlyExecuting = true;
  161. this.callback(this);
  162. } finally {
  163. this.currentlyExecuting = false;
  164. }
  165. }
  166. }
  167. }
  168. Object.extend(String, {
  169. interpret: function(value) {
  170. return value == null ? '' : String(value);
  171. },
  172. specialChar: {
  173. '\b': '\\b',
  174. '\t': '\\t',
  175. '\n': '\\n',
  176. '\f': '\\f',
  177. '\r': '\\r',
  178. '\\': '\\\\'
  179. }
  180. });
  181. Object.extend(String.prototype, {
  182. gsub: function(pattern, replacement) {
  183. var result = '', source = this, match;
  184. replacement = arguments.callee.prepareReplacement(replacement);
  185. while (source.length > 0) {
  186. if (match = source.match(pattern)) {
  187. result += source.slice(0, match.index);
  188. result += String.interpret(replacement(match));
  189. source = source.slice(match.index + match[0].length);
  190. } else {
  191. result += source, source = '';
  192. }
  193. }
  194. return result;
  195. },
  196. sub: function(pattern, replacement, count) {
  197. replacement = this.gsub.prepareReplacement(replacement);
  198. count = count === undefined ? 1 : count;
  199. return this.gsub(pattern, function(match) {
  200. if (--count < 0) return match[0];
  201. return replacement(match);
  202. });
  203. },
  204. scan: function(pattern, iterator) {
  205. this.gsub(pattern, iterator);
  206. return this;
  207. },
  208. truncate: function(length, truncation) {
  209. length = length || 30;
  210. truncation = truncation === undefined ? '...' : truncation;
  211. return this.length > length ?
  212. this.slice(0, length - truncation.length) + truncation : this;
  213. },
  214. strip: function() {
  215. return this.replace(/^\s+/, '').replace(/\s+$/, '');
  216. },
  217. stripTags: function() {
  218. return this.replace(/<\/?[^>]+>/gi, '');
  219. },
  220. stripScripts: function() {
  221. return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  222. },
  223. extractScripts: function() {
  224. var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
  225. var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
  226. return (this.match(matchAll) || []).map(function(scriptTag) {
  227. return (scriptTag.match(matchOne) || ['', ''])[1];
  228. });
  229. },
  230. evalScripts: function() {
  231. return this.extractScripts().map(function(script) { return eval(script) });
  232. },
  233. escapeHTML: function() {
  234. var self = arguments.callee;
  235. self.text.data = this;
  236. return self.div.innerHTML;
  237. },
  238. unescapeHTML: function() {
  239. var div = document.createElement('div');
  240. div.innerHTML = this.stripTags();
  241. return div.childNodes[0] ? (div.childNodes.length > 1 ?
  242. $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
  243. div.childNodes[0].nodeValue) : '';
  244. },
  245. toQueryParams: function(separator) {
  246. var match = this.strip().match(/([^?#]*)(#.*)?$/);
  247. if (!match) return {};
  248. return match[1].split(separator || '&').inject({}, function(hash, pair) {
  249. if ((pair = pair.split('='))[0]) {
  250. var key = decodeURIComponent(pair.shift());
  251. var value = pair.length > 1 ? pair.join('=') : pair[0];
  252. if (value != undefined) value = decodeURIComponent(value);
  253. if (key in hash) {
  254. if (hash[key].constructor != Array) hash[key] = [hash[key]];
  255. hash[key].push(value);
  256. }
  257. else hash[key] = value;
  258. }
  259. return hash;
  260. });
  261. },
  262. toArray: function() {
  263. return this.split('');
  264. },
  265. succ: function() {
  266. return this.slice(0, this.length - 1) +
  267. String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  268. },
  269. times: function(count) {
  270. var result = '';
  271. for (var i = 0; i < count; i++) result += this;
  272. return result;
  273. },
  274. camelize: function() {
  275. var parts = this.split('-'), len = parts.length;
  276. if (len == 1) return parts[0];
  277. var camelized = this.charAt(0) == '-'
  278. ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
  279. : parts[0];
  280. for (var i = 1; i < len; i++)
  281. camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
  282. return camelized;
  283. },
  284. capitalize: function() {
  285. return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  286. },
  287. underscore: function() {
  288. return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  289. },
  290. dasherize: function() {
  291. return this.gsub(/_/,'-');
  292. },
  293. inspect: function(useDoubleQuotes) {
  294. var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
  295. var character = String.specialChar[match[0]];
  296. return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
  297. });
  298. if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
  299. return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  300. },
  301. toJSON: function() {
  302. return this.inspect(true);
  303. },
  304. unfilterJSON: function(filter) {
  305. return this.sub(filter || Prototype.JSONFilter, '#{1}');
  306. },
  307. isJSON: function() {
  308. var str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
  309. return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  310. },
  311. evalJSON: function(sanitize) {
  312. var json = this.unfilterJSON();
  313. try {
  314. if (!sanitize || json.isJSON()) return eval('(' + json + ')');
  315. } catch (e) { }
  316. throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  317. },
  318. include: function(pattern) {
  319. return this.indexOf(pattern) > -1;
  320. },
  321. startsWith: function(pattern) {
  322. return this.indexOf(pattern) === 0;
  323. },
  324. endsWith: function(pattern) {
  325. var d = this.length - pattern.length;
  326. return d >= 0 && this.lastIndexOf(pattern) === d;
  327. },
  328. empty: function() {
  329. return this == '';
  330. },
  331. blank: function() {
  332. return /^\s*$/.test(this);
  333. }
  334. });
  335. if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
  336. escapeHTML: function() {
  337. return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  338. },
  339. unescapeHTML: function() {
  340. return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
  341. }
  342. });
  343. String.prototype.gsub.prepareReplacement = function(replacement) {
  344. if (typeof replacement == 'function') return replacement;
  345. var template = new Template(replacement);
  346. return function(match) { return template.evaluate(match) };
  347. }
  348. String.prototype.parseQuery = String.prototype.toQueryParams;
  349. Object.extend(String.prototype.escapeHTML, {
  350. div: document.createElement('div'),
  351. text: document.createTextNode('')
  352. });
  353. with (String.prototype.escapeHTML) div.appendChild(text);
  354. var Template = Class.create();
  355. Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
  356. Template.prototype = {
  357. initialize: function(template, pattern) {
  358. this.template = template.toString();
  359. this.pattern = pattern || Template.Pattern;
  360. },
  361. evaluate: function(object) {
  362. return this.template.gsub(this.pattern, function(match) {
  363. var before = match[1];
  364. if (before == '\\') return match[2];
  365. return before + String.interpret(object[match[3]]);
  366. });
  367. }
  368. }
  369. var $break = {}, $continue = new Error('"throw $continue" is deprecated, use "return" instead');
  370. var Enumerable = {
  371. each: function(iterator) {
  372. var index = 0;
  373. try {
  374. this._each(function(value) {
  375. iterator(value, index++);
  376. });
  377. } catch (e) {
  378. if (e != $break) throw e;
  379. }
  380. return this;
  381. },
  382. eachSlice: function(number, iterator) {
  383. var index = -number, slices = [], array = this.toArray();
  384. while ((index += number) < array.length)
  385. slices.push(array.slice(index, index+number));
  386. return slices.map(iterator);
  387. },
  388. all: function(iterator) {
  389. var result = true;
  390. this.each(function(value, index) {
  391. result = result && !!(iterator || Prototype.K)(value, index);
  392. if (!result) throw $break;
  393. });
  394. return result;
  395. },
  396. any: function(iterator) {
  397. var result = false;
  398. this.each(function(value, index) {
  399. if (result = !!(iterator || Prototype.K)(value, index))
  400. throw $break;
  401. });
  402. return result;
  403. },
  404. collect: function(iterator) {
  405. var results = [];
  406. this.each(function(value, index) {
  407. results.push((iterator || Prototype.K)(value, index));
  408. });
  409. return results;
  410. },
  411. detect: function(iterator) {
  412. var result;
  413. this.each(function(value, index) {
  414. if (iterator(value, index)) {
  415. result = value;
  416. throw $break;
  417. }
  418. });
  419. return result;
  420. },
  421. findAll: function(iterator) {
  422. var results = [];
  423. this.each(function(value, index) {
  424. if (iterator(value, index))
  425. results.push(value);
  426. });
  427. return results;
  428. },
  429. grep: function(pattern, iterator) {
  430. var results = [];
  431. this.each(function(value, index) {
  432. var stringValue = value.toString();
  433. if (stringValue.match(pattern))
  434. results.push((iterator || Prototype.K)(value, index));
  435. })
  436. return results;
  437. },
  438. include: function(object) {
  439. var found = false;
  440. this.each(function(value) {
  441. if (value == object) {
  442. found = true;
  443. throw $break;
  444. }
  445. });
  446. return found;
  447. },
  448. inGroupsOf: function(number, fillWith) {
  449. fillWith = fillWith === undefined ? null : fillWith;
  450. return this.eachSlice(number, function(slice) {
  451. while(slice.length < number) slice.push(fillWith);
  452. return slice;
  453. });
  454. },
  455. inject: function(memo, iterator) {
  456. this.each(function(value, index) {
  457. memo = iterator(memo, value, index);
  458. });
  459. return memo;
  460. },
  461. invoke: function(method) {
  462. var args = $A(arguments).slice(1);
  463. return this.map(function(value) {
  464. return value[method].apply(value, args);
  465. });
  466. },
  467. max: function(iterator) {
  468. var result;
  469. this.each(function(value, index) {
  470. value = (iterator || Prototype.K)(value, index);
  471. if (result == undefined || value >= result)
  472. result = value;
  473. });
  474. return result;
  475. },
  476. min: function(iterator) {
  477. var result;
  478. this.each(function(value, index) {
  479. value = (iterator || Prototype.K)(value, index);
  480. if (result == undefined || value < result)
  481. result = value;
  482. });
  483. return result;
  484. },
  485. partition: function(iterator) {
  486. var trues = [], falses = [];
  487. this.each(function(value, index) {
  488. ((iterator || Prototype.K)(value, index) ?
  489. trues : falses).push(value);
  490. });
  491. return [trues, falses];
  492. },
  493. pluck: function(property) {
  494. var results = [];
  495. this.each(function(value, index) {
  496. results.push(value[property]);
  497. });
  498. return results;
  499. },
  500. reject: function(iterator) {
  501. var results = [];
  502. this.each(function(value, index) {
  503. if (!iterator(value, index))
  504. results.push(value);
  505. });
  506. return results;
  507. },
  508. sortBy: function(iterator) {
  509. return this.map(function(value, index) {
  510. return {value: value, criteria: iterator(value, index)};
  511. }).sort(function(left, right) {
  512. var a = left.criteria, b = right.criteria;
  513. return a < b ? -1 : a > b ? 1 : 0;
  514. }).pluck('value');
  515. },
  516. toArray: function() {
  517. return this.map();
  518. },
  519. zip: function() {
  520. var iterator = Prototype.K, args = $A(arguments);
  521. if (typeof args.last() == 'function')
  522. iterator = args.pop();
  523. var collections = [this].concat(args).map($A);
  524. return this.map(function(value, index) {
  525. return iterator(collections.pluck(index));
  526. });
  527. },
  528. size: function() {
  529. return this.toArray().length;
  530. },
  531. inspect: function() {
  532. return '#<Enumerable:' + this.toArray().inspect() + '>';
  533. }
  534. }
  535. Object.extend(Enumerable, {
  536. map: Enumerable.collect,
  537. find: Enumerable.detect,
  538. select: Enumerable.findAll,
  539. member: Enumerable.include,
  540. entries: Enumerable.toArray
  541. });
  542. var $A = Array.from = function(iterable) {
  543. if (!iterable) return [];
  544. if (iterable.toArray) {
  545. return iterable.toArray();
  546. } else {
  547. var results = [];
  548. for (var i = 0, length = iterable.length; i < length; i++)
  549. results.push(iterable[i]);
  550. return results;
  551. }
  552. }
  553. if (Prototype.Browser.WebKit) {
  554. $A = Array.from = function(iterable) {
  555. if (!iterable) return [];
  556. if (!(typeof iterable == 'function' && iterable == '[object NodeList]') &&
  557. iterable.toArray) {
  558. return iterable.toArray();
  559. } else {
  560. var results = [];
  561. for (var i = 0, length = iterable.length; i < length; i++)
  562. results.push(iterable[i]);
  563. return results;
  564. }
  565. }
  566. }
  567. Object.extend(Array.prototype, Enumerable);
  568. if (!Array.prototype._reverse)
  569. Array.prototype._reverse = Array.prototype.reverse;
  570. Object.extend(Array.prototype, {
  571. _each: function(iterator) {
  572. for (var i = 0, length = this.length; i < length; i++)
  573. iterator(this[i]);
  574. },
  575. clear: function() {
  576. this.length = 0;
  577. return this;
  578. },
  579. first: function() {
  580. return this[0];
  581. },
  582. last: function() {
  583. return this[this.length - 1];
  584. },
  585. compact: function() {
  586. return this.select(function(value) {
  587. return value != null;
  588. });
  589. },
  590. flatten: function() {
  591. return this.inject([], function(array, value) {
  592. return array.concat(value && value.constructor == Array ?
  593. value.flatten() : [value]);
  594. });
  595. },
  596. without: function() {
  597. var values = $A(arguments);
  598. return this.select(function(value) {
  599. return !values.include(value);
  600. });
  601. },
  602. indexOf: function(object) {
  603. for (var i = 0, length = this.length; i < length; i++)
  604. if (this[i] == object) return i;
  605. return -1;
  606. },
  607. reverse: function(inline) {
  608. return (inline !== false ? this : this.toArray())._reverse();
  609. },
  610. reduce: function() {
  611. return this.length > 1 ? this : this[0];
  612. },
  613. uniq: function(sorted) {
  614. return this.inject([], function(array, value, index) {
  615. if (0 == index || (sorted ? array.last() != value : !array.include(value)))
  616. array.push(value);
  617. return array;
  618. });
  619. },
  620. clone: function() {
  621. return [].concat(this);
  622. },
  623. size: function() {
  624. return this.length;
  625. },
  626. inspect: function() {
  627. return '[' + this.map(Object.inspect).join(', ') + ']';
  628. },
  629. toJSON: function() {
  630. var results = [];
  631. this.each(function(object) {
  632. var value = Object.toJSON(object);
  633. if (value !== undefined) results.push(value);
  634. });
  635. return '[' + results.join(', ') + ']';
  636. }
  637. });
  638. Array.prototype.toArray = Array.prototype.clone;
  639. function $w(string) {
  640. string = string.strip();
  641. return string ? string.split(/\s+/) : [];
  642. }
  643. if (Prototype.Browser.Opera){
  644. Array.prototype.concat = function() {
  645. var array = [];
  646. for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
  647. for (var i = 0, length = arguments.length; i < length; i++) {
  648. if (arguments[i].constructor == Array) {
  649. for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
  650. array.push(arguments[i][j]);
  651. } else {
  652. array.push(arguments[i]);
  653. }
  654. }
  655. return array;
  656. }
  657. }
  658. var Hash = function(object) {
  659. if (object instanceof Hash) this.merge(object);
  660. else Object.extend(this, object || {});
  661. };
  662. Object.extend(Hash, {
  663. toQueryString: function(obj) {
  664. var parts = [];
  665. parts.add = arguments.callee.addPair;
  666. this.prototype._each.call(obj, function(pair) {
  667. if (!pair.key) return;
  668. var value = pair.value;
  669. if (value && typeof value == 'object') {
  670. if (value.constructor == Array) value.each(function(value) {
  671. parts.add(pair.key, value);
  672. });
  673. return;
  674. }
  675. parts.add(pair.key, value);
  676. });
  677. return parts.join('&');
  678. },
  679. toJSON: function(object) {
  680. var results = [];
  681. this.prototype._each.call(object, function(pair) {
  682. var value = Object.toJSON(pair.value);
  683. if (value !== undefined) results.push(pair.key.toJSON() + ': ' + value);
  684. });
  685. return '{' + results.join(', ') + '}';
  686. }
  687. });
  688. Hash.toQueryString.addPair = function(key, value, prefix) {
  689. key = encodeURIComponent(key);
  690. if (value === undefined) this.push(key);
  691. else this.push(key + '=' + (value == null ? '' : encodeURIComponent(value)));
  692. }
  693. Object.extend(Hash.prototype, Enumerable);
  694. Object.extend(Hash.prototype, {
  695. _each: function(iterator) {
  696. for (var key in this) {
  697. var value = this[key];
  698. if (value && value == Hash.prototype[key]) continue;
  699. var pair = [key, value];
  700. pair.key = key;
  701. pair.value = value;
  702. iterator(pair);
  703. }
  704. },
  705. keys: function() {
  706. return this.pluck('key');
  707. },
  708. values: function() {
  709. return this.pluck('value');
  710. },
  711. merge: function(hash) {
  712. return $H(hash).inject(this, function(mergedHash, pair) {
  713. mergedHash[pair.key] = pair.value;
  714. return mergedHash;
  715. });
  716. },
  717. remove: function() {
  718. var result;
  719. for(var i = 0, length = arguments.length; i < length; i++) {
  720. var value = this[arguments[i]];
  721. if (value !== undefined){
  722. if (result === undefined) result = value;
  723. else {
  724. if (result.constructor != Array) result = [result];
  725. result.push(value)
  726. }
  727. }
  728. delete this[arguments[i]];
  729. }
  730. return result;
  731. },
  732. toQueryString: function() {
  733. return Hash.toQueryString(this);
  734. },
  735. inspect: function() {
  736. return '#<Hash:{' + this.map(function(pair) {
  737. return pair.map(Object.inspect).join(': ');
  738. }).join(', ') + '}>';
  739. },
  740. toJSON: function() {
  741. return Hash.toJSON(this);
  742. }
  743. });
  744. function $H(object) {
  745. if (object instanceof Hash) return object;
  746. return new Hash(object);
  747. };
  748. // Safari iterates over shadowed properties
  749. if (function() {
  750. var i = 0, Test = function(value) { this.key = value };
  751. Test.prototype.key = 'foo';
  752. for (var property in new Test('bar')) i++;
  753. return i > 1;
  754. }()) Hash.prototype._each = function(iterator) {
  755. var cache = [];
  756. for (var key in this) {
  757. var value = this[key];
  758. if ((value && value == Hash.prototype[key]) || cache.include(key)) continue;
  759. cache.push(key);
  760. var pair = [key, value];
  761. pair.key = key;
  762. pair.value = value;
  763. iterator(pair);
  764. }
  765. };
  766. ObjectRange = Class.create();
  767. Object.extend(ObjectRange.prototype, Enumerable);
  768. Object.extend(ObjectRange.prototype, {
  769. initialize: function(start, end, exclusive) {
  770. this.start = start;
  771. this.end = end;
  772. this.exclusive = exclusive;
  773. },
  774. _each: function(iterator) {
  775. var value = this.start;
  776. while (this.include(value)) {
  777. iterator(value);
  778. value = value.succ();
  779. }
  780. },
  781. include: function(value) {
  782. if (value < this.start)
  783. return false;
  784. if (this.exclusive)
  785. return value < this.end;
  786. return value <= this.end;
  787. }
  788. });
  789. var $R = function(start, end, exclusive) {
  790. return new ObjectRange(start, end, exclusive);
  791. }
  792. var Ajax = {
  793. getTransport: function() {
  794. return Try.these(
  795. function() {return new XMLHttpRequest()},
  796. function() {return new ActiveXObject('Msxml2.XMLHTTP')},
  797. function() {return new ActiveXObject('Microsoft.XMLHTTP')}
  798. ) || false;
  799. },
  800. activeRequestCount: 0
  801. }
  802. Ajax.Responders = {
  803. responders: [],
  804. _each: function(iterator) {
  805. this.responders._each(iterator);
  806. },
  807. register: function(responder) {
  808. if (!this.include(responder))
  809. this.responders.push(responder);
  810. },
  811. unregister: function(responder) {
  812. this.responders = this.responders.without(responder);
  813. },
  814. dispatch: function(callback, request, transport, json) {
  815. this.each(function(responder) {
  816. if (typeof responder[callback] == 'function') {
  817. try {
  818. responder[callback].apply(responder, [request, transport, json]);
  819. } catch (e) {}
  820. }
  821. });
  822. }
  823. };
  824. Object.extend(Ajax.Responders, Enumerable);
  825. Ajax.Responders.register({
  826. onCreate: function() {
  827. Ajax.activeRequestCount++;
  828. },
  829. onComplete: function() {
  830. Ajax.activeRequestCount--;
  831. }
  832. });
  833. Ajax.Base = function() {};
  834. Ajax.Base.prototype = {
  835. setOptions: function(options) {
  836. this.options = {
  837. method: 'post',
  838. asynchronous: true,
  839. contentType: 'application/x-www-form-urlencoded',
  840. encoding: 'UTF-8',
  841. parameters: ''
  842. }
  843. Object.extend(this.options, options || {});
  844. this.options.method = this.options.method.toLowerCase();
  845. if (typeof this.options.parameters == 'string')
  846. this.options.parameters = this.options.parameters.toQueryParams();
  847. }
  848. }
  849. Ajax.Request = Class.create();
  850. Ajax.Request.Events =
  851. ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
  852. Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  853. _complete: false,
  854. initialize: function(url, options) {
  855. this.transport = Ajax.getTransport();
  856. this.setOptions(options);
  857. this.request(url);
  858. },
  859. request: function(url) {
  860. this.url = url;
  861. this.method = this.options.method;
  862. var params = Object.clone(this.options.parameters);
  863. if (!['get', 'post'].include(this.method)) {
  864. // simulate other verbs over post
  865. params['_method'] = this.method;
  866. this.method = 'post';
  867. }
  868. this.parameters = params;
  869. if (params = Hash.toQueryString(params)) {
  870. // when GET, append parameters to URL
  871. if (this.method == 'get')
  872. this.url += (this.url.include('?') ? '&' : '?') + params;
  873. else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
  874. params += '&_=';
  875. }
  876. try {
  877. if (this.options.onCreate) this.options.onCreate(this.transport);
  878. Ajax.Responders.dispatch('onCreate', this, this.transport);
  879. this.transport.open(this.method.toUpperCase(), this.url,
  880. this.options.asynchronous);
  881. if (this.options.asynchronous)
  882. setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);
  883. this.transport.onreadystatechange = this.onStateChange.bind(this);
  884. this.setRequestHeaders();
  885. this.body = this.method == 'post' ? (this.options.postBody || params) : null;
  886. this.transport.send(this.body);
  887. /* Force Firefox to handle ready state 4 for synchronous requests */
  888. if (!this.options.asynchronous && this.transport.overrideMimeType)
  889. this.onStateChange();
  890. }
  891. catch (e) {
  892. this.dispatchException(e);
  893. }
  894. },
  895. onStateChange: function() {
  896. var readyState = this.transport.readyState;
  897. if (readyState > 1 && !((readyState == 4) && this._complete))
  898. this.respondToReadyState(this.transport.readyState);
  899. },
  900. setRequestHeaders: function() {
  901. var headers = {
  902. 'X-Requested-With': 'XMLHttpRequest',
  903. 'X-Prototype-Version': Prototype.Version,
  904. 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  905. };
  906. if (this.method == 'post') {
  907. headers['Content-type'] = this.options.contentType +
  908. (this.options.encoding ? '; charset=' + this.options.encoding : '');
  909. /* Force "Connection: close" for older Mozilla browsers to work
  910. * around a bug where XMLHttpRequest sends an incorrect
  911. * Content-length header. See Mozilla Bugzilla #246651.
  912. */
  913. if (this.transport.overrideMimeType &&
  914. (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
  915. headers['Connection'] = 'close';
  916. }
  917. // user-defined headers
  918. if (typeof this.options.requestHeaders == 'object') {
  919. var extras = this.options.requestHeaders;
  920. if (typeof extras.push == 'function')
  921. for (var i = 0, length = extras.length; i < length; i += 2)
  922. headers[extras[i]] = extras[i+1];
  923. else
  924. $H(extras).each(function(pair) { headers[pair.key] = pair.value });
  925. }
  926. for (var name in headers)
  927. this.transport.setRequestHeader(name, headers[name]);
  928. },
  929. success: function() {
  930. return !this.transport.status
  931. || (this.transport.status >= 200 && this.transport.status < 300);
  932. },
  933. respondToReadyState: function(readyState) {
  934. var state = Ajax.Request.Events[readyState];
  935. var transport = this.transport, json = this.evalJSON();
  936. if (state == 'Complete') {
  937. try {
  938. this._complete = true;
  939. (this.options['on' + this.transport.status]
  940. || this.options['on' + (this.success() ? 'Success' : 'Failure')]
  941. || Prototype.emptyFunction)(transport, json);
  942. } catch (e) {
  943. this.dispatchException(e);
  944. }
  945. var contentType = this.getHeader('Content-type');
  946. if (contentType && this.isSameOrigin() && contentType.strip().
  947. match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
  948. this.evalResponse();
  949. }
  950. try {
  951. (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
  952. Ajax.Responders.dispatch('on' + state, this, transport, json);
  953. } catch (e) {
  954. this.dispatchException(e);
  955. }
  956. if (state == 'Complete') {
  957. // avoid memory leak in MSIE: clean up
  958. this.transport.onreadystatechange = Prototype.emptyFunction;
  959. }
  960. },
  961. isSameOrigin: function() {
  962. var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
  963. return !m || (m[0] == new Template('#{protocol}//#{domain}#{port}').evaluate({
  964. protocol: location.protocol,
  965. domain: document.domain,
  966. port: location.port ? ':' + location.port : ''
  967. }));
  968. },
  969. getHeader: function(name) {
  970. try {
  971. return this.transport.getResponseHeader(name);
  972. } catch (e) { return null }
  973. },
  974. evalJSON: function() {
  975. try {
  976. var json = this.getHeader('X-JSON');
  977. return json ? json.evalJSON(!this.isSameOrigin()) : null;
  978. } catch (e) { return null }
  979. },
  980. evalResponse: function() {
  981. try {
  982. return eval((this.transport.responseText || '').unfilterJSON());
  983. } catch (e) {
  984. this.dispatchException(e);
  985. }
  986. },
  987. dispatchException: function(exception) {
  988. (this.options.onException || Prototype.emptyFunction)(this, exception);
  989. Ajax.Responders.dispatch('onException', this, exception);
  990. }
  991. });
  992. Ajax.Updater = Class.create();
  993. Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  994. initialize: function(container, url, options) {
  995. this.container = {
  996. success: (container.success || container),
  997. failure: (container.failure || (container.success ? null : container))
  998. }
  999. this.transport = Ajax.getTransport();
  1000. this.setOptions(options);
  1001. var onComplete = this.options.onComplete || Prototype.emptyFunction;
  1002. this.options.onComplete = (function(transport, param) {
  1003. this.updateContent();
  1004. onComplete(transport, param);
  1005. }).bind(this);
  1006. this.request(url);
  1007. },
  1008. updateContent: function() {
  1009. var receiver = this.container[this.success() ? 'success' : 'failure'];
  1010. var response = this.transport.responseText;
  1011. if (!this.options.evalScripts) response = response.stripScripts();
  1012. if (receiver = $(receiver)) {
  1013. if (this.options.insertion)
  1014. new this.options.insertion(receiver, response);
  1015. else
  1016. receiver.update(response);
  1017. }
  1018. if (this.success()) {
  1019. if (this.onComplete)
  1020. setTimeout(this.onComplete.bind(this), 10);
  1021. }
  1022. }
  1023. });
  1024. Ajax.PeriodicalUpdater = Class.create();
  1025. Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  1026. initialize: function(container, url, options) {
  1027. this.setOptions(options);
  1028. this.onComplete = this.options.onComplete;
  1029. this.frequency = (this.options.frequency || 2);
  1030. this.decay = (this.options.decay || 1);
  1031. this.updater = {};
  1032. this.container = container;
  1033. this.url = url;
  1034. this.start();
  1035. },
  1036. start: function() {
  1037. this.options.onComplete = this.updateComplete.bind(this);
  1038. this.onTimerEvent();
  1039. },
  1040. stop: function() {
  1041. this.updater.options.onComplete = undefined;
  1042. clearTimeout(this.timer);
  1043. (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  1044. },
  1045. updateComplete: function(request) {
  1046. if (this.options.decay) {
  1047. this.decay = (request.responseText == this.lastText ?
  1048. this.decay * this.options.decay : 1);
  1049. this.lastText = request.responseText;
  1050. }
  1051. this.timer = setTimeout(this.onTimerEvent.bind(this),
  1052. this.decay * this.frequency * 1000);
  1053. },
  1054. onTimerEvent: function() {
  1055. this.updater = new Ajax.Updater(this.container, this.url, this.options);
  1056. }
  1057. });
  1058. function $(element) {
  1059. if (arguments.length > 1) {
  1060. for (var i = 0, elements = [], length = arguments.length; i < length; i++)
  1061. elements.push($(arguments[i]));
  1062. return elements;
  1063. }
  1064. if (typeof element == 'string')
  1065. element = document.getElementById(element);
  1066. return Element.extend(element);
  1067. }
  1068. if (Prototype.BrowserFeatures.XPath) {
  1069. document._getElementsByXPath = function(expression, parentElement) {
  1070. var results = [];
  1071. var query = document.evaluate(expression, $(parentElement) || document,
  1072. null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  1073. for (var i = 0, length = query.snapshotLength; i < length; i++)
  1074. results.push(query.snapshotItem(i));
  1075. return results;
  1076. };
  1077. document.getElementsByClassName = function(className, parentElement) {
  1078. var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
  1079. return document._getElementsByXPath(q, parentElement);
  1080. }
  1081. } else document.getElementsByClassName = function(className, parentElement) {
  1082. var children = ($(parentElement) || document.body).getElementsByTagName('*');
  1083. var elements = [], child, pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
  1084. for (var i = 0, length = children.length; i < length; i++) {
  1085. child = children[i];
  1086. var elementClassName = child.className;
  1087. if (elementClassName.length == 0) continue;
  1088. if (elementClassName == className || elementClassName.match(pattern))
  1089. elements.push(Element.extend(child));
  1090. }
  1091. return elements;
  1092. };
  1093. /*--------------------------------------------------------------------------*/
  1094. if (!window.Element) var Element = {};
  1095. Element.extend = function(element) {
  1096. var F = Prototype.BrowserFeatures;
  1097. if (!element || !element.tagName || element.nodeType == 3 ||
  1098. element._extended || F.SpecificElementExtensions || element == window)
  1099. return element;
  1100. var methods = {}, tagName = element.tagName, cache = Element.extend.cache,
  1101. T = Element.Methods.ByTag;
  1102. // extend methods for all tags (Safari doesn't need this)
  1103. if (!F.ElementExtensions) {
  1104. Object.extend(methods, Element.Methods),
  1105. Object.extend(methods, Element.Methods.Simulated);
  1106. }
  1107. // extend methods for specific tags
  1108. if (T[tagName]) Object.extend(methods, T[tagName]);
  1109. for (var property in methods) {
  1110. var value = methods[property];
  1111. if (typeof value == 'function' && !(property in element))
  1112. element[property] = cache.findOrStore(value);
  1113. }
  1114. element._extended = Prototype.emptyFunction;
  1115. return element;
  1116. };
  1117. Element.extend.cache = {
  1118. findOrStore: function(value) {
  1119. return this[value] = this[value] || function() {
  1120. return value.apply(null, [this].concat($A(arguments)));
  1121. }
  1122. }
  1123. };
  1124. Element.Methods = {
  1125. visible: function(element) {
  1126. return $(element).style.display != 'none';
  1127. },
  1128. toggle: function(element) {
  1129. element = $(element);
  1130. Element[Element.visible(element) ? 'hide' : 'show'](element);
  1131. return element;
  1132. },
  1133. hide: function(element) {
  1134. $(element).style.display = 'none';
  1135. return element;
  1136. },
  1137. show: function(element) {
  1138. $(element).style.display = '';
  1139. return element;
  1140. },
  1141. remove: function(element) {
  1142. element = $(element);
  1143. element.parentNode.removeChild(element);
  1144. return element;
  1145. },
  1146. update: function(element, html) {
  1147. html = typeof html == 'undefined' ? '' : html.toString();
  1148. $(element).innerHTML = html.stripScripts();
  1149. setTimeout(function() {html.evalScripts()}, 10);
  1150. return element;
  1151. },
  1152. replace: function(element, html) {
  1153. element = $(element);
  1154. html = typeof html == 'undefined' ? '' : html.toString();
  1155. if (element.outerHTML) {
  1156. element.outerHTML = html.stripScripts();
  1157. } else {
  1158. var range = element.ownerDocument.createRange();
  1159. range.selectNodeContents(element);
  1160. element.parentNode.replaceChild(
  1161. range.createContextualFragment(html.stripScripts()), element);
  1162. }
  1163. setTimeout(function() {html.evalScripts()}, 10);
  1164. return element;
  1165. },
  1166. inspect: function(element) {
  1167. element = $(element);
  1168. var result = '<' + element.tagName.toLowerCase();
  1169. $H({'id': 'id', 'className': 'class'}).each(function(pair) {
  1170. var property = pair.first(), attribute = pair.last();
  1171. var value = (element[property] || '').toString();
  1172. if (value) result += ' ' + attribute + '=' + value.inspect(true);
  1173. });
  1174. return result + '>';
  1175. },
  1176. recursivelyCollect: function(element, property) {
  1177. element = $(element);
  1178. var elements = [];
  1179. while (element = element[property])
  1180. if (element.nodeType == 1)
  1181. elements.push(Element.extend(element));
  1182. return elements;
  1183. },
  1184. ancestors: function(element) {
  1185. return $(element).recursivelyCollect('parentNode');
  1186. },
  1187. descendants: function(element) {
  1188. return $A($(element).getElementsByTagName('*')).each(Element.extend);
  1189. },
  1190. firstDescendant: function(element) {
  1191. element = $(element).firstChild;
  1192. while (element && element.nodeType != 1) element = element.nextSibling;
  1193. return $(element);
  1194. },
  1195. immediateDescendants: function(element) {
  1196. if (!(element = $(element).firstChild)) return [];
  1197. while (element && element.nodeType != 1) element = element.nextSibling;
  1198. if (element) return [element].concat($(element).nextSiblings());
  1199. return [];
  1200. },
  1201. previousSiblings: function(element) {
  1202. return $(element).recursivelyCollect('previousSibling');
  1203. },
  1204. nextSiblings: function(element) {
  1205. return $(element).recursivelyCollect('nextSibling');
  1206. },
  1207. siblings: function(element) {
  1208. element = $(element);
  1209. return element.previousSiblings().reverse().concat(element.nextSiblings());
  1210. },
  1211. match: function(element, selector) {
  1212. if (typeof selector == 'string')
  1213. selector = new Selector(selector);
  1214. return selector.match($(element));
  1215. },
  1216. up: function(element, expression, index) {
  1217. element = $(element);
  1218. if (arguments.length == 1) return $(element.parentNode);
  1219. var ancestors = element.ancestors();
  1220. return expression ? Selector.findElement(ancestors, expression, index) :
  1221. ancestors[index || 0];
  1222. },
  1223. down: function(element, expression, index) {
  1224. element = $(element);
  1225. if (arguments.length == 1) return element.firstDescendant();
  1226. var descendants = element.descendants();
  1227. return expression ? Selector.findElement(descendants, expression, index) :
  1228. descendants[index || 0];
  1229. },
  1230. previous: function(element, expression, index) {
  1231. element = $(element);
  1232. if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
  1233. var previousSiblings = element.previousSiblings();
  1234. return expression ? Selector.findElement(previousSiblings, expression, index) :
  1235. previousSiblings[index || 0];
  1236. },
  1237. next: function(element, expression, index) {
  1238. element = $(element);
  1239. if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
  1240. var nextSiblings = element.nextSiblings();
  1241. return expression ? Selector.findElement(nextSiblings, expression, index) :
  1242. nextSiblings[index || 0];
  1243. },
  1244. getElementsBySelector: function() {
  1245. var args = $A(arguments), element = $(args.shift());
  1246. return Selector.findChildElements(element, args);
  1247. },
  1248. getElementsByClassName: function(element, className) {
  1249. return document.getElementsByClassName(className, element);
  1250. },
  1251. readAttribute: function(element, name) {
  1252. element = $(element);
  1253. if (Prototype.Browser.IE) {
  1254. if (!element.attributes) return null;
  1255. var t = Element._attributeTranslations;
  1256. if (t.values[name]) return t.values[name](element, name);
  1257. if (t.names[name]) name = t.names[name];
  1258. var attribute = element.attributes[name];
  1259. return attribute ? attribute.nodeValue : null;
  1260. }
  1261. return element.getAttribute(name);
  1262. },
  1263. getHeight: function(element) {
  1264. return $(element).getDimensions().height;
  1265. },
  1266. getWidth: function(element) {
  1267. return $(element).getDimensions().width;
  1268. },
  1269. classNames: function(element) {
  1270. return new Element.ClassNames(element);
  1271. },
  1272. hasClassName: function(element, className) {
  1273. if (!(element = $(element))) return;
  1274. var elementClassName = element.className;
  1275. if (elementClassName.length == 0) return false;
  1276. if (elementClassName == className ||
  1277. elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
  1278. return true;
  1279. return false;
  1280. },
  1281. addClassName: function(element, className) {
  1282. if (!(element = $(element))) return;
  1283. Element.classNames(element).add(className);
  1284. return element;
  1285. },
  1286. removeClassName: function(element, className) {
  1287. if (!(element = $(element))) return;
  1288. Element.classNames(element).remove(className);
  1289. return element;
  1290. },
  1291. toggleClassName: function(element, className) {
  1292. if (!(element = $(element))) return;
  1293. Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
  1294. return element;
  1295. },
  1296. observe: function() {
  1297. Event.observe.apply(Event, arguments);
  1298. return $A(arguments).first();
  1299. },
  1300. stopObserving: function() {
  1301. Event.stopObserving.apply(Event, arguments);
  1302. return $A(arguments).first();
  1303. },
  1304. // removes whitespace-only text node children
  1305. cleanWhitespace: function(element) {
  1306. element = $(element);
  1307. var node = element.firstChild;
  1308. while (node) {
  1309. var nextNode = node.nextSibling;
  1310. if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
  1311. element.removeChild(node);
  1312. node = nextNode;
  1313. }
  1314. return element;
  1315. },
  1316. empty: function(element) {
  1317. return $(element).innerHTML.blank();
  1318. },
  1319. descendantOf: function(element, ancestor) {
  1320. element = $(element), ancestor = $(ancestor);
  1321. while (element = element.parentNode)
  1322. if (element == ancestor) return true;
  1323. return false;
  1324. },
  1325. scrollTo: function(element) {
  1326. element = $(element);
  1327. var pos = Position.cumulativeOffset(element);
  1328. window.scrollTo(pos[0], pos[1]);
  1329. return element;
  1330. },
  1331. getStyle: function(element, style) {
  1332. element = $(element);
  1333. style = style == 'float' ? 'cssFloat' : style.camelize();
  1334. var value = element.style[style];
  1335. if (!value) {
  1336. var css = document.defaultView.getComputedStyle(element, null);
  1337. value = css ? css[style] : null;
  1338. }
  1339. if (style == 'opacity') return value ? parseFloat(value) : 1.0;
  1340. return value == 'auto' ? null : value;
  1341. },
  1342. getOpacity: function(element) {
  1343. return $(element).getStyle('opacity');
  1344. },
  1345. setStyle: function(element, styles, camelized) {
  1346. element = $(element);
  1347. var elementStyle = element.style;
  1348. for (var property in styles)
  1349. if (property == 'opacity') element.setOpacity(styles[property])
  1350. else
  1351. elementStyle[(property == 'float' || property == 'cssFloat') ?
  1352. (elementStyle.styleFloat === undefined ? 'cssFloat' : 'styleFloat') :
  1353. (camelized ? property : property.camelize())] = styles[property];
  1354. return element;
  1355. },
  1356. setOpacity: function(element, value) {
  1357. element = $(element);
  1358. element.style.opacity = (value == 1 || value === '') ? '' :
  1359. (value < 0.00001) ? 0 : value;
  1360. return element;
  1361. },
  1362. getDimensions: function(element) {
  1363. element = $(element);
  1364. var display = $(element).getStyle('display');
  1365. if (display != 'none' && display != null) // Safari bug
  1366. return {width: element.offsetWidth, height: element.offsetHeight};
  1367. // All *Width and *Height properties give 0 on elements with display none,
  1368. // so enable the element temporarily
  1369. var els = element.style;
  1370. var originalVisibility = els.visibility;
  1371. var originalPosition = els.position;
  1372. var originalDisplay = els.display;
  1373. els.visibility = 'hidden';
  1374. els.position = 'absolute';
  1375. els.display = 'block';
  1376. var originalWidth = element.clientWidth;
  1377. var originalHeight = element.clientHeight;
  1378. els.display = originalDisplay;
  1379. els.position = originalPosition;
  1380. els.visibility = originalVisibility;
  1381. return {width: originalWidth, height: originalHeight};
  1382. },
  1383. makePositioned: function(element) {
  1384. element = $(element);
  1385. var pos = Element.getStyle(element, 'position');
  1386. if (pos == 'static' || !pos) {
  1387. element._madePositioned = true;
  1388. element.style.position = 'relative';
  1389. // Opera returns the offset relative to the positioning context, when an
  1390. // element is position relative but top and left have not been defined
  1391. if (window.opera) {
  1392. element.style.top = 0;
  1393. element.style.left = 0;
  1394. }
  1395. }
  1396. return element;
  1397. },
  1398. undoPositioned: function(element) {
  1399. element = $(element);
  1400. if (element._madePositioned) {
  1401. element._madePositioned = undefined;
  1402. element.style.position =
  1403. element.style.top =
  1404. element.style.left =
  1405. element.style.bottom =
  1406. element.style.right = '';
  1407. }
  1408. return element;
  1409. },
  1410. makeClipping: function(element) {
  1411. element = $(element);
  1412. if (element._overflow) return element;
  1413. element._overflow = element.style.overflow || 'auto';
  1414. if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
  1415. element.style.overflow = 'hidden';
  1416. return element;
  1417. },
  1418. undoClipping: function(element) {
  1419. element = $(element);
  1420. if (!element._overflow) return element;
  1421. element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
  1422. element._overflow = null;
  1423. return element;
  1424. }
  1425. };
  1426. Object.extend(Element.Methods, {
  1427. childOf: Element.Methods.descendantOf,
  1428. childElements: Element.Methods.immediateDescendants
  1429. });
  1430. if (Prototype.Browser.Opera) {
  1431. Element.Methods._getStyle = Element.Methods.getStyle;
  1432. Element.Methods.getStyle = function(element, style) {
  1433. switch(style) {
  1434. case 'left':
  1435. case 'top':
  1436. case 'right':
  1437. case 'bottom':
  1438. if (Element._getStyle(element, 'position') == 'static') return null;
  1439. default: return Element._getStyle(element, style);
  1440. }
  1441. };
  1442. }
  1443. else if (Prototype.Browser.IE) {
  1444. Element.Methods.getStyle = function(element, style) {
  1445. element = $(element);
  1446. style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
  1447. var value = element.style[style];
  1448. if (!value && element.currentStyle) value = element.currentStyle[style];
  1449. if (style == 'opacity') {
  1450. if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
  1451. if (value[1]) return parseFloat(value[1]) / 100;
  1452. return 1.0;
  1453. }
  1454. if (value == 'auto') {
  1455. if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
  1456. return element['offset'+style.capitalize()] + 'px';
  1457. return null;
  1458. }
  1459. return value;
  1460. };
  1461. Element.Methods.setOpacity = function(element, value) {
  1462. element = $(element);
  1463. var filter = element.getStyle('filter'), style = element.style;
  1464. if (value == 1 || value === '') {
  1465. style.filter = filter.replace(/alpha\([^\)]*\)/gi,'');
  1466. return element;
  1467. } else if (value < 0.00001) value = 0;
  1468. style.filter = filter.replace(/alpha\([^\)]*\)/gi, '') +
  1469. 'alpha(opacity=' + (value * 100) + ')';
  1470. return element;
  1471. };
  1472. // IE is missing .innerHTML support for TABLE-related elements
  1473. Element.Methods.update = function(element, html) {
  1474. element = $(element);
  1475. html = typeof html == 'undefined' ? '' : html.toString();
  1476. var tagName = element.tagName.toUpperCase();
  1477. if (['THEAD','TBODY','TR','TD'].include(tagName)) {
  1478. var div = document.createElement('div');
  1479. switch (tagName) {
  1480. case 'THEAD':
  1481. case 'TBODY':
  1482. div.innerHTML = '<table><tbody>' + html.stripScripts() + '</tbody></table>';
  1483. depth = 2;
  1484. break;
  1485. case 'TR':
  1486. div.innerHTML = '<table><tbody><tr>' + html.stripScripts() + '</tr></tbody></table>';
  1487. depth = 3;
  1488. break;
  1489. case 'TD':
  1490. div.innerHTML = '<table><tbody><tr><td>' + html.stripScripts() + '</td></tr></tbody></table>';
  1491. depth = 4;
  1492. }
  1493. $A(element.childNodes).each(function(node) { element.removeChild(node) });
  1494. depth.times(function() { div = div.firstChild });
  1495. $A(div.childNodes).each(function(node) { element.appendChild(node) });
  1496. } else {
  1497. element.innerHTML = html.stripScripts();
  1498. }
  1499. setTimeout(function() { html.evalScripts() }, 10);
  1500. return element;
  1501. }
  1502. }
  1503. else if (Prototype.Browser.Gecko) {
  1504. Element.Methods.setOpacity = function(element, value) {
  1505. element = $(element);
  1506. element.style.opacity = (value == 1) ? 0.999999 :
  1507. (value === '') ? '' : (value < 0.00001) ? 0 : value;
  1508. return element;
  1509. };
  1510. }
  1511. Element._attributeTranslations = {
  1512. names: {
  1513. colspan: "colSpan",
  1514. rowspan: "rowSpan",
  1515. valign: "vAlign",
  1516. datetime: "dateTime",
  1517. accesskey: "accessKey",
  1518. tabindex: "tabIndex",
  1519. enctype: "encType",
  1520. maxlength: "maxLength",
  1521. readonly: "readOnly",
  1522. longdesc: "longDesc"
  1523. },
  1524. values: {
  1525. _getAttr: function(element, attribute) {
  1526. return element.getAttribute(attribute, 2);
  1527. },
  1528. _flag: function(element, attribute) {
  1529. return $(element).hasAttribute(attribute) ? attribute : null;
  1530. },
  1531. style: function(element) {
  1532. return element.style.cssText.toLowerCase();
  1533. },
  1534. title: function(element) {
  1535. var node = element.getAttributeNode('title');
  1536. return node.specified ? node.nodeValue : null;
  1537. }
  1538. }
  1539. };
  1540. (function() {
  1541. Object.extend(this, {
  1542. href: this._getAttr,
  1543. src: this._getAttr,
  1544. type: this._getAttr,
  1545. disabled: this._flag,
  1546. checked: this._flag,
  1547. readonly: this._flag,
  1548. multiple: this._flag
  1549. });
  1550. }).call(Element._attributeTranslations.values);
  1551. Element.Methods.Simulated = {
  1552. hasAttribute: function(element, attribute) {
  1553. var t = Element._attributeTranslations, node;
  1554. attribute = t.names[attribute] || attribute;
  1555. node = $(element).getAttributeNode(attribute);
  1556. return node && node.specified;
  1557. }
  1558. };
  1559. Element.Methods.ByTag = {};
  1560. Object.extend(Element, Element.Methods);
  1561. if (!Prototype.BrowserFeatures.ElementExtensions &&
  1562. document.createElement('div').__proto__) {
  1563. window.HTMLElement = {};
  1564. window.HTMLElement.prototype = document.createElement('div').__proto__;
  1565. Prototype.BrowserFeatures.ElementExtensions = true;
  1566. }
  1567. Element.hasAttribute = function(element, attribute) {
  1568. if (element.hasAttribute) return element.hasAttribute(attribute);
  1569. return Element.Methods.Simulated.hasAttribute(element, attribute);
  1570. };
  1571. Element.addMethods = function(methods) {
  1572. var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
  1573. if (!methods) {
  1574. Object.extend(Form, Form.Methods);
  1575. Object.extend(Form.Element, Form.Element.Methods);
  1576. Object.extend(Element.Methods.ByTag, {
  1577. "FORM": Object.clone(Form.Methods),
  1578. "INPUT": Object.clone(Form.Element.Methods),
  1579. "SELECT": Object.clone(Form.Element.Methods),
  1580. "TEXTAREA": Object.clone(Form.Element.Methods)
  1581. });
  1582. }
  1583. if (arguments.length == 2) {
  1584. var tagName = methods;
  1585. methods = arguments[1];
  1586. }
  1587. if (!tagName) Object.extend(Element.Methods, methods || {});
  1588. else {
  1589. if (tagName.constructor == Array) tagName.each(extend);
  1590. else extend(tagName);
  1591. }
  1592. function extend(tagName) {
  1593. tagName = tagName.toUpperCase();
  1594. if (!Element.Methods.ByTag[tagName])
  1595. Element.Methods.ByTag[tagName] = {};
  1596. Object.extend(Element.Methods.ByTag[tagName], methods);
  1597. }
  1598. function copy(methods, destination, onlyIfAbsent) {
  1599. onlyIfAbsent = onlyIfAbsent || false;
  1600. var cache = Element.extend.cache;
  1601. for (var property in methods) {
  1602. var value = methods[property];
  1603. if (!onlyIfAbsent || !(property in destination))
  1604. destination[property] = cache.findOrStore(value);
  1605. }
  1606. }
  1607. function findDOMClass(tagName) {
  1608. var klass;
  1609. var trans = {
  1610. "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
  1611. "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
  1612. "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
  1613. "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
  1614. "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
  1615. "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
  1616. "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
  1617. "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
  1618. "FrameSet", "IFRAME": "IFrame"
  1619. };
  1620. if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
  1621. if (window[klass]) return window[klass];
  1622. klass = 'HTML' + tagName + 'Element';
  1623. if (window[klass]) return window[klass];
  1624. klass = 'HTML' + tagName.capitalize() + 'Element';
  1625. if (window[klass]) return window[klass];
  1626. window[klass] = {};
  1627. window[klass].prototype = document.createElement(tagName).__proto__;
  1628. return window[klass];
  1629. }
  1630. if (F.ElementExtensions) {
  1631. copy(Element.Methods, HTMLElement.prototype);
  1632. copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  1633. }
  1634. if (F.SpecificElementExtensions) {
  1635. for (var tag in Element.Methods.ByTag) {
  1636. var klass = findDOMClass(tag);
  1637. if (typeof klass == "undefined") continue;
  1638. copy(T[tag], klass.prototype);
  1639. }
  1640. }
  1641. Object.extend(Element, Element.Methods);
  1642. delete Element.ByTag;
  1643. };
  1644. var Toggle = { display: Element.toggle };
  1645. /*--------------------------------------------------------------------------*/
  1646. Abstract.Insertion = function(adjacency) {
  1647. this.adjacency = adjacency;
  1648. }
  1649. Abstract.Insertion.prototype = {
  1650. initialize: function(element, content) {
  1651. this.element = $(element);
  1652. this.content = content.stripScripts();
  1653. if (this.adjacency && this.element.insertAdjacentHTML) {
  1654. try {
  1655. this.element.insertAdjacentHTML(this.adjacency, this.content);
  1656. } catch (e) {
  1657. var tagName = this.element.tagName.toUpperCase();
  1658. if (['TBODY', 'TR'].include(tagName)) {
  1659. this.insertContent(this.contentFromAnonymousTable());
  1660. } else {
  1661. throw e;
  1662. }
  1663. }
  1664. } else {
  1665. this.range = this.element.ownerDocument.createRange();
  1666. if (this.initializeRange) this.initializeRange();
  1667. this.insertContent([this.range.createContextualFragment(this.content)]);
  1668. }
  1669. setTimeout(function() {content.evalScripts()}, 10);
  1670. },
  1671. contentFromAnonymousTable: function() {
  1672. var div = document.createElement('div');
  1673. div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
  1674. return $A(div.childNodes[0].childNodes[0].childNodes);
  1675. }
  1676. }
  1677. var Insertion = new Object();
  1678. Insertion.Before = Class.create();
  1679. Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  1680. initializeRange: function() {
  1681. this.range.setStartBefore(this.element);
  1682. },
  1683. insertContent: function(fragments) {
  1684. fragments.each((function(fragment) {
  1685. this.element.parentNode.insertBefore(fragment, this.element);
  1686. }).bind(this));
  1687. }
  1688. });
  1689. Insertion.Top = Class.create();
  1690. Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  1691. initializeRange: function() {
  1692. this.range.selectNodeContents(this.element);
  1693. this.range.collapse(true);
  1694. },
  1695. insertContent: function(fragments) {
  1696. fragments.reverse(false).each((function(fragment) {
  1697. this.element.insertBefore(fragment, this.element.firstChild);
  1698. }).bind(this));
  1699. }
  1700. });
  1701. Insertion.Bottom = Class.create();
  1702. Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  1703. initializeRange: function() {
  1704. this.range.selectNodeContents(this.element);
  1705. this.range.collapse(this.element);
  1706. },
  1707. insertContent: function(fragments) {
  1708. fragments.each((function(fragment) {
  1709. this.element.appendChild(fragment);
  1710. }).bind(this));
  1711. }
  1712. });
  1713. Insertion.After = Class.create();
  1714. Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  1715. initializeRange: function() {
  1716. this.range.setStartAfter(this.element);
  1717. },
  1718. insertContent: function(fragments) {
  1719. fragments.each((function(fragment) {
  1720. this.element.parentNode.insertBefore(fragment,
  1721. this.element.nextSibling);
  1722. }).bind(this));
  1723. }
  1724. });
  1725. /*--------------------------------------------------------------------------*/
  1726. Element.ClassNames = Class.create();
  1727. Element.ClassNames.prototype = {
  1728. initialize: function(element) {
  1729. this.element = $(element);
  1730. },
  1731. _each: function(iterator) {
  1732. this.element.className.split(/\s+/).select(function(name) {
  1733. return name.length > 0;
  1734. })._each(iterator);
  1735. },
  1736. set: function(className) {
  1737. this.element.className = className;
  1738. },
  1739. add: function(classNameToAdd) {
  1740. if (this.include(classNameToAdd)) return;
  1741. this.set($A(this).concat(classNameToAdd).join(' '));
  1742. },
  1743. remove: function(classNameToRemove) {
  1744. if (!this.include(classNameToRemove)) return;
  1745. this.set($A(this).without(classNameToRemove).join(' '));
  1746. },
  1747. toString: function() {
  1748. return $A(this).join(' ');
  1749. }
  1750. };
  1751. Object.extend(Element.ClassNames.prototype, Enumerable);
  1752. /* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
  1753. * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
  1754. * license. Please see http://www.yui-ext.com/ for more information. */
  1755. var Selector = Class.create();
  1756. Selector.prototype = {
  1757. initialize: function(expression) {
  1758. this.expression = expression.strip();
  1759. this.compileMatcher();
  1760. },
  1761. compileMatcher: function() {
  1762. // Selectors with namespaced attributes can't use the XPath version
  1763. if (Prototype.BrowserFeatures.XPath && !(/\[[\w-]*?:/).test(this.expression))
  1764. return this.compileXPathMatcher();
  1765. var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
  1766. c = Selector.criteria, le, p, m;
  1767. if (Selector._cache[e]) {
  1768. this.matcher = Selector._cache[e]; return;
  1769. }
  1770. this.matcher = ["this.matcher = function(root) {",
  1771. "var r = root, h = Selector.handlers, c = false, n;"];
  1772. while (e && le != e && (/\S/).test(e)) {
  1773. le = e;
  1774. for (var i in ps) {
  1775. p = ps[i];
  1776. if (m = e.match(p)) {
  1777. this.matcher.push(typeof c[i] == 'function' ? c[i](m) :
  1778. new Template(c[i]).evaluate(m));
  1779. e = e.replace(m[0], '');
  1780. break;
  1781. }
  1782. }
  1783. }
  1784. this.matcher.push("return h.unique(n);\n}");
  1785. eval(this.matcher.join('\n'));
  1786. Selector._cache[this.expression] = this.matcher;
  1787. },
  1788. compileXPathMatcher: function() {
  1789. var e = this.expression, ps = Selector.patterns,
  1790. x = Selector.xpath, le, m;
  1791. if (Selector._cache[e]) {
  1792. this.xpath = Selector._cache[e]; return;
  1793. }
  1794. this.matcher = ['.//*'];
  1795. while (e && le != e && (/\S/).test(e)) {
  1796. le = e;
  1797. for (var i in ps) {
  1798. if (m = e.match(ps[i])) {
  1799. this.matcher.push(typeof x[i] == 'function' ? x[i](m) :
  1800. new Template(x[i]).evaluate(m));
  1801. e = e.replace(m[0], '');
  1802. break;
  1803. }
  1804. }
  1805. }
  1806. this.xpath = this.matcher.join('');
  1807. Selector._cache[this.expression] = this.xpath;
  1808. },
  1809. findElements: function(root) {
  1810. root = root || document;
  1811. if (this.xpath) return document._getElementsByXPath(this.xpath, root);
  1812. return this.matcher(root);
  1813. },
  1814. match: function(element) {
  1815. return this.findElements(document).include(element);
  1816. },
  1817. toString: function() {
  1818. return this.expression;
  1819. },
  1820. inspect: function() {
  1821. return "#<Selector:" + this.expression.inspect() + ">";
  1822. }
  1823. };
  1824. Object.extend(Selector, {
  1825. _cache: {},
  1826. xpath: {
  1827. descendant: "//*",
  1828. child: "/*",
  1829. adjacent: "/following-sibling::*[1]",
  1830. laterSibling: '/following-sibling::*',
  1831. tagName: function(m) {
  1832. if (m[1] == '*') return '';
  1833. return "[local-name()='" + m[1].toLowerCase() +
  1834. "' or local-name()='" + m[1].toUpperCase() + "']";
  1835. },
  1836. className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
  1837. id: "[@id='#{1}']",
  1838. attrPresence: "[@#{1}]",
  1839. attr: function(m) {
  1840. m[3] = m[5] || m[6];
  1841. return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
  1842. },
  1843. pseudo: function(m) {
  1844. var h = Selector.xpath.pseudos[m[1]];
  1845. if (!h) return '';
  1846. if (typeof h === 'function') return h(m);
  1847. return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
  1848. },
  1849. operators: {
  1850. '=': "[@#{1}='#{3}']",
  1851. '!=': "[@#{1}!='#{3}']",
  1852. '^=': "[starts-with(@#{1}, '#{3}')]",
  1853. '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
  1854. '*=': "[contains(@#{1}, '#{3}')]",
  1855. '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
  1856. '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
  1857. },
  1858. pseudos: {
  1859. 'first-child': '[not(preceding-sibling::*)]',
  1860. 'last-child': '[not(following-sibling::*)]',
  1861. 'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
  1862. 'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
  1863. 'checked': "[@checked]",
  1864. 'disabled': "[@disabled]",
  1865. 'enabled': "[not(@disabled)]",
  1866. 'not': function(m) {
  1867. var e = m[6], p = Selector.patterns,
  1868. x = Selector.xpath, le, m, v;
  1869. var exclusion = [];
  1870. while (e && le != e && (/\S/).test(e)) {
  1871. le = e;
  1872. for (var i in p) {
  1873. if (m = e.match(p[i])) {
  1874. v = typeof x[i] == 'function' ? x[i](m) : new Template(x[i]).evaluate(m);
  1875. exclusion.push("(" + v.substring(1, v.length - 1) + ")");
  1876. e = e.replace(m[0], '');
  1877. break;
  1878. }
  1879. }
  1880. }
  1881. return "[not(" + exclusion.join(" and ") + ")]";
  1882. },
  1883. 'nth-child': function(m) {
  1884. return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
  1885. },
  1886. 'nth-last-child': function(m) {
  1887. return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
  1888. },
  1889. 'nth-of-type': function(m) {
  1890. return Selector.xpath.pseudos.nth("position() ", m);
  1891. },
  1892. 'nth-last-of-type': function(m) {
  1893. return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
  1894. },
  1895. 'first-of-type': function(m) {
  1896. m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
  1897. },
  1898. 'last-of-type': function(m) {
  1899. m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
  1900. },
  1901. 'only-of-type': function(m) {
  1902. var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
  1903. },
  1904. nth: function(fragment, m) {
  1905. var mm, formula = m[6], predicate;
  1906. if (formula == 'even') formula = '2n+0';
  1907. if (formula == 'odd') formula = '2n+1';
  1908. if (mm = formula.match(/^(\d+)$/)) // digit only
  1909. return '[' + fragment + "= " + mm[1] + ']';
  1910. if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
  1911. if (mm[1] == "-") mm[1] = -1;
  1912. var a = mm[1] ? Number(mm[1]) : 1;
  1913. var b = mm[2] ? Number(mm[2]) : 0;
  1914. predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
  1915. "((#{fragment} - #{b}) div #{a} >= 0)]";
  1916. return new Template(predicate).evaluate({
  1917. fragment: fragment, a: a, b: b });
  1918. }
  1919. }
  1920. }
  1921. },
  1922. criteria: {
  1923. tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
  1924. className: 'n = h.className(n, r, "#{1}", c); c = false;',
  1925. id: 'n = h.id(n, r, "#{1}", c); c = false;',
  1926. attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;',
  1927. attr: function(m) {
  1928. m[3] = (m[5] || m[6]);
  1929. return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m);
  1930. },
  1931. pseudo: function(m) {
  1932. if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
  1933. return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
  1934. },
  1935. descendant: 'c = "descendant";',
  1936. child: 'c = "child";',
  1937. adjacent: 'c = "adjacent";',
  1938. laterSibling: 'c = "laterSibling";'
  1939. },
  1940. patterns: {
  1941. // combinators must be listed first
  1942. // (and descendant needs to be last combinator)
  1943. laterSibling: /^\s*~\s*/,
  1944. child: /^\s*>\s*/,
  1945. adjacent: /^\s*\+\s*/,
  1946. descendant: /^\s/,
  1947. // selectors follow
  1948. tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
  1949. id: /^#([\w\-\*]+)(\b|$)/,
  1950. className: /^\.([\w\-\*]+)(\b|$)/,
  1951. pseudo: /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|\s|(?=:))/,
  1952. attrPresence: /^\[([\w]+)\]/,
  1953. attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\]]*?)\4|([^'"][^\]]*?)))?\]/
  1954. },
  1955. handlers: {
  1956. // UTILITY FUNCTIONS
  1957. // joins two collections
  1958. concat: function(a, b) {
  1959. for (var i = 0, node; node = b[i]; i++)
  1960. a.push(node);
  1961. return a;
  1962. },
  1963. // marks an array of nodes for counting
  1964. mark: function(nodes) {
  1965. for (var i = 0, node; node = nodes[i]; i++)
  1966. node._counted = true;
  1967. return nodes;
  1968. },
  1969. unmark: function(nodes) {
  1970. for (var i = 0, node; node = nodes[i]; i++)
  1971. node._counted = undefined;
  1972. return nodes;
  1973. },
  1974. // mark each child node with its position (for nth calls)
  1975. // "ofType" flag indicates whether we're indexing for nth-of-type
  1976. // rather than nth-child
  1977. index: function(parentNode, reverse, ofType) {
  1978. parentNode._counted = true;
  1979. if (reverse) {
  1980. for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
  1981. node = nodes[i];
  1982. if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
  1983. }
  1984. } else {
  1985. for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
  1986. if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
  1987. }
  1988. },
  1989. // filters out duplicates and extends all nodes
  1990. unique: function(nodes) {
  1991. if (nodes.length == 0) return nodes;
  1992. var results = [], n;
  1993. for (var i = 0, l = nodes.length; i < l; i++)
  1994. if (!(n = nodes[i])._counted) {
  1995. n._counted = true;
  1996. results.push(Element.extend(n));
  1997. }
  1998. return Selector.handlers.unmark(results);
  1999. },
  2000. // COMBINATOR FUNCTIONS
  2001. descendant: function(nodes) {
  2002. var h = Selector.handlers;
  2003. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2004. h.concat(results, node.getElementsByTagName('*'));
  2005. return results;
  2006. },
  2007. child: function(nodes) {
  2008. var h = Selector.handlers;
  2009. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2010. for (var j = 0, children = [], child; child = node.childNodes[j]; j++)
  2011. if (child.nodeType == 1 && child.tagName != '!') results.push(child);
  2012. }
  2013. return results;
  2014. },
  2015. adjacent: function(nodes) {
  2016. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2017. var next = this.nextElementSibling(node);
  2018. if (next) results.push(next);
  2019. }
  2020. return results;
  2021. },
  2022. laterSibling: function(nodes) {
  2023. var h = Selector.handlers;
  2024. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2025. h.concat(results, Element.nextSiblings(node));
  2026. return results;
  2027. },
  2028. nextElementSibling: function(node) {
  2029. while (node = node.nextSibling)
  2030. if (node.nodeType == 1) return node;
  2031. return null;
  2032. },
  2033. previousElementSibling: function(node) {
  2034. while (node = node.previousSibling)
  2035. if (node.nodeType == 1) return node;
  2036. return null;
  2037. },
  2038. // TOKEN FUNCTIONS
  2039. tagName: function(nodes, root, tagName, combinator) {
  2040. tagName = tagName.toUpperCase();
  2041. var results = [], h = Selector.handlers;
  2042. if (nodes) {
  2043. if (combinator) {
  2044. // fastlane for ordinary descendant combinators
  2045. if (combinator == "descendant") {
  2046. for (var i = 0, node; node = nodes[i]; i++)
  2047. h.concat(results, node.getElementsByTagName(tagName));
  2048. return results;
  2049. } else nodes = this[combinator](nodes);
  2050. if (tagName == "*") return nodes;
  2051. }
  2052. for (var i = 0, node; node = nodes[i]; i++)
  2053. if (node.tagName.toUpperCase() == tagName) results.push(node);
  2054. return results;
  2055. } else return root.getElementsByTagName(tagName);
  2056. },
  2057. id: function(nodes, root, id, combinator) {
  2058. var targetNode = $(id), h = Selector.handlers;
  2059. if (!nodes && root == document) return targetNode ? [targetNode] : [];
  2060. if (nodes) {
  2061. if (combinator) {
  2062. if (combinator == 'child') {
  2063. for (var i = 0, node; node = nodes[i]; i++)
  2064. if (targetNode.parentNode == node) return [targetNode];
  2065. } else if (combinator == 'descendant') {
  2066. for (var i = 0, node; node = nodes[i]; i++)
  2067. if (Element.descendantOf(targetNode, node)) return [targetNode];
  2068. } else if (combinator == 'adjacent') {
  2069. for (var i = 0, node; node = nodes[i]; i++)
  2070. if (Selector.handlers.previousElementSibling(targetNode) == node)
  2071. return [targetNode];
  2072. } else nodes = h[combinator](nodes);
  2073. }
  2074. for (var i = 0, node; node = nodes[i]; i++)
  2075. if (node == targetNode) return [targetNode];
  2076. return [];
  2077. }
  2078. return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
  2079. },
  2080. className: function(nodes, root, className, combinator) {
  2081. if (nodes && combinator) nodes = this[combinator](nodes);
  2082. return Selector.handlers.byClassName(nodes, root, className);
  2083. },
  2084. byClassName: function(nodes, root, className) {
  2085. if (!nodes) nodes = Selector.handlers.descendant([root]);
  2086. var needle = ' ' + className + ' ';
  2087. for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
  2088. nodeClassName = node.className;
  2089. if (nodeClassName.length == 0) continue;
  2090. if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
  2091. results.push(node);
  2092. }
  2093. return results;
  2094. },
  2095. attrPresence: function(nodes, root, attr) {
  2096. var results = [];
  2097. for (var i = 0, node; node = nodes[i]; i++)
  2098. if (Element.hasAttribute(node, attr)) results.push(node);
  2099. return results;
  2100. },
  2101. attr: function(nodes, root, attr, value, operator) {
  2102. if (!nodes) nodes = root.getElementsByTagName("*");
  2103. var handler = Selector.operators[operator], results = [];
  2104. for (var i = 0, node; node = nodes[i]; i++) {
  2105. var nodeValue = Element.readAttribute(node, attr);
  2106. if (nodeValue === null) continue;
  2107. if (handler(nodeValue, value)) results.push(node);
  2108. }
  2109. return results;
  2110. },
  2111. pseudo: function(nodes, name, value, root, combinator) {
  2112. if (nodes && combinator) nodes = this[combinator](nodes);
  2113. if (!nodes) nodes = root.getElementsByTagName("*");
  2114. return Selector.pseudos[name](nodes, value, root);
  2115. }
  2116. },
  2117. pseudos: {
  2118. 'first-child': function(nodes, value, root) {
  2119. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2120. if (Selector.handlers.previousElementSibling(node)) continue;
  2121. results.push(node);
  2122. }
  2123. return results;
  2124. },
  2125. 'last-child': function(nodes, value, root) {
  2126. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2127. if (Selector.handlers.nextElementSibling(node)) continue;
  2128. results.push(node);
  2129. }
  2130. return results;
  2131. },
  2132. 'only-child': function(nodes, value, root) {
  2133. var h = Selector.handlers;
  2134. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2135. if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
  2136. results.push(node);
  2137. return results;
  2138. },
  2139. 'nth-child': function(nodes, formula, root) {
  2140. return Selector.pseudos.nth(nodes, formula, root);
  2141. },
  2142. 'nth-last-child': function(nodes, formula, root) {
  2143. return Selector.pseudos.nth(nodes, formula, root, true);
  2144. },
  2145. 'nth-of-type': function(nodes, formula, root) {
  2146. return Selector.pseudos.nth(nodes, formula, root, false, true);
  2147. },
  2148. 'nth-last-of-type': function(nodes, formula, root) {
  2149. return Selector.pseudos.nth(nodes, formula, root, true, true);
  2150. },
  2151. 'first-of-type': function(nodes, formula, root) {
  2152. return Selector.pseudos.nth(nodes, "1", root, false, true);
  2153. },
  2154. 'last-of-type': function(nodes, formula, root) {
  2155. return Selector.pseudos.nth(nodes, "1", root, true, true);
  2156. },
  2157. 'only-of-type': function(nodes, formula, root) {
  2158. var p = Selector.pseudos;
  2159. return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
  2160. },
  2161. // handles the an+b logic
  2162. getIndices: function(a, b, total) {
  2163. if (a == 0) return b > 0 ? [b] : [];
  2164. return $R(1, total).inject([], function(memo, i) {
  2165. if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
  2166. return memo;
  2167. });
  2168. },
  2169. // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
  2170. nth: function(nodes, formula, root, reverse, ofType) {
  2171. if (nodes.length == 0) return [];
  2172. if (formula == 'even') formula = '2n+0';
  2173. if (formula == 'odd') formula = '2n+1';
  2174. var h = Selector.handlers, results = [], indexed = [], m;
  2175. h.mark(nodes);
  2176. for (var i = 0, node; node = nodes[i]; i++) {
  2177. if (!node.parentNode._counted) {
  2178. h.index(node.parentNode, reverse, ofType);
  2179. indexed.push(node.parentNode);
  2180. }
  2181. }
  2182. if (formula.match(/^\d+$/)) { // just a number
  2183. formula = Number(formula);
  2184. for (var i = 0, node; node = nodes[i]; i++)
  2185. if (node.nodeIndex == formula) results.push(node);
  2186. } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
  2187. if (m[1] == "-") m[1] = -1;
  2188. var a = m[1] ? Number(m[1]) : 1;
  2189. var b = m[2] ? Number(m[2]) : 0;
  2190. var indices = Selector.pseudos.getIndices(a, b, nodes.length);
  2191. for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
  2192. for (var j = 0; j < l; j++)
  2193. if (node.nodeIndex == indices[j]) results.push(node);
  2194. }
  2195. }
  2196. h.unmark(nodes);
  2197. h.unmark(indexed);
  2198. return results;
  2199. },
  2200. 'empty': function(nodes, value, root) {
  2201. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2202. // IE treats comments as element nodes
  2203. if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
  2204. results.push(node);
  2205. }
  2206. return results;
  2207. },
  2208. 'not': function(nodes, selector, root) {
  2209. var h = Selector.handlers, selectorType, m;
  2210. var exclusions = new Selector(selector).findElements(root);
  2211. h.mark(exclusions);
  2212. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2213. if (!node._counted) results.push(node);
  2214. h.unmark(exclusions);
  2215. return results;
  2216. },
  2217. 'enabled': function(nodes, value, root) {
  2218. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2219. if (!node.disabled) results.push(node);
  2220. return results;
  2221. },
  2222. 'disabled': function(nodes, value, root) {
  2223. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2224. if (node.disabled) results.push(node);
  2225. return results;
  2226. },
  2227. 'checked': function(nodes, value, root) {
  2228. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2229. if (node.checked) results.push(node);
  2230. return results;
  2231. }
  2232. },
  2233. operators: {
  2234. '=': function(nv, v) { return nv == v; },
  2235. '!=': function(nv, v) { return nv != v; },
  2236. '^=': function(nv, v) { return nv.startsWith(v); },
  2237. '$=': function(nv, v) { return nv.endsWith(v); },
  2238. '*=': function(nv, v) { return nv.include(v); },
  2239. '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
  2240. '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
  2241. },
  2242. matchElements: function(elements, expression) {
  2243. var matches = new Selector(expression).findElements(), h = Selector.handlers;
  2244. h.mark(matches);
  2245. for (var i = 0, results = [], element; element = elements[i]; i++)
  2246. if (element._counted) results.push(element);
  2247. h.unmark(matches);
  2248. return results;
  2249. },
  2250. findElement: function(elements, expression, index) {
  2251. if (typeof expression == 'number') {
  2252. index = expression; expression = false;
  2253. }
  2254. return Selector.matchElements(elements, expression || '*')[index || 0];
  2255. },
  2256. findChildElements: function(element, expressions) {
  2257. var exprs = expressions.join(','), expressions = [];
  2258. exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
  2259. expressions.push(m[1].strip());
  2260. });
  2261. var results = [], h = Selector.handlers;
  2262. for (var i = 0, l = expressions.length, selector; i < l; i++) {
  2263. selector = new Selector(expressions[i].strip());
  2264. h.concat(results, selector.findElements(element));
  2265. }
  2266. return (l > 1) ? h.unique(results) : results;
  2267. }
  2268. });
  2269. function $$() {
  2270. return Selector.findChildElements(document, $A(arguments));
  2271. }
  2272. var Form = {
  2273. reset: function(form) {
  2274. $(form).reset();
  2275. return form;
  2276. },
  2277. serializeElements: function(elements, getHash) {
  2278. var data = elements.inject({}, function(result, element) {
  2279. if (!element.disabled && element.name) {
  2280. var key = element.name, value = $(element).getValue();
  2281. if (value != null) {
  2282. if (key in result) {
  2283. if (result[key].constructor != Array) result[key] = [result[key]];
  2284. result[key].push(value);
  2285. }
  2286. else result[key] = value;
  2287. }
  2288. }
  2289. return result;
  2290. });
  2291. return getHash ? data : Hash.toQueryString(data);
  2292. }
  2293. };
  2294. Form.Methods = {
  2295. serialize: function(form, getHash) {
  2296. return Form.serializeElements(Form.getElements(form), getHash);
  2297. },
  2298. getElements: function(form) {
  2299. return $A($(form).getElementsByTagName('*')).inject([],
  2300. function(elements, child) {
  2301. if (Form.Element.Serializers[child.tagName.toLowerCase()])
  2302. elements.push(Element.extend(child));
  2303. return elements;
  2304. }
  2305. );
  2306. },
  2307. getInputs: function(form, typeName, name) {
  2308. form = $(form);
  2309. var inputs = form.getElementsByTagName('input');
  2310. if (!typeName && !name) return $A(inputs).map(Element.extend);
  2311. for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
  2312. var input = inputs[i];
  2313. if ((typeName && input.type != typeName) || (name && input.name != name))
  2314. continue;
  2315. matchingInputs.push(Element.extend(input));
  2316. }
  2317. return matchingInputs;
  2318. },
  2319. disable: function(form) {
  2320. form = $(form);
  2321. Form.getElements(form).invoke('disable');
  2322. return form;
  2323. },
  2324. enable: function(form) {
  2325. form = $(form);
  2326. Form.getElements(form).invoke('enable');
  2327. return form;
  2328. },
  2329. findFirstElement: function(form) {
  2330. return $(form).getElements().find(function(element) {
  2331. return element.type != 'hidden' && !element.disabled &&
  2332. ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
  2333. });
  2334. },
  2335. focusFirstElement: function(form) {
  2336. form = $(form);
  2337. form.findFirstElement().activate();
  2338. return form;
  2339. },
  2340. request: function(form, options) {
  2341. form = $(form), options = Object.clone(options || {});
  2342. var params = options.parameters;
  2343. options.parameters = form.serialize(true);
  2344. if (params) {
  2345. if (typeof params == 'string') params = params.toQueryParams();
  2346. Object.extend(options.parameters, params);
  2347. }
  2348. if (form.hasAttribute('method') && !options.method)
  2349. options.method = form.method;
  2350. return new Ajax.Request(form.readAttribute('action'), options);
  2351. }
  2352. }
  2353. /*--------------------------------------------------------------------------*/
  2354. Form.Element = {
  2355. focus: function(element) {
  2356. $(element).focus();
  2357. return element;
  2358. },
  2359. select: function(element) {
  2360. $(element).select();
  2361. return element;
  2362. }
  2363. }
  2364. Form.Element.Methods = {
  2365. serialize: function(element) {
  2366. element = $(element);
  2367. if (!element.disabled && element.name) {
  2368. var value = element.getValue();
  2369. if (value != undefined) {
  2370. var pair = {};
  2371. pair[element.name] = value;
  2372. return Hash.toQueryString(pair);
  2373. }
  2374. }
  2375. return '';
  2376. },
  2377. getValue: function(element) {
  2378. element = $(element);
  2379. var method = element.tagName.toLowerCase();
  2380. return Form.Element.Serializers[method](element);
  2381. },
  2382. clear: function(element) {
  2383. $(element).value = '';
  2384. return element;
  2385. },
  2386. present: function(element) {
  2387. return $(element).value != '';
  2388. },
  2389. activate: function(element) {
  2390. element = $(element);
  2391. try {
  2392. element.focus();
  2393. if (element.select && (element.tagName.toLowerCase() != 'input' ||
  2394. !['button', 'reset', 'submit'].include(element.type)))
  2395. element.select();
  2396. } catch (e) {}
  2397. return element;
  2398. },
  2399. disable: function(element) {
  2400. element = $(element);
  2401. element.blur();
  2402. element.disabled = true;
  2403. return element;
  2404. },
  2405. enable: function(element) {
  2406. element = $(element);
  2407. element.disabled = false;
  2408. return element;
  2409. }
  2410. }
  2411. /*--------------------------------------------------------------------------*/
  2412. var Field = Form.Element;
  2413. var $F = Form.Element.Methods.getValue;
  2414. /*--------------------------------------------------------------------------*/
  2415. Form.Element.Serializers = {
  2416. input: function(element) {
  2417. switch (element.type.toLowerCase()) {
  2418. case 'checkbox':
  2419. case 'radio':
  2420. return Form.Element.Serializers.inputSelector(element);
  2421. default:
  2422. return Form.Element.Serializers.textarea(element);
  2423. }
  2424. },
  2425. inputSelector: function(element) {
  2426. return element.checked ? element.value : null;
  2427. },
  2428. textarea: function(element) {
  2429. return element.value;
  2430. },
  2431. select: function(element) {
  2432. return this[element.type == 'select-one' ?
  2433. 'selectOne' : 'selectMany'](element);
  2434. },
  2435. selectOne: function(element) {
  2436. var index = element.selectedIndex;
  2437. return index >= 0 ? this.optionValue(element.options[index]) : null;
  2438. },
  2439. selectMany: function(element) {
  2440. var values, length = element.length;
  2441. if (!length) return null;
  2442. for (var i = 0, values = []; i < length; i++) {
  2443. var opt = element.options[i];
  2444. if (opt.selected) values.push(this.optionValue(opt));
  2445. }
  2446. return values;
  2447. },
  2448. optionValue: function(opt) {
  2449. // extend element because hasAttribute may not be native
  2450. return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  2451. }
  2452. }
  2453. /*--------------------------------------------------------------------------*/
  2454. Abstract.TimedObserver = function() {}
  2455. Abstract.TimedObserver.prototype = {
  2456. initialize: function(element, frequency, callback) {
  2457. this.frequency = frequency;
  2458. this.element = $(element);
  2459. this.callback = callback;
  2460. this.lastValue = this.getValue();
  2461. this.registerCallback();
  2462. },
  2463. registerCallback: function() {
  2464. setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  2465. },
  2466. onTimerEvent: function() {
  2467. var value = this.getValue();
  2468. var changed = ('string' == typeof this.lastValue && 'string' == typeof value
  2469. ? this.lastValue != value : String(this.lastValue) != String(value));
  2470. if (changed) {
  2471. this.callback(this.element, value);
  2472. this.lastValue = value;
  2473. }
  2474. }
  2475. }
  2476. Form.Element.Observer = Class.create();
  2477. Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  2478. getValue: function() {
  2479. return Form.Element.getValue(this.element);
  2480. }
  2481. });
  2482. Form.Observer = Class.create();
  2483. Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  2484. getValue: function() {
  2485. return Form.serialize(this.element);
  2486. }
  2487. });
  2488. /*--------------------------------------------------------------------------*/
  2489. Abstract.EventObserver = function() {}
  2490. Abstract.EventObserver.prototype = {
  2491. initialize: function(element, callback) {
  2492. this.element = $(element);
  2493. this.callback = callback;
  2494. this.lastValue = this.getValue();
  2495. if (this.element.tagName.toLowerCase() == 'form')
  2496. this.registerFormCallbacks();
  2497. else
  2498. this.registerCallback(this.element);
  2499. },
  2500. onElementEvent: function() {
  2501. var value = this.getValue();
  2502. if (this.lastValue != value) {
  2503. this.callback(this.element, value);
  2504. this.lastValue = value;
  2505. }
  2506. },
  2507. registerFormCallbacks: function() {
  2508. Form.getElements(this.element).each(this.registerCallback.bind(this));
  2509. },
  2510. registerCallback: function(element) {
  2511. if (element.type) {
  2512. switch (element.type.toLowerCase()) {
  2513. case 'checkbox':
  2514. case 'radio':
  2515. Event.observe(element, 'click', this.onElementEvent.bind(this));
  2516. break;
  2517. default:
  2518. Event.observe(element, 'change', this.onElementEvent.bind(this));
  2519. break;
  2520. }
  2521. }
  2522. }
  2523. }
  2524. Form.Element.EventObserver = Class.create();
  2525. Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  2526. getValue: function() {
  2527. return Form.Element.getValue(this.element);
  2528. }
  2529. });
  2530. Form.EventObserver = Class.create();
  2531. Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  2532. getValue: function() {
  2533. return Form.serialize(this.element);
  2534. }
  2535. });
  2536. if (!window.Event) {
  2537. var Event = new Object();
  2538. }
  2539. Object.extend(Event, {
  2540. KEY_BACKSPACE: 8,
  2541. KEY_TAB: 9,
  2542. KEY_RETURN: 13,
  2543. KEY_ESC: 27,
  2544. KEY_LEFT: 37,
  2545. KEY_UP: 38,
  2546. KEY_RIGHT: 39,
  2547. KEY_DOWN: 40,
  2548. KEY_DELETE: 46,
  2549. KEY_HOME: 36,
  2550. KEY_END: 35,
  2551. KEY_PAGEUP: 33,
  2552. KEY_PAGEDOWN: 34,
  2553. element: function(event) {
  2554. return $(event.target || event.srcElement);
  2555. },
  2556. isLeftClick: function(event) {
  2557. return (((event.which) && (event.which == 1)) ||
  2558. ((event.button) && (event.button == 1)));
  2559. },
  2560. pointerX: function(event) {
  2561. return event.pageX || (event.clientX +
  2562. (document.documentElement.scrollLeft || document.body.scrollLeft));
  2563. },
  2564. pointerY: function(event) {
  2565. return event.pageY || (event.clientY +
  2566. (document.documentElement.scrollTop || document.body.scrollTop));
  2567. },
  2568. stop: function(event) {
  2569. if (event.preventDefault) {
  2570. event.preventDefault();
  2571. event.stopPropagation();
  2572. } else {
  2573. event.returnValue = false;
  2574. event.cancelBubble = true;
  2575. }
  2576. },
  2577. // find the first node with the given tagName, starting from the
  2578. // node the event was triggered on; traverses the DOM upwards
  2579. findElement: function(event, tagName) {
  2580. var element = Event.element(event);
  2581. while (element.parentNode && (!element.tagName ||
  2582. (element.tagName.toUpperCase() != tagName.toUpperCase())))
  2583. element = element.parentNode;
  2584. return element;
  2585. },
  2586. observers: false,
  2587. _observeAndCache: function(element, name, observer, useCapture) {
  2588. if (!this.observers) this.observers = [];
  2589. if (element.addEventListener) {
  2590. this.observers.push([element, name, observer, useCapture]);
  2591. element.addEventListener(name, observer, useCapture);
  2592. } else if (element.attachEvent) {
  2593. this.observers.push([element, name, observer, useCapture]);
  2594. element.attachEvent('on' + name, observer);
  2595. }
  2596. },
  2597. unloadCache: function() {
  2598. if (!Event.observers) return;
  2599. for (var i = 0, length = Event.observers.length; i < length; i++) {
  2600. Event.stopObserving.apply(this, Event.observers[i]);
  2601. Event.observers[i][0] = null;
  2602. }
  2603. Event.observers = false;
  2604. },
  2605. observe: function(element, name, observer, useCapture) {
  2606. element = $(element);
  2607. useCapture = useCapture || false;
  2608. if (name == 'keypress' &&
  2609. (Prototype.Browser.WebKit || element.attachEvent))
  2610. name = 'keydown';
  2611. Event._observeAndCache(element, name, observer, useCapture);
  2612. },
  2613. stopObserving: function(element, name, observer, useCapture) {
  2614. element = $(element);
  2615. useCapture = useCapture || false;
  2616. if (name == 'keypress' &&
  2617. (Prototype.Browser.WebKit || element.attachEvent))
  2618. name = 'keydown';
  2619. if (element.removeEventListener) {
  2620. element.removeEventListener(name, observer, useCapture);
  2621. } else if (element.detachEvent) {
  2622. try {
  2623. element.detachEvent('on' + name, observer);
  2624. } catch (e) {}
  2625. }
  2626. }
  2627. });
  2628. /* prevent memory leaks in IE */
  2629. if (Prototype.Browser.IE)
  2630. Event.observe(window, 'unload', Event.unloadCache, false);
  2631. var Position = {
  2632. // set to true if needed, warning: firefox performance problems
  2633. // NOT neeeded for page scrolling, only if draggable contained in
  2634. // scrollable elements
  2635. includeScrollOffsets: false,
  2636. // must be called before calling withinIncludingScrolloffset, every time the
  2637. // page is scrolled
  2638. prepare: function() {
  2639. this.deltaX = window.pageXOffset
  2640. || document.documentElement.scrollLeft
  2641. || document.body.scrollLeft
  2642. || 0;
  2643. this.deltaY = window.pageYOffset
  2644. || document.documentElement.scrollTop
  2645. || document.body.scrollTop
  2646. || 0;
  2647. },
  2648. realOffset: function(element) {
  2649. var valueT = 0, valueL = 0;
  2650. do {
  2651. valueT += element.scrollTop || 0;
  2652. valueL += element.scrollLeft || 0;
  2653. element = element.parentNode;
  2654. } while (element);
  2655. return [valueL, valueT];
  2656. },
  2657. cumulativeOffset: function(element) {
  2658. var valueT = 0, valueL = 0;
  2659. do {
  2660. valueT += element.offsetTop || 0;
  2661. valueL += element.offsetLeft || 0;
  2662. element = element.offsetParent;
  2663. } while (element);
  2664. return [valueL, valueT];
  2665. },
  2666. positionedOffset: function(element) {
  2667. var valueT = 0, valueL = 0;
  2668. do {
  2669. valueT += element.offsetTop || 0;
  2670. valueL += element.offsetLeft || 0;
  2671. element = element.offsetParent;
  2672. if (element) {
  2673. if(element.tagName=='BODY') break;
  2674. var p = Element.getStyle(element, 'position');
  2675. if (p == 'relative' || p == 'absolute') break;
  2676. }
  2677. } while (element);
  2678. return [valueL, valueT];
  2679. },
  2680. offsetParent: function(element) {
  2681. if (element.offsetParent) return element.offsetParent;
  2682. if (element == document.body) return element;
  2683. while ((element = element.parentNode) && element != document.body)
  2684. if (Element.getStyle(element, 'position') != 'static')
  2685. return element;
  2686. return document.body;
  2687. },
  2688. // caches x/y coordinate pair to use with overlap
  2689. within: function(element, x, y) {
  2690. if (this.includeScrollOffsets)
  2691. return this.withinIncludingScrolloffsets(element, x, y);
  2692. this.xcomp = x;
  2693. this.ycomp = y;
  2694. this.offset = this.cumulativeOffset(element);
  2695. return (y >= this.offset[1] &&
  2696. y < this.offset[1] + element.offsetHeight &&
  2697. x >= this.offset[0] &&
  2698. x < this.offset[0] + element.offsetWidth);
  2699. },
  2700. withinIncludingScrolloffsets: function(element, x, y) {
  2701. var offsetcache = this.realOffset(element);
  2702. this.xcomp = x + offsetcache[0] - this.deltaX;
  2703. this.ycomp = y + offsetcache[1] - this.deltaY;
  2704. this.offset = this.cumulativeOffset(element);
  2705. return (this.ycomp >= this.offset[1] &&
  2706. this.ycomp < this.offset[1] + element.offsetHeight &&
  2707. this.xcomp >= this.offset[0] &&
  2708. this.xcomp < this.offset[0] + element.offsetWidth);
  2709. },
  2710. // within must be called directly before
  2711. overlap: function(mode, element) {
  2712. if (!mode) return 0;
  2713. if (mode == 'vertical')
  2714. return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
  2715. element.offsetHeight;
  2716. if (mode == 'horizontal')
  2717. return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
  2718. element.offsetWidth;
  2719. },
  2720. page: function(forElement) {
  2721. var valueT = 0, valueL = 0;
  2722. var element = forElement;
  2723. do {
  2724. valueT += element.offsetTop || 0;
  2725. valueL += element.offsetLeft || 0;
  2726. // Safari fix
  2727. if (element.offsetParent == document.body)
  2728. if (Element.getStyle(element,'position')=='absolute') break;
  2729. } while (element = element.offsetParent);
  2730. element = forElement;
  2731. do {
  2732. if (!window.opera || element.tagName=='BODY') {
  2733. valueT -= element.scrollTop || 0;
  2734. valueL -= element.scrollLeft || 0;
  2735. }
  2736. } while (element = element.parentNode);
  2737. return [valueL, valueT];
  2738. },
  2739. clone: function(source, target) {
  2740. var options = Object.extend({
  2741. setLeft: true,
  2742. setTop: true,
  2743. setWidth: true,
  2744. setHeight: true,
  2745. offsetTop: 0,
  2746. offsetLeft: 0
  2747. }, arguments[2] || {})
  2748. // find page position of source
  2749. source = $(source);
  2750. var p = Position.page(source);
  2751. // find coordinate system to use
  2752. target = $(target);
  2753. var delta = [0, 0];
  2754. var parent = null;
  2755. // delta [0,0] will do fine with position: fixed elements,
  2756. // position:absolute needs offsetParent deltas
  2757. if (Element.getStyle(target,'position') == 'absolute') {
  2758. parent = Position.offsetParent(target);
  2759. delta = Position.page(parent);
  2760. }
  2761. // correct by body offsets (fixes Safari)
  2762. if (parent == document.body) {
  2763. delta[0] -= document.body.offsetLeft;
  2764. delta[1] -= document.body.offsetTop;
  2765. }
  2766. // set position
  2767. if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
  2768. if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
  2769. if(options.setWidth) target.style.width = source.offsetWidth + 'px';
  2770. if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  2771. },
  2772. absolutize: function(element) {
  2773. element = $(element);
  2774. if (element.style.position == 'absolute') return;
  2775. Position.prepare();
  2776. var offsets = Position.positionedOffset(element);
  2777. var top = offsets[1];
  2778. var left = offsets[0];
  2779. var width = element.clientWidth;
  2780. var height = element.clientHeight;
  2781. element._originalLeft = left - parseFloat(element.style.left || 0);
  2782. element._originalTop = top - parseFloat(element.style.top || 0);
  2783. element._originalWidth = element.style.width;
  2784. element._originalHeight = element.style.height;
  2785. element.style.position = 'absolute';
  2786. element.style.top = top + 'px';
  2787. element.style.left = left + 'px';
  2788. element.style.width = width + 'px';
  2789. element.style.height = height + 'px';
  2790. },
  2791. relativize: function(element) {
  2792. element = $(element);
  2793. if (element.style.position == 'relative') return;
  2794. Position.prepare();
  2795. element.style.position = 'relative';
  2796. var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
  2797. var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
  2798. element.style.top = top + 'px';
  2799. element.style.left = left + 'px';
  2800. element.style.height = element._originalHeight;
  2801. element.style.width = element._originalWidth;
  2802. }
  2803. }
  2804. // Safari returns margins on body which is incorrect if the child is absolutely
  2805. // positioned. For performance reasons, redefine Position.cumulativeOffset for
  2806. // KHTML/WebKit only.
  2807. if (Prototype.Browser.WebKit) {
  2808. Position.cumulativeOffset = function(element) {
  2809. var valueT = 0, valueL = 0;
  2810. do {
  2811. valueT += element.offsetTop || 0;
  2812. valueL += element.offsetLeft || 0;
  2813. if (element.offsetParent == document.body)
  2814. if (Element.getStyle(element, 'position') == 'absolute') break;
  2815. element = element.offsetParent;
  2816. } while (element);
  2817. return [valueL, valueT];
  2818. }
  2819. }
  2820. Element.addMethods();