prototype.js 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170
  1. /* Prototype JavaScript framework, version 1.6.0.1
  2. * (c) 2005-2007 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.6.0.1',
  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. MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
  16. },
  17. BrowserFeatures: {
  18. XPath: !!document.evaluate,
  19. ElementExtensions: !!window.HTMLElement,
  20. SpecificElementExtensions:
  21. document.createElement('div').__proto__ &&
  22. document.createElement('div').__proto__ !==
  23. document.createElement('form').__proto__
  24. },
  25. ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
  26. JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
  27. emptyFunction: function() { },
  28. K: function(x) { return x }
  29. };
  30. if (Prototype.Browser.MobileSafari)
  31. Prototype.BrowserFeatures.SpecificElementExtensions = false;
  32. /* Based on Alex Arnell's inheritance implementation. */
  33. var Class = {
  34. create: function() {
  35. var parent = null, properties = $A(arguments);
  36. if (Object.isFunction(properties[0]))
  37. parent = properties.shift();
  38. function klass() {
  39. this.initialize.apply(this, arguments);
  40. }
  41. Object.extend(klass, Class.Methods);
  42. klass.superclass = parent;
  43. klass.subclasses = [];
  44. if (parent) {
  45. var subclass = function() { };
  46. subclass.prototype = parent.prototype;
  47. klass.prototype = new subclass;
  48. parent.subclasses.push(klass);
  49. }
  50. for (var i = 0; i < properties.length; i++)
  51. klass.addMethods(properties[i]);
  52. if (!klass.prototype.initialize)
  53. klass.prototype.initialize = Prototype.emptyFunction;
  54. klass.prototype.constructor = klass;
  55. return klass;
  56. }
  57. };
  58. Class.Methods = {
  59. addMethods: function(source) {
  60. var ancestor = this.superclass && this.superclass.prototype;
  61. var properties = Object.keys(source);
  62. if (!Object.keys({ toString: true }).length)
  63. properties.push("toString", "valueOf");
  64. for (var i = 0, length = properties.length; i < length; i++) {
  65. var property = properties[i], value = source[property];
  66. if (ancestor && Object.isFunction(value) &&
  67. value.argumentNames().first() == "$super") {
  68. var method = value, value = Object.extend((function(m) {
  69. return function() { return ancestor[m].apply(this, arguments) };
  70. })(property).wrap(method), {
  71. valueOf: function() { return method },
  72. toString: function() { return method.toString() }
  73. });
  74. }
  75. this.prototype[property] = value;
  76. }
  77. return this;
  78. }
  79. };
  80. var Abstract = { };
  81. Object.extend = function(destination, source) {
  82. for (var property in source)
  83. destination[property] = source[property];
  84. return destination;
  85. };
  86. Object.extend(Object, {
  87. inspect: function(object) {
  88. try {
  89. if (Object.isUndefined(object)) return 'undefined';
  90. if (object === null) return 'null';
  91. return object.inspect ? object.inspect() : object.toString();
  92. } catch (e) {
  93. if (e instanceof RangeError) return '...';
  94. throw e;
  95. }
  96. },
  97. toJSON: function(object) {
  98. var type = typeof object;
  99. switch (type) {
  100. case 'undefined':
  101. case 'function':
  102. case 'unknown': return;
  103. case 'boolean': return object.toString();
  104. }
  105. if (object === null) return 'null';
  106. if (object.toJSON) return object.toJSON();
  107. if (Object.isElement(object)) return;
  108. var results = [];
  109. for (var property in object) {
  110. var value = Object.toJSON(object[property]);
  111. if (!Object.isUndefined(value))
  112. results.push(property.toJSON() + ': ' + value);
  113. }
  114. return '{' + results.join(', ') + '}';
  115. },
  116. toQueryString: function(object) {
  117. return $H(object).toQueryString();
  118. },
  119. toHTML: function(object) {
  120. return object && object.toHTML ? object.toHTML() : String.interpret(object);
  121. },
  122. keys: function(object) {
  123. var keys = [];
  124. for (var property in object)
  125. keys.push(property);
  126. return keys;
  127. },
  128. values: function(object) {
  129. var values = [];
  130. for (var property in object)
  131. values.push(object[property]);
  132. return values;
  133. },
  134. clone: function(object) {
  135. return Object.extend({ }, object);
  136. },
  137. isElement: function(object) {
  138. return object && object.nodeType == 1;
  139. },
  140. isArray: function(object) {
  141. return object && object.constructor === Array;
  142. },
  143. isHash: function(object) {
  144. return object instanceof Hash;
  145. },
  146. isFunction: function(object) {
  147. return typeof object == "function";
  148. },
  149. isString: function(object) {
  150. return typeof object == "string";
  151. },
  152. isNumber: function(object) {
  153. return typeof object == "number";
  154. },
  155. isUndefined: function(object) {
  156. return typeof object == "undefined";
  157. }
  158. });
  159. Object.extend(Function.prototype, {
  160. argumentNames: function() {
  161. var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
  162. return names.length == 1 && !names[0] ? [] : names;
  163. },
  164. bind: function() {
  165. if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
  166. var __method = this, args = $A(arguments), object = args.shift();
  167. return function() {
  168. return __method.apply(object, args.concat($A(arguments)));
  169. }
  170. },
  171. bindAsEventListener: function() {
  172. var __method = this, args = $A(arguments), object = args.shift();
  173. return function(event) {
  174. return __method.apply(object, [event || window.event].concat(args));
  175. }
  176. },
  177. curry: function() {
  178. if (!arguments.length) return this;
  179. var __method = this, args = $A(arguments);
  180. return function() {
  181. return __method.apply(this, args.concat($A(arguments)));
  182. }
  183. },
  184. delay: function() {
  185. var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
  186. return window.setTimeout(function() {
  187. return __method.apply(__method, args);
  188. }, timeout);
  189. },
  190. wrap: function(wrapper) {
  191. var __method = this;
  192. return function() {
  193. return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
  194. }
  195. },
  196. methodize: function() {
  197. if (this._methodized) return this._methodized;
  198. var __method = this;
  199. return this._methodized = function() {
  200. return __method.apply(null, [this].concat($A(arguments)));
  201. };
  202. }
  203. });
  204. Function.prototype.defer = Function.prototype.delay.curry(0.01);
  205. Date.prototype.toJSON = function() {
  206. return '"' + this.getUTCFullYear() + '-' +
  207. (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
  208. this.getUTCDate().toPaddedString(2) + 'T' +
  209. this.getUTCHours().toPaddedString(2) + ':' +
  210. this.getUTCMinutes().toPaddedString(2) + ':' +
  211. this.getUTCSeconds().toPaddedString(2) + 'Z"';
  212. };
  213. var Try = {
  214. these: function() {
  215. var returnValue;
  216. for (var i = 0, length = arguments.length; i < length; i++) {
  217. var lambda = arguments[i];
  218. try {
  219. returnValue = lambda();
  220. break;
  221. } catch (e) { }
  222. }
  223. return returnValue;
  224. }
  225. };
  226. RegExp.prototype.match = RegExp.prototype.test;
  227. RegExp.escape = function(str) {
  228. return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  229. };
  230. /*--------------------------------------------------------------------------*/
  231. var PeriodicalExecuter = Class.create({
  232. initialize: function(callback, frequency) {
  233. this.callback = callback;
  234. this.frequency = frequency;
  235. this.currentlyExecuting = false;
  236. this.registerCallback();
  237. },
  238. registerCallback: function() {
  239. this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  240. },
  241. execute: function() {
  242. this.callback(this);
  243. },
  244. stop: function() {
  245. if (!this.timer) return;
  246. clearInterval(this.timer);
  247. this.timer = null;
  248. },
  249. onTimerEvent: function() {
  250. if (!this.currentlyExecuting) {
  251. try {
  252. this.currentlyExecuting = true;
  253. this.execute();
  254. } finally {
  255. this.currentlyExecuting = false;
  256. }
  257. }
  258. }
  259. });
  260. Object.extend(String, {
  261. interpret: function(value) {
  262. return value == null ? '' : String(value);
  263. },
  264. specialChar: {
  265. '\b': '\\b',
  266. '\t': '\\t',
  267. '\n': '\\n',
  268. '\f': '\\f',
  269. '\r': '\\r',
  270. '\\': '\\\\'
  271. }
  272. });
  273. Object.extend(String.prototype, {
  274. gsub: function(pattern, replacement) {
  275. var result = '', source = this, match;
  276. replacement = arguments.callee.prepareReplacement(replacement);
  277. while (source.length > 0) {
  278. if (match = source.match(pattern)) {
  279. result += source.slice(0, match.index);
  280. result += String.interpret(replacement(match));
  281. source = source.slice(match.index + match[0].length);
  282. } else {
  283. result += source, source = '';
  284. }
  285. }
  286. return result;
  287. },
  288. sub: function(pattern, replacement, count) {
  289. replacement = this.gsub.prepareReplacement(replacement);
  290. count = Object.isUndefined(count) ? 1 : count;
  291. return this.gsub(pattern, function(match) {
  292. if (--count < 0) return match[0];
  293. return replacement(match);
  294. });
  295. },
  296. scan: function(pattern, iterator) {
  297. this.gsub(pattern, iterator);
  298. return String(this);
  299. },
  300. truncate: function(length, truncation) {
  301. length = length || 30;
  302. truncation = Object.isUndefined(truncation) ? '...' : truncation;
  303. return this.length > length ?
  304. this.slice(0, length - truncation.length) + truncation : String(this);
  305. },
  306. strip: function() {
  307. return this.replace(/^\s+/, '').replace(/\s+$/, '');
  308. },
  309. stripTags: function() {
  310. return this.replace(/<\/?[^>]+>/gi, '');
  311. },
  312. stripScripts: function() {
  313. return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  314. },
  315. extractScripts: function() {
  316. var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
  317. var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
  318. return (this.match(matchAll) || []).map(function(scriptTag) {
  319. return (scriptTag.match(matchOne) || ['', ''])[1];
  320. });
  321. },
  322. evalScripts: function() {
  323. return this.extractScripts().map(function(script) { return eval(script) });
  324. },
  325. escapeHTML: function() {
  326. var self = arguments.callee;
  327. self.text.data = this;
  328. return self.div.innerHTML;
  329. },
  330. unescapeHTML: function() {
  331. var div = new Element('div');
  332. div.innerHTML = this.stripTags();
  333. return div.childNodes[0] ? (div.childNodes.length > 1 ?
  334. $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
  335. div.childNodes[0].nodeValue) : '';
  336. },
  337. toQueryParams: function(separator) {
  338. var match = this.strip().match(/([^?#]*)(#.*)?$/);
  339. if (!match) return { };
  340. return match[1].split(separator || '&').inject({ }, function(hash, pair) {
  341. if ((pair = pair.split('='))[0]) {
  342. var key = decodeURIComponent(pair.shift());
  343. var value = pair.length > 1 ? pair.join('=') : pair[0];
  344. if (value != undefined) value = decodeURIComponent(value);
  345. if (key in hash) {
  346. if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
  347. hash[key].push(value);
  348. }
  349. else hash[key] = value;
  350. }
  351. return hash;
  352. });
  353. },
  354. toArray: function() {
  355. return this.split('');
  356. },
  357. succ: function() {
  358. return this.slice(0, this.length - 1) +
  359. String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  360. },
  361. times: function(count) {
  362. return count < 1 ? '' : new Array(count + 1).join(this);
  363. },
  364. camelize: function() {
  365. var parts = this.split('-'), len = parts.length;
  366. if (len == 1) return parts[0];
  367. var camelized = this.charAt(0) == '-'
  368. ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
  369. : parts[0];
  370. for (var i = 1; i < len; i++)
  371. camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
  372. return camelized;
  373. },
  374. capitalize: function() {
  375. return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  376. },
  377. underscore: function() {
  378. return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  379. },
  380. dasherize: function() {
  381. return this.gsub(/_/,'-');
  382. },
  383. inspect: function(useDoubleQuotes) {
  384. var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
  385. var character = String.specialChar[match[0]];
  386. return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
  387. });
  388. if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
  389. return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  390. },
  391. toJSON: function() {
  392. return this.inspect(true);
  393. },
  394. unfilterJSON: function(filter) {
  395. return this.sub(filter || Prototype.JSONFilter, '#{1}');
  396. },
  397. isJSON: function() {
  398. var str = this;
  399. if (str.blank()) return false;
  400. str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
  401. return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  402. },
  403. evalJSON: function(sanitize) {
  404. var json = this.unfilterJSON();
  405. try {
  406. if (!sanitize || json.isJSON()) return eval('(' + json + ')');
  407. } catch (e) { }
  408. throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  409. },
  410. include: function(pattern) {
  411. return this.indexOf(pattern) > -1;
  412. },
  413. startsWith: function(pattern) {
  414. return this.indexOf(pattern) === 0;
  415. },
  416. endsWith: function(pattern) {
  417. var d = this.length - pattern.length;
  418. return d >= 0 && this.lastIndexOf(pattern) === d;
  419. },
  420. empty: function() {
  421. return this == '';
  422. },
  423. blank: function() {
  424. return /^\s*$/.test(this);
  425. },
  426. interpolate: function(object, pattern) {
  427. return new Template(this, pattern).evaluate(object);
  428. }
  429. });
  430. if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
  431. escapeHTML: function() {
  432. return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  433. },
  434. unescapeHTML: function() {
  435. return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
  436. }
  437. });
  438. String.prototype.gsub.prepareReplacement = function(replacement) {
  439. if (Object.isFunction(replacement)) return replacement;
  440. var template = new Template(replacement);
  441. return function(match) { return template.evaluate(match) };
  442. };
  443. String.prototype.parseQuery = String.prototype.toQueryParams;
  444. Object.extend(String.prototype.escapeHTML, {
  445. div: document.createElement('div'),
  446. text: document.createTextNode('')
  447. });
  448. with (String.prototype.escapeHTML) div.appendChild(text);
  449. var Template = Class.create({
  450. initialize: function(template, pattern) {
  451. this.template = template.toString();
  452. this.pattern = pattern || Template.Pattern;
  453. },
  454. evaluate: function(object) {
  455. if (Object.isFunction(object.toTemplateReplacements))
  456. object = object.toTemplateReplacements();
  457. return this.template.gsub(this.pattern, function(match) {
  458. if (object == null) return '';
  459. var before = match[1] || '';
  460. if (before == '\\') return match[2];
  461. var ctx = object, expr = match[3];
  462. var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
  463. match = pattern.exec(expr);
  464. if (match == null) return before;
  465. while (match != null) {
  466. var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
  467. ctx = ctx[comp];
  468. if (null == ctx || '' == match[3]) break;
  469. expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
  470. match = pattern.exec(expr);
  471. }
  472. return before + String.interpret(ctx);
  473. }.bind(this));
  474. }
  475. });
  476. Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
  477. var $break = { };
  478. var Enumerable = {
  479. each: function(iterator, context) {
  480. var index = 0;
  481. iterator = iterator.bind(context);
  482. try {
  483. this._each(function(value) {
  484. iterator(value, index++);
  485. });
  486. } catch (e) {
  487. if (e != $break) throw e;
  488. }
  489. return this;
  490. },
  491. eachSlice: function(number, iterator, context) {
  492. iterator = iterator ? iterator.bind(context) : Prototype.K;
  493. var index = -number, slices = [], array = this.toArray();
  494. while ((index += number) < array.length)
  495. slices.push(array.slice(index, index+number));
  496. return slices.collect(iterator, context);
  497. },
  498. all: function(iterator, context) {
  499. iterator = iterator ? iterator.bind(context) : Prototype.K;
  500. var result = true;
  501. this.each(function(value, index) {
  502. result = result && !!iterator(value, index);
  503. if (!result) throw $break;
  504. });
  505. return result;
  506. },
  507. any: function(iterator, context) {
  508. iterator = iterator ? iterator.bind(context) : Prototype.K;
  509. var result = false;
  510. this.each(function(value, index) {
  511. if (result = !!iterator(value, index))
  512. throw $break;
  513. });
  514. return result;
  515. },
  516. collect: function(iterator, context) {
  517. iterator = iterator ? iterator.bind(context) : Prototype.K;
  518. var results = [];
  519. this.each(function(value, index) {
  520. results.push(iterator(value, index));
  521. });
  522. return results;
  523. },
  524. detect: function(iterator, context) {
  525. iterator = iterator.bind(context);
  526. var result;
  527. this.each(function(value, index) {
  528. if (iterator(value, index)) {
  529. result = value;
  530. throw $break;
  531. }
  532. });
  533. return result;
  534. },
  535. findAll: function(iterator, context) {
  536. iterator = iterator.bind(context);
  537. var results = [];
  538. this.each(function(value, index) {
  539. if (iterator(value, index))
  540. results.push(value);
  541. });
  542. return results;
  543. },
  544. grep: function(filter, iterator, context) {
  545. iterator = iterator ? iterator.bind(context) : Prototype.K;
  546. var results = [];
  547. if (Object.isString(filter))
  548. filter = new RegExp(filter);
  549. this.each(function(value, index) {
  550. if (filter.match(value))
  551. results.push(iterator(value, index));
  552. });
  553. return results;
  554. },
  555. include: function(object) {
  556. if (Object.isFunction(this.indexOf))
  557. if (this.indexOf(object) != -1) return true;
  558. var found = false;
  559. this.each(function(value) {
  560. if (value == object) {
  561. found = true;
  562. throw $break;
  563. }
  564. });
  565. return found;
  566. },
  567. inGroupsOf: function(number, fillWith) {
  568. fillWith = Object.isUndefined(fillWith) ? null : fillWith;
  569. return this.eachSlice(number, function(slice) {
  570. while(slice.length < number) slice.push(fillWith);
  571. return slice;
  572. });
  573. },
  574. inject: function(memo, iterator, context) {
  575. iterator = iterator.bind(context);
  576. this.each(function(value, index) {
  577. memo = iterator(memo, value, index);
  578. });
  579. return memo;
  580. },
  581. invoke: function(method) {
  582. var args = $A(arguments).slice(1);
  583. return this.map(function(value) {
  584. return value[method].apply(value, args);
  585. });
  586. },
  587. max: function(iterator, context) {
  588. iterator = iterator ? iterator.bind(context) : Prototype.K;
  589. var result;
  590. this.each(function(value, index) {
  591. value = iterator(value, index);
  592. if (result == null || value >= result)
  593. result = value;
  594. });
  595. return result;
  596. },
  597. min: function(iterator, context) {
  598. iterator = iterator ? iterator.bind(context) : Prototype.K;
  599. var result;
  600. this.each(function(value, index) {
  601. value = iterator(value, index);
  602. if (result == null || value < result)
  603. result = value;
  604. });
  605. return result;
  606. },
  607. partition: function(iterator, context) {
  608. iterator = iterator ? iterator.bind(context) : Prototype.K;
  609. var trues = [], falses = [];
  610. this.each(function(value, index) {
  611. (iterator(value, index) ?
  612. trues : falses).push(value);
  613. });
  614. return [trues, falses];
  615. },
  616. pluck: function(property) {
  617. var results = [];
  618. this.each(function(value) {
  619. results.push(value[property]);
  620. });
  621. return results;
  622. },
  623. reject: function(iterator, context) {
  624. iterator = iterator.bind(context);
  625. var results = [];
  626. this.each(function(value, index) {
  627. if (!iterator(value, index))
  628. results.push(value);
  629. });
  630. return results;
  631. },
  632. sortBy: function(iterator, context) {
  633. iterator = iterator.bind(context);
  634. return this.map(function(value, index) {
  635. return {value: value, criteria: iterator(value, index)};
  636. }).sort(function(left, right) {
  637. var a = left.criteria, b = right.criteria;
  638. return a < b ? -1 : a > b ? 1 : 0;
  639. }).pluck('value');
  640. },
  641. toArray: function() {
  642. return this.map();
  643. },
  644. zip: function() {
  645. var iterator = Prototype.K, args = $A(arguments);
  646. if (Object.isFunction(args.last()))
  647. iterator = args.pop();
  648. var collections = [this].concat(args).map($A);
  649. return this.map(function(value, index) {
  650. return iterator(collections.pluck(index));
  651. });
  652. },
  653. size: function() {
  654. return this.toArray().length;
  655. },
  656. inspect: function() {
  657. return '#<Enumerable:' + this.toArray().inspect() + '>';
  658. }
  659. };
  660. Object.extend(Enumerable, {
  661. map: Enumerable.collect,
  662. find: Enumerable.detect,
  663. select: Enumerable.findAll,
  664. filter: Enumerable.findAll,
  665. member: Enumerable.include,
  666. entries: Enumerable.toArray,
  667. every: Enumerable.all,
  668. some: Enumerable.any
  669. });
  670. function $A(iterable) {
  671. if (!iterable) return [];
  672. if (iterable.toArray) return iterable.toArray();
  673. var length = iterable.length || 0, results = new Array(length);
  674. while (length--) results[length] = iterable[length];
  675. return results;
  676. }
  677. if (Prototype.Browser.WebKit) {
  678. function $A(iterable) {
  679. if (!iterable) return [];
  680. if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
  681. iterable.toArray) return iterable.toArray();
  682. var length = iterable.length || 0, results = new Array(length);
  683. while (length--) results[length] = iterable[length];
  684. return results;
  685. }
  686. }
  687. Array.from = $A;
  688. Object.extend(Array.prototype, Enumerable);
  689. if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
  690. Object.extend(Array.prototype, {
  691. _each: function(iterator) {
  692. for (var i = 0, length = this.length; i < length; i++)
  693. iterator(this[i]);
  694. },
  695. clear: function() {
  696. this.length = 0;
  697. return this;
  698. },
  699. first: function() {
  700. return this[0];
  701. },
  702. last: function() {
  703. return this[this.length - 1];
  704. },
  705. compact: function() {
  706. return this.select(function(value) {
  707. return value != null;
  708. });
  709. },
  710. flatten: function() {
  711. return this.inject([], function(array, value) {
  712. return array.concat(Object.isArray(value) ?
  713. value.flatten() : [value]);
  714. });
  715. },
  716. without: function() {
  717. var values = $A(arguments);
  718. return this.select(function(value) {
  719. return !values.include(value);
  720. });
  721. },
  722. reverse: function(inline) {
  723. return (inline !== false ? this : this.toArray())._reverse();
  724. },
  725. reduce: function() {
  726. return this.length > 1 ? this : this[0];
  727. },
  728. uniq: function(sorted) {
  729. return this.inject([], function(array, value, index) {
  730. if (0 == index || (sorted ? array.last() != value : !array.include(value)))
  731. array.push(value);
  732. return array;
  733. });
  734. },
  735. intersect: function(array) {
  736. return this.uniq().findAll(function(item) {
  737. return array.detect(function(value) { return item === value });
  738. });
  739. },
  740. clone: function() {
  741. return [].concat(this);
  742. },
  743. size: function() {
  744. return this.length;
  745. },
  746. inspect: function() {
  747. return '[' + this.map(Object.inspect).join(', ') + ']';
  748. },
  749. toJSON: function() {
  750. var results = [];
  751. this.each(function(object) {
  752. var value = Object.toJSON(object);
  753. if (!Object.isUndefined(value)) results.push(value);
  754. });
  755. return '[' + results.join(', ') + ']';
  756. }
  757. });
  758. // use native browser JS 1.6 implementation if available
  759. if (Object.isFunction(Array.prototype.forEach))
  760. Array.prototype._each = Array.prototype.forEach;
  761. if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
  762. i || (i = 0);
  763. var length = this.length;
  764. if (i < 0) i = length + i;
  765. for (; i < length; i++)
  766. if (this[i] === item) return i;
  767. return -1;
  768. };
  769. if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
  770. i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
  771. var n = this.slice(0, i).reverse().indexOf(item);
  772. return (n < 0) ? n : i - n - 1;
  773. };
  774. Array.prototype.toArray = Array.prototype.clone;
  775. function $w(string) {
  776. if (!Object.isString(string)) return [];
  777. string = string.strip();
  778. return string ? string.split(/\s+/) : [];
  779. }
  780. if (Prototype.Browser.Opera){
  781. Array.prototype.concat = function() {
  782. var array = [];
  783. for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
  784. for (var i = 0, length = arguments.length; i < length; i++) {
  785. if (Object.isArray(arguments[i])) {
  786. for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
  787. array.push(arguments[i][j]);
  788. } else {
  789. array.push(arguments[i]);
  790. }
  791. }
  792. return array;
  793. };
  794. }
  795. Object.extend(Number.prototype, {
  796. toColorPart: function() {
  797. return this.toPaddedString(2, 16);
  798. },
  799. succ: function() {
  800. return this + 1;
  801. },
  802. times: function(iterator) {
  803. $R(0, this, true).each(iterator);
  804. return this;
  805. },
  806. toPaddedString: function(length, radix) {
  807. var string = this.toString(radix || 10);
  808. return '0'.times(length - string.length) + string;
  809. },
  810. toJSON: function() {
  811. return isFinite(this) ? this.toString() : 'null';
  812. }
  813. });
  814. $w('abs round ceil floor').each(function(method){
  815. Number.prototype[method] = Math[method].methodize();
  816. });
  817. function $H(object) {
  818. return new Hash(object);
  819. };
  820. var Hash = Class.create(Enumerable, (function() {
  821. function toQueryPair(key, value) {
  822. if (Object.isUndefined(value)) return key;
  823. return key + '=' + encodeURIComponent(String.interpret(value));
  824. }
  825. return {
  826. initialize: function(object) {
  827. this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
  828. },
  829. _each: function(iterator) {
  830. for (var key in this._object) {
  831. var value = this._object[key], pair = [key, value];
  832. pair.key = key;
  833. pair.value = value;
  834. iterator(pair);
  835. }
  836. },
  837. set: function(key, value) {
  838. return this._object[key] = value;
  839. },
  840. get: function(key) {
  841. return this._object[key];
  842. },
  843. unset: function(key) {
  844. var value = this._object[key];
  845. delete this._object[key];
  846. return value;
  847. },
  848. toObject: function() {
  849. return Object.clone(this._object);
  850. },
  851. keys: function() {
  852. return this.pluck('key');
  853. },
  854. values: function() {
  855. return this.pluck('value');
  856. },
  857. index: function(value) {
  858. var match = this.detect(function(pair) {
  859. return pair.value === value;
  860. });
  861. return match && match.key;
  862. },
  863. merge: function(object) {
  864. return this.clone().update(object);
  865. },
  866. update: function(object) {
  867. return new Hash(object).inject(this, function(result, pair) {
  868. result.set(pair.key, pair.value);
  869. return result;
  870. });
  871. },
  872. toQueryString: function() {
  873. return this.map(function(pair) {
  874. var key = encodeURIComponent(pair.key), values = pair.value;
  875. if (values && typeof values == 'object') {
  876. if (Object.isArray(values))
  877. return values.map(toQueryPair.curry(key)).join('&');
  878. }
  879. return toQueryPair(key, values);
  880. }).join('&');
  881. },
  882. inspect: function() {
  883. return '#<Hash:{' + this.map(function(pair) {
  884. return pair.map(Object.inspect).join(': ');
  885. }).join(', ') + '}>';
  886. },
  887. toJSON: function() {
  888. return Object.toJSON(this.toObject());
  889. },
  890. clone: function() {
  891. return new Hash(this);
  892. }
  893. }
  894. })());
  895. Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
  896. Hash.from = $H;
  897. var ObjectRange = Class.create(Enumerable, {
  898. initialize: function(start, end, exclusive) {
  899. this.start = start;
  900. this.end = end;
  901. this.exclusive = exclusive;
  902. },
  903. _each: function(iterator) {
  904. var value = this.start;
  905. while (this.include(value)) {
  906. iterator(value);
  907. value = value.succ();
  908. }
  909. },
  910. include: function(value) {
  911. if (value < this.start)
  912. return false;
  913. if (this.exclusive)
  914. return value < this.end;
  915. return value <= this.end;
  916. }
  917. });
  918. var $R = function(start, end, exclusive) {
  919. return new ObjectRange(start, end, exclusive);
  920. };
  921. var Ajax = {
  922. getTransport: function() {
  923. return Try.these(
  924. function() {return new XMLHttpRequest()},
  925. function() {return new ActiveXObject('Msxml2.XMLHTTP')},
  926. function() {return new ActiveXObject('Microsoft.XMLHTTP')}
  927. ) || false;
  928. },
  929. activeRequestCount: 0
  930. };
  931. Ajax.Responders = {
  932. responders: [],
  933. _each: function(iterator) {
  934. this.responders._each(iterator);
  935. },
  936. register: function(responder) {
  937. if (!this.include(responder))
  938. this.responders.push(responder);
  939. },
  940. unregister: function(responder) {
  941. this.responders = this.responders.without(responder);
  942. },
  943. dispatch: function(callback, request, transport, json) {
  944. this.each(function(responder) {
  945. if (Object.isFunction(responder[callback])) {
  946. try {
  947. responder[callback].apply(responder, [request, transport, json]);
  948. } catch (e) { }
  949. }
  950. });
  951. }
  952. };
  953. Object.extend(Ajax.Responders, Enumerable);
  954. Ajax.Responders.register({
  955. onCreate: function() { Ajax.activeRequestCount++ },
  956. onComplete: function() { Ajax.activeRequestCount-- }
  957. });
  958. Ajax.Base = Class.create({
  959. initialize: function(options) {
  960. this.options = {
  961. method: 'post',
  962. asynchronous: true,
  963. contentType: 'application/x-www-form-urlencoded',
  964. encoding: 'UTF-8',
  965. parameters: '',
  966. evalJSON: true,
  967. evalJS: true
  968. };
  969. Object.extend(this.options, options || { });
  970. this.options.method = this.options.method.toLowerCase();
  971. if (Object.isString(this.options.parameters))
  972. this.options.parameters = this.options.parameters.toQueryParams();
  973. else if (Object.isHash(this.options.parameters))
  974. this.options.parameters = this.options.parameters.toObject();
  975. }
  976. });
  977. Ajax.Request = Class.create(Ajax.Base, {
  978. _complete: false,
  979. initialize: function($super, url, options) {
  980. $super(options);
  981. this.transport = Ajax.getTransport();
  982. this.request(url);
  983. },
  984. request: function(url) {
  985. this.url = url;
  986. this.method = this.options.method;
  987. var params = Object.clone(this.options.parameters);
  988. if (!['get', 'post'].include(this.method)) {
  989. // simulate other verbs over post
  990. params['_method'] = this.method;
  991. this.method = 'post';
  992. }
  993. this.parameters = params;
  994. if (params = Object.toQueryString(params)) {
  995. // when GET, append parameters to URL
  996. if (this.method == 'get')
  997. this.url += (this.url.include('?') ? '&' : '?') + params;
  998. else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
  999. params += '&_=';
  1000. }
  1001. try {
  1002. var response = new Ajax.Response(this);
  1003. if (this.options.onCreate) this.options.onCreate(response);
  1004. Ajax.Responders.dispatch('onCreate', this, response);
  1005. this.transport.open(this.method.toUpperCase(), this.url,
  1006. this.options.asynchronous);
  1007. if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
  1008. this.transport.onreadystatechange = this.onStateChange.bind(this);
  1009. this.setRequestHeaders();
  1010. this.body = this.method == 'post' ? (this.options.postBody || params) : null;
  1011. this.transport.send(this.body);
  1012. /* Force Firefox to handle ready state 4 for synchronous requests */
  1013. if (!this.options.asynchronous && this.transport.overrideMimeType)
  1014. this.onStateChange();
  1015. }
  1016. catch (e) {
  1017. this.dispatchException(e);
  1018. }
  1019. },
  1020. onStateChange: function() {
  1021. var readyState = this.transport.readyState;
  1022. if (readyState > 1 && !((readyState == 4) && this._complete))
  1023. this.respondToReadyState(this.transport.readyState);
  1024. },
  1025. setRequestHeaders: function() {
  1026. var headers = {
  1027. 'X-Requested-With': 'XMLHttpRequest',
  1028. 'X-Prototype-Version': Prototype.Version,
  1029. 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  1030. };
  1031. if (this.method == 'post') {
  1032. headers['Content-type'] = this.options.contentType +
  1033. (this.options.encoding ? '; charset=' + this.options.encoding : '');
  1034. /* Force "Connection: close" for older Mozilla browsers to work
  1035. * around a bug where XMLHttpRequest sends an incorrect
  1036. * Content-length header. See Mozilla Bugzilla #246651.
  1037. */
  1038. if (this.transport.overrideMimeType &&
  1039. (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
  1040. headers['Connection'] = 'close';
  1041. }
  1042. // user-defined headers
  1043. if (typeof this.options.requestHeaders == 'object') {
  1044. var extras = this.options.requestHeaders;
  1045. if (Object.isFunction(extras.push))
  1046. for (var i = 0, length = extras.length; i < length; i += 2)
  1047. headers[extras[i]] = extras[i+1];
  1048. else
  1049. $H(extras).each(function(pair) { headers[pair.key] = pair.value });
  1050. }
  1051. for (var name in headers)
  1052. this.transport.setRequestHeader(name, headers[name]);
  1053. },
  1054. success: function() {
  1055. var status = this.getStatus();
  1056. return !status || (status >= 200 && status < 300);
  1057. },
  1058. getStatus: function() {
  1059. try {
  1060. return this.transport.status || 0;
  1061. } catch (e) { return 0 }
  1062. },
  1063. respondToReadyState: function(readyState) {
  1064. var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
  1065. if (state == 'Complete') {
  1066. try {
  1067. this._complete = true;
  1068. (this.options['on' + response.status]
  1069. || this.options['on' + (this.success() ? 'Success' : 'Failure')]
  1070. || Prototype.emptyFunction)(response, response.headerJSON);
  1071. } catch (e) {
  1072. this.dispatchException(e);
  1073. }
  1074. var contentType = response.getHeader('Content-type');
  1075. if (this.options.evalJS == 'force'
  1076. || (this.options.evalJS && contentType
  1077. && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
  1078. this.evalResponse();
  1079. }
  1080. try {
  1081. (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
  1082. Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
  1083. } catch (e) {
  1084. this.dispatchException(e);
  1085. }
  1086. if (state == 'Complete') {
  1087. // avoid memory leak in MSIE: clean up
  1088. this.transport.onreadystatechange = Prototype.emptyFunction;
  1089. }
  1090. },
  1091. getHeader: function(name) {
  1092. try {
  1093. return this.transport.getResponseHeader(name) || null;
  1094. } catch (e) { return null }
  1095. },
  1096. evalResponse: function() {
  1097. try {
  1098. return eval((this.transport.responseText || '').unfilterJSON());
  1099. } catch (e) {
  1100. this.dispatchException(e);
  1101. }
  1102. },
  1103. dispatchException: function(exception) {
  1104. (this.options.onException || Prototype.emptyFunction)(this, exception);
  1105. Ajax.Responders.dispatch('onException', this, exception);
  1106. }
  1107. });
  1108. Ajax.Request.Events =
  1109. ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
  1110. Ajax.Response = Class.create({
  1111. initialize: function(request){
  1112. this.request = request;
  1113. var transport = this.transport = request.transport,
  1114. readyState = this.readyState = transport.readyState;
  1115. if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
  1116. this.status = this.getStatus();
  1117. this.statusText = this.getStatusText();
  1118. this.responseText = String.interpret(transport.responseText);
  1119. this.headerJSON = this._getHeaderJSON();
  1120. }
  1121. if(readyState == 4) {
  1122. var xml = transport.responseXML;
  1123. this.responseXML = Object.isUndefined(xml) ? null : xml;
  1124. this.responseJSON = this._getResponseJSON();
  1125. }
  1126. },
  1127. status: 0,
  1128. statusText: '',
  1129. getStatus: Ajax.Request.prototype.getStatus,
  1130. getStatusText: function() {
  1131. try {
  1132. return this.transport.statusText || '';
  1133. } catch (e) { return '' }
  1134. },
  1135. getHeader: Ajax.Request.prototype.getHeader,
  1136. getAllHeaders: function() {
  1137. try {
  1138. return this.getAllResponseHeaders();
  1139. } catch (e) { return null }
  1140. },
  1141. getResponseHeader: function(name) {
  1142. return this.transport.getResponseHeader(name);
  1143. },
  1144. getAllResponseHeaders: function() {
  1145. return this.transport.getAllResponseHeaders();
  1146. },
  1147. _getHeaderJSON: function() {
  1148. var json = this.getHeader('X-JSON');
  1149. if (!json) return null;
  1150. json = decodeURIComponent(escape(json));
  1151. try {
  1152. return json.evalJSON(this.request.options.sanitizeJSON);
  1153. } catch (e) {
  1154. this.request.dispatchException(e);
  1155. }
  1156. },
  1157. _getResponseJSON: function() {
  1158. var options = this.request.options;
  1159. if (!options.evalJSON || (options.evalJSON != 'force' &&
  1160. !(this.getHeader('Content-type') || '').include('application/json')) ||
  1161. this.responseText.blank())
  1162. return null;
  1163. try {
  1164. return this.responseText.evalJSON(options.sanitizeJSON);
  1165. } catch (e) {
  1166. this.request.dispatchException(e);
  1167. }
  1168. }
  1169. });
  1170. Ajax.Updater = Class.create(Ajax.Request, {
  1171. initialize: function($super, container, url, options) {
  1172. this.container = {
  1173. success: (container.success || container),
  1174. failure: (container.failure || (container.success ? null : container))
  1175. };
  1176. options = Object.clone(options);
  1177. var onComplete = options.onComplete;
  1178. options.onComplete = (function(response, json) {
  1179. this.updateContent(response.responseText);
  1180. if (Object.isFunction(onComplete)) onComplete(response, json);
  1181. }).bind(this);
  1182. $super(url, options);
  1183. },
  1184. updateContent: function(responseText) {
  1185. var receiver = this.container[this.success() ? 'success' : 'failure'],
  1186. options = this.options;
  1187. if (!options.evalScripts) responseText = responseText.stripScripts();
  1188. if (receiver = $(receiver)) {
  1189. if (options.insertion) {
  1190. if (Object.isString(options.insertion)) {
  1191. var insertion = { }; insertion[options.insertion] = responseText;
  1192. receiver.insert(insertion);
  1193. }
  1194. else options.insertion(receiver, responseText);
  1195. }
  1196. else receiver.update(responseText);
  1197. }
  1198. }
  1199. });
  1200. Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
  1201. initialize: function($super, container, url, options) {
  1202. $super(options);
  1203. this.onComplete = this.options.onComplete;
  1204. this.frequency = (this.options.frequency || 2);
  1205. this.decay = (this.options.decay || 1);
  1206. this.updater = { };
  1207. this.container = container;
  1208. this.url = url;
  1209. this.start();
  1210. },
  1211. start: function() {
  1212. this.options.onComplete = this.updateComplete.bind(this);
  1213. this.onTimerEvent();
  1214. },
  1215. stop: function() {
  1216. this.updater.options.onComplete = undefined;
  1217. clearTimeout(this.timer);
  1218. (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  1219. },
  1220. updateComplete: function(response) {
  1221. if (this.options.decay) {
  1222. this.decay = (response.responseText == this.lastText ?
  1223. this.decay * this.options.decay : 1);
  1224. this.lastText = response.responseText;
  1225. }
  1226. this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
  1227. },
  1228. onTimerEvent: function() {
  1229. this.updater = new Ajax.Updater(this.container, this.url, this.options);
  1230. }
  1231. });
  1232. function $(element) {
  1233. if (arguments.length > 1) {
  1234. for (var i = 0, elements = [], length = arguments.length; i < length; i++)
  1235. elements.push($(arguments[i]));
  1236. return elements;
  1237. }
  1238. if (Object.isString(element))
  1239. element = document.getElementById(element);
  1240. return Element.extend(element);
  1241. }
  1242. if (Prototype.BrowserFeatures.XPath) {
  1243. document._getElementsByXPath = function(expression, parentElement) {
  1244. var results = [];
  1245. var query = document.evaluate(expression, $(parentElement) || document,
  1246. null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  1247. for (var i = 0, length = query.snapshotLength; i < length; i++)
  1248. results.push(Element.extend(query.snapshotItem(i)));
  1249. return results;
  1250. };
  1251. }
  1252. /*--------------------------------------------------------------------------*/
  1253. if (!window.Node) var Node = { };
  1254. if (!Node.ELEMENT_NODE) {
  1255. // DOM level 2 ECMAScript Language Binding
  1256. Object.extend(Node, {
  1257. ELEMENT_NODE: 1,
  1258. ATTRIBUTE_NODE: 2,
  1259. TEXT_NODE: 3,
  1260. CDATA_SECTION_NODE: 4,
  1261. ENTITY_REFERENCE_NODE: 5,
  1262. ENTITY_NODE: 6,
  1263. PROCESSING_INSTRUCTION_NODE: 7,
  1264. COMMENT_NODE: 8,
  1265. DOCUMENT_NODE: 9,
  1266. DOCUMENT_TYPE_NODE: 10,
  1267. DOCUMENT_FRAGMENT_NODE: 11,
  1268. NOTATION_NODE: 12
  1269. });
  1270. }
  1271. (function() {
  1272. var element = this.Element;
  1273. this.Element = function(tagName, attributes) {
  1274. attributes = attributes || { };
  1275. tagName = tagName.toLowerCase();
  1276. var cache = Element.cache;
  1277. if (Prototype.Browser.IE && attributes.name) {
  1278. tagName = '<' + tagName + ' name="' + attributes.name + '">';
  1279. delete attributes.name;
  1280. return Element.writeAttribute(document.createElement(tagName), attributes);
  1281. }
  1282. if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
  1283. return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
  1284. };
  1285. Object.extend(this.Element, element || { });
  1286. }).call(window);
  1287. Element.cache = { };
  1288. Element.Methods = {
  1289. visible: function(element) {
  1290. return $(element).style.display != 'none';
  1291. },
  1292. toggle: function(element) {
  1293. element = $(element);
  1294. Element[Element.visible(element) ? 'hide' : 'show'](element);
  1295. return element;
  1296. },
  1297. hide: function(element) {
  1298. $(element).style.display = 'none';
  1299. return element;
  1300. },
  1301. show: function(element) {
  1302. $(element).style.display = '';
  1303. return element;
  1304. },
  1305. remove: function(element) {
  1306. element = $(element);
  1307. element.parentNode.removeChild(element);
  1308. return element;
  1309. },
  1310. update: function(element, content) {
  1311. element = $(element);
  1312. if (content && content.toElement) content = content.toElement();
  1313. if (Object.isElement(content)) return element.update().insert(content);
  1314. content = Object.toHTML(content);
  1315. element.innerHTML = content.stripScripts();
  1316. content.evalScripts.bind(content).defer();
  1317. return element;
  1318. },
  1319. replace: function(element, content) {
  1320. element = $(element);
  1321. if (content && content.toElement) content = content.toElement();
  1322. else if (!Object.isElement(content)) {
  1323. content = Object.toHTML(content);
  1324. var range = element.ownerDocument.createRange();
  1325. range.selectNode(element);
  1326. content.evalScripts.bind(content).defer();
  1327. content = range.createContextualFragment(content.stripScripts());
  1328. }
  1329. element.parentNode.replaceChild(content, element);
  1330. return element;
  1331. },
  1332. insert: function(element, insertions) {
  1333. element = $(element);
  1334. if (Object.isString(insertions) || Object.isNumber(insertions) ||
  1335. Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
  1336. insertions = {bottom:insertions};
  1337. var content, insert, tagName, childNodes;
  1338. for (position in insertions) {
  1339. content = insertions[position];
  1340. position = position.toLowerCase();
  1341. insert = Element._insertionTranslations[position];
  1342. if (content && content.toElement) content = content.toElement();
  1343. if (Object.isElement(content)) {
  1344. insert(element, content);
  1345. continue;
  1346. }
  1347. content = Object.toHTML(content);
  1348. tagName = ((position == 'before' || position == 'after')
  1349. ? element.parentNode : element).tagName.toUpperCase();
  1350. childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
  1351. if (position == 'top' || position == 'after') childNodes.reverse();
  1352. childNodes.each(insert.curry(element));
  1353. content.evalScripts.bind(content).defer();
  1354. }
  1355. return element;
  1356. },
  1357. wrap: function(element, wrapper, attributes) {
  1358. element = $(element);
  1359. if (Object.isElement(wrapper))
  1360. $(wrapper).writeAttribute(attributes || { });
  1361. else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
  1362. else wrapper = new Element('div', wrapper);
  1363. if (element.parentNode)
  1364. element.parentNode.replaceChild(wrapper, element);
  1365. wrapper.appendChild(element);
  1366. return wrapper;
  1367. },
  1368. inspect: function(element) {
  1369. element = $(element);
  1370. var result = '<' + element.tagName.toLowerCase();
  1371. $H({'id': 'id', 'className': 'class'}).each(function(pair) {
  1372. var property = pair.first(), attribute = pair.last();
  1373. var value = (element[property] || '').toString();
  1374. if (value) result += ' ' + attribute + '=' + value.inspect(true);
  1375. });
  1376. return result + '>';
  1377. },
  1378. recursivelyCollect: function(element, property) {
  1379. element = $(element);
  1380. var elements = [];
  1381. while (element = element[property])
  1382. if (element.nodeType == 1)
  1383. elements.push(Element.extend(element));
  1384. return elements;
  1385. },
  1386. ancestors: function(element) {
  1387. return $(element).recursivelyCollect('parentNode');
  1388. },
  1389. descendants: function(element) {
  1390. return $(element).getElementsBySelector("*");
  1391. },
  1392. firstDescendant: function(element) {
  1393. element = $(element).firstChild;
  1394. while (element && element.nodeType != 1) element = element.nextSibling;
  1395. return $(element);
  1396. },
  1397. immediateDescendants: function(element) {
  1398. if (!(element = $(element).firstChild)) return [];
  1399. while (element && element.nodeType != 1) element = element.nextSibling;
  1400. if (element) return [element].concat($(element).nextSiblings());
  1401. return [];
  1402. },
  1403. previousSiblings: function(element) {
  1404. return $(element).recursivelyCollect('previousSibling');
  1405. },
  1406. nextSiblings: function(element) {
  1407. return $(element).recursivelyCollect('nextSibling');
  1408. },
  1409. siblings: function(element) {
  1410. element = $(element);
  1411. return element.previousSiblings().reverse().concat(element.nextSiblings());
  1412. },
  1413. match: function(element, selector) {
  1414. if (Object.isString(selector))
  1415. selector = new Selector(selector);
  1416. return selector.match($(element));
  1417. },
  1418. up: function(element, expression, index) {
  1419. element = $(element);
  1420. if (arguments.length == 1) return $(element.parentNode);
  1421. var ancestors = element.ancestors();
  1422. return Object.isNumber(expression) ? ancestors[expression] :
  1423. Selector.findElement(ancestors, expression, index);
  1424. },
  1425. down: function(element, expression, index) {
  1426. element = $(element);
  1427. if (arguments.length == 1) return element.firstDescendant();
  1428. return Object.isNumber(expression) ? element.descendants()[expression] :
  1429. element.select(expression)[index || 0];
  1430. },
  1431. previous: function(element, expression, index) {
  1432. element = $(element);
  1433. if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
  1434. var previousSiblings = element.previousSiblings();
  1435. return Object.isNumber(expression) ? previousSiblings[expression] :
  1436. Selector.findElement(previousSiblings, expression, index);
  1437. },
  1438. next: function(element, expression, index) {
  1439. element = $(element);
  1440. if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
  1441. var nextSiblings = element.nextSiblings();
  1442. return Object.isNumber(expression) ? nextSiblings[expression] :
  1443. Selector.findElement(nextSiblings, expression, index);
  1444. },
  1445. select: function() {
  1446. var args = $A(arguments), element = $(args.shift());
  1447. return Selector.findChildElements(element, args);
  1448. },
  1449. adjacent: function() {
  1450. var args = $A(arguments), element = $(args.shift());
  1451. return Selector.findChildElements(element.parentNode, args).without(element);
  1452. },
  1453. identify: function(element) {
  1454. element = $(element);
  1455. var id = element.readAttribute('id'), self = arguments.callee;
  1456. if (id) return id;
  1457. do { id = 'anonymous_element_' + self.counter++ } while ($(id));
  1458. element.writeAttribute('id', id);
  1459. return id;
  1460. },
  1461. readAttribute: function(element, name) {
  1462. element = $(element);
  1463. if (Prototype.Browser.IE) {
  1464. var t = Element._attributeTranslations.read;
  1465. if (t.values[name]) return t.values[name](element, name);
  1466. if (t.names[name]) name = t.names[name];
  1467. if (name.include(':')) {
  1468. return (!element.attributes || !element.attributes[name]) ? null :
  1469. element.attributes[name].value;
  1470. }
  1471. }
  1472. return element.getAttribute(name);
  1473. },
  1474. writeAttribute: function(element, name, value) {
  1475. element = $(element);
  1476. var attributes = { }, t = Element._attributeTranslations.write;
  1477. if (typeof name == 'object') attributes = name;
  1478. else attributes[name] = Object.isUndefined(value) ? true : value;
  1479. for (var attr in attributes) {
  1480. name = t.names[attr] || attr;
  1481. value = attributes[attr];
  1482. if (t.values[attr]) name = t.values[attr](element, value);
  1483. if (value === false || value === null)
  1484. element.removeAttribute(name);
  1485. else if (value === true)
  1486. element.setAttribute(name, name);
  1487. else element.setAttribute(name, value);
  1488. }
  1489. return element;
  1490. },
  1491. getHeight: function(element) {
  1492. return $(element).getDimensions().height;
  1493. },
  1494. getWidth: function(element) {
  1495. return $(element).getDimensions().width;
  1496. },
  1497. classNames: function(element) {
  1498. return new Element.ClassNames(element);
  1499. },
  1500. hasClassName: function(element, className) {
  1501. if (!(element = $(element))) return;
  1502. var elementClassName = element.className;
  1503. return (elementClassName.length > 0 && (elementClassName == className ||
  1504. new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
  1505. },
  1506. addClassName: function(element, className) {
  1507. if (!(element = $(element))) return;
  1508. if (!element.hasClassName(className))
  1509. element.className += (element.className ? ' ' : '') + className;
  1510. return element;
  1511. },
  1512. removeClassName: function(element, className) {
  1513. if (!(element = $(element))) return;
  1514. element.className = element.className.replace(
  1515. new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
  1516. return element;
  1517. },
  1518. toggleClassName: function(element, className) {
  1519. if (!(element = $(element))) return;
  1520. return element[element.hasClassName(className) ?
  1521. 'removeClassName' : 'addClassName'](className);
  1522. },
  1523. // removes whitespace-only text node children
  1524. cleanWhitespace: function(element) {
  1525. element = $(element);
  1526. var node = element.firstChild;
  1527. while (node) {
  1528. var nextNode = node.nextSibling;
  1529. if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
  1530. element.removeChild(node);
  1531. node = nextNode;
  1532. }
  1533. return element;
  1534. },
  1535. empty: function(element) {
  1536. return $(element).innerHTML.blank();
  1537. },
  1538. descendantOf: function(element, ancestor) {
  1539. element = $(element), ancestor = $(ancestor);
  1540. var originalAncestor = ancestor;
  1541. if (element.compareDocumentPosition)
  1542. return (element.compareDocumentPosition(ancestor) & 8) === 8;
  1543. if (element.sourceIndex && !Prototype.Browser.Opera) {
  1544. var e = element.sourceIndex, a = ancestor.sourceIndex,
  1545. nextAncestor = ancestor.nextSibling;
  1546. if (!nextAncestor) {
  1547. do { ancestor = ancestor.parentNode; }
  1548. while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
  1549. }
  1550. if (nextAncestor) return (e > a && e < nextAncestor.sourceIndex);
  1551. }
  1552. while (element = element.parentNode)
  1553. if (element == originalAncestor) return true;
  1554. return false;
  1555. },
  1556. scrollTo: function(element) {
  1557. element = $(element);
  1558. var pos = element.cumulativeOffset();
  1559. window.scrollTo(pos[0], pos[1]);
  1560. return element;
  1561. },
  1562. getStyle: function(element, style) {
  1563. element = $(element);
  1564. style = style == 'float' ? 'cssFloat' : style.camelize();
  1565. var value = element.style[style];
  1566. if (!value) {
  1567. var css = document.defaultView.getComputedStyle(element, null);
  1568. value = css ? css[style] : null;
  1569. }
  1570. if (style == 'opacity') return value ? parseFloat(value) : 1.0;
  1571. return value == 'auto' ? null : value;
  1572. },
  1573. getOpacity: function(element) {
  1574. return $(element).getStyle('opacity');
  1575. },
  1576. setStyle: function(element, styles) {
  1577. element = $(element);
  1578. var elementStyle = element.style, match;
  1579. if (Object.isString(styles)) {
  1580. element.style.cssText += ';' + styles;
  1581. return styles.include('opacity') ?
  1582. element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
  1583. }
  1584. for (var property in styles)
  1585. if (property == 'opacity') element.setOpacity(styles[property]);
  1586. else
  1587. elementStyle[(property == 'float' || property == 'cssFloat') ?
  1588. (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
  1589. property] = styles[property];
  1590. return element;
  1591. },
  1592. setOpacity: function(element, value) {
  1593. element = $(element);
  1594. element.style.opacity = (value == 1 || value === '') ? '' :
  1595. (value < 0.00001) ? 0 : value;
  1596. return element;
  1597. },
  1598. getDimensions: function(element) {
  1599. element = $(element);
  1600. var display = $(element).getStyle('display');
  1601. if (display != 'none' && display != null) // Safari bug
  1602. return {width: element.offsetWidth, height: element.offsetHeight};
  1603. // All *Width and *Height properties give 0 on elements with display none,
  1604. // so enable the element temporarily
  1605. var els = element.style;
  1606. var originalVisibility = els.visibility;
  1607. var originalPosition = els.position;
  1608. var originalDisplay = els.display;
  1609. els.visibility = 'hidden';
  1610. els.position = 'absolute';
  1611. els.display = 'block';
  1612. var originalWidth = element.clientWidth;
  1613. var originalHeight = element.clientHeight;
  1614. els.display = originalDisplay;
  1615. els.position = originalPosition;
  1616. els.visibility = originalVisibility;
  1617. return {width: originalWidth, height: originalHeight};
  1618. },
  1619. makePositioned: function(element) {
  1620. element = $(element);
  1621. var pos = Element.getStyle(element, 'position');
  1622. if (pos == 'static' || !pos) {
  1623. element._madePositioned = true;
  1624. element.style.position = 'relative';
  1625. // Opera returns the offset relative to the positioning context, when an
  1626. // element is position relative but top and left have not been defined
  1627. if (window.opera) {
  1628. element.style.top = 0;
  1629. element.style.left = 0;
  1630. }
  1631. }
  1632. return element;
  1633. },
  1634. undoPositioned: function(element) {
  1635. element = $(element);
  1636. if (element._madePositioned) {
  1637. element._madePositioned = undefined;
  1638. element.style.position =
  1639. element.style.top =
  1640. element.style.left =
  1641. element.style.bottom =
  1642. element.style.right = '';
  1643. }
  1644. return element;
  1645. },
  1646. makeClipping: function(element) {
  1647. element = $(element);
  1648. if (element._overflow) return element;
  1649. element._overflow = Element.getStyle(element, 'overflow') || 'auto';
  1650. if (element._overflow !== 'hidden')
  1651. element.style.overflow = 'hidden';
  1652. return element;
  1653. },
  1654. undoClipping: function(element) {
  1655. element = $(element);
  1656. if (!element._overflow) return element;
  1657. element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
  1658. element._overflow = null;
  1659. return element;
  1660. },
  1661. cumulativeOffset: function(element) {
  1662. var valueT = 0, valueL = 0;
  1663. do {
  1664. valueT += element.offsetTop || 0;
  1665. valueL += element.offsetLeft || 0;
  1666. element = element.offsetParent;
  1667. } while (element);
  1668. return Element._returnOffset(valueL, valueT);
  1669. },
  1670. positionedOffset: function(element) {
  1671. var valueT = 0, valueL = 0;
  1672. do {
  1673. valueT += element.offsetTop || 0;
  1674. valueL += element.offsetLeft || 0;
  1675. element = element.offsetParent;
  1676. if (element) {
  1677. if (element.tagName == 'BODY') break;
  1678. var p = Element.getStyle(element, 'position');
  1679. if (p == 'relative' || p == 'absolute') break;
  1680. }
  1681. } while (element);
  1682. return Element._returnOffset(valueL, valueT);
  1683. },
  1684. absolutize: function(element) {
  1685. element = $(element);
  1686. if (element.getStyle('position') == 'absolute') return;
  1687. // Position.prepare(); // To be done manually by Scripty when it needs it.
  1688. var offsets = element.positionedOffset();
  1689. var top = offsets[1];
  1690. var left = offsets[0];
  1691. var width = element.clientWidth;
  1692. var height = element.clientHeight;
  1693. element._originalLeft = left - parseFloat(element.style.left || 0);
  1694. element._originalTop = top - parseFloat(element.style.top || 0);
  1695. element._originalWidth = element.style.width;
  1696. element._originalHeight = element.style.height;
  1697. element.style.position = 'absolute';
  1698. element.style.top = top + 'px';
  1699. element.style.left = left + 'px';
  1700. element.style.width = width + 'px';
  1701. element.style.height = height + 'px';
  1702. return element;
  1703. },
  1704. relativize: function(element) {
  1705. element = $(element);
  1706. if (element.getStyle('position') == 'relative') return;
  1707. // Position.prepare(); // To be done manually by Scripty when it needs it.
  1708. element.style.position = 'relative';
  1709. var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
  1710. var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
  1711. element.style.top = top + 'px';
  1712. element.style.left = left + 'px';
  1713. element.style.height = element._originalHeight;
  1714. element.style.width = element._originalWidth;
  1715. return element;
  1716. },
  1717. cumulativeScrollOffset: function(element) {
  1718. var valueT = 0, valueL = 0;
  1719. do {
  1720. valueT += element.scrollTop || 0;
  1721. valueL += element.scrollLeft || 0;
  1722. element = element.parentNode;
  1723. } while (element);
  1724. return Element._returnOffset(valueL, valueT);
  1725. },
  1726. getOffsetParent: function(element) {
  1727. if (element.offsetParent) return $(element.offsetParent);
  1728. if (element == document.body) return $(element);
  1729. while ((element = element.parentNode) && element != document.body)
  1730. if (Element.getStyle(element, 'position') != 'static')
  1731. return $(element);
  1732. return $(document.body);
  1733. },
  1734. viewportOffset: function(forElement) {
  1735. var valueT = 0, valueL = 0;
  1736. var element = forElement;
  1737. do {
  1738. valueT += element.offsetTop || 0;
  1739. valueL += element.offsetLeft || 0;
  1740. // Safari fix
  1741. if (element.offsetParent == document.body &&
  1742. Element.getStyle(element, 'position') == 'absolute') break;
  1743. } while (element = element.offsetParent);
  1744. element = forElement;
  1745. do {
  1746. if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
  1747. valueT -= element.scrollTop || 0;
  1748. valueL -= element.scrollLeft || 0;
  1749. }
  1750. } while (element = element.parentNode);
  1751. return Element._returnOffset(valueL, valueT);
  1752. },
  1753. clonePosition: function(element, source) {
  1754. var options = Object.extend({
  1755. setLeft: true,
  1756. setTop: true,
  1757. setWidth: true,
  1758. setHeight: true,
  1759. offsetTop: 0,
  1760. offsetLeft: 0
  1761. }, arguments[2] || { });
  1762. // find page position of source
  1763. source = $(source);
  1764. var p = source.viewportOffset();
  1765. // find coordinate system to use
  1766. element = $(element);
  1767. var delta = [0, 0];
  1768. var parent = null;
  1769. // delta [0,0] will do fine with position: fixed elements,
  1770. // position:absolute needs offsetParent deltas
  1771. if (Element.getStyle(element, 'position') == 'absolute') {
  1772. parent = element.getOffsetParent();
  1773. delta = parent.viewportOffset();
  1774. }
  1775. // correct by body offsets (fixes Safari)
  1776. if (parent == document.body) {
  1777. delta[0] -= document.body.offsetLeft;
  1778. delta[1] -= document.body.offsetTop;
  1779. }
  1780. // set position
  1781. if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
  1782. if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
  1783. if (options.setWidth) element.style.width = source.offsetWidth + 'px';
  1784. if (options.setHeight) element.style.height = source.offsetHeight + 'px';
  1785. return element;
  1786. }
  1787. };
  1788. Element.Methods.identify.counter = 1;
  1789. Object.extend(Element.Methods, {
  1790. getElementsBySelector: Element.Methods.select,
  1791. childElements: Element.Methods.immediateDescendants
  1792. });
  1793. Element._attributeTranslations = {
  1794. write: {
  1795. names: {
  1796. className: 'class',
  1797. htmlFor: 'for'
  1798. },
  1799. values: { }
  1800. }
  1801. };
  1802. if (Prototype.Browser.Opera) {
  1803. Element.Methods.getStyle = Element.Methods.getStyle.wrap(
  1804. function(proceed, element, style) {
  1805. switch (style) {
  1806. case 'left': case 'top': case 'right': case 'bottom':
  1807. if (proceed(element, 'position') === 'static') return null;
  1808. case 'height': case 'width':
  1809. // returns '0px' for hidden elements; we want it to return null
  1810. if (!Element.visible(element)) return null;
  1811. // returns the border-box dimensions rather than the content-box
  1812. // dimensions, so we subtract padding and borders from the value
  1813. var dim = parseInt(proceed(element, style), 10);
  1814. if (dim !== element['offset' + style.capitalize()])
  1815. return dim + 'px';
  1816. var properties;
  1817. if (style === 'height') {
  1818. properties = ['border-top-width', 'padding-top',
  1819. 'padding-bottom', 'border-bottom-width'];
  1820. }
  1821. else {
  1822. properties = ['border-left-width', 'padding-left',
  1823. 'padding-right', 'border-right-width'];
  1824. }
  1825. return properties.inject(dim, function(memo, property) {
  1826. var val = proceed(element, property);
  1827. return val === null ? memo : memo - parseInt(val, 10);
  1828. }) + 'px';
  1829. default: return proceed(element, style);
  1830. }
  1831. }
  1832. );
  1833. Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
  1834. function(proceed, element, attribute) {
  1835. if (attribute === 'title') return element.title;
  1836. return proceed(element, attribute);
  1837. }
  1838. );
  1839. }
  1840. else if (Prototype.Browser.IE) {
  1841. $w('positionedOffset getOffsetParent viewportOffset').each(function(method) {
  1842. Element.Methods[method] = Element.Methods[method].wrap(
  1843. function(proceed, element) {
  1844. element = $(element);
  1845. var position = element.getStyle('position');
  1846. if (position != 'static') return proceed(element);
  1847. element.setStyle({ position: 'relative' });
  1848. var value = proceed(element);
  1849. element.setStyle({ position: position });
  1850. return value;
  1851. }
  1852. );
  1853. });
  1854. Element.Methods.getStyle = function(element, style) {
  1855. element = $(element);
  1856. style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
  1857. var value = element.style[style];
  1858. if (!value && element.currentStyle) value = element.currentStyle[style];
  1859. if (style == 'opacity') {
  1860. if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
  1861. if (value[1]) return parseFloat(value[1]) / 100;
  1862. return 1.0;
  1863. }
  1864. if (value == 'auto') {
  1865. if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
  1866. return element['offset' + style.capitalize()] + 'px';
  1867. return null;
  1868. }
  1869. return value;
  1870. };
  1871. Element.Methods.setOpacity = function(element, value) {
  1872. function stripAlpha(filter){
  1873. return filter.replace(/alpha\([^\)]*\)/gi,'');
  1874. }
  1875. element = $(element);
  1876. var currentStyle = element.currentStyle;
  1877. if ((currentStyle && !currentStyle.hasLayout) ||
  1878. (!currentStyle && element.style.zoom == 'normal'))
  1879. element.style.zoom = 1;
  1880. var filter = element.getStyle('filter'), style = element.style;
  1881. if (value == 1 || value === '') {
  1882. (filter = stripAlpha(filter)) ?
  1883. style.filter = filter : style.removeAttribute('filter');
  1884. return element;
  1885. } else if (value < 0.00001) value = 0;
  1886. style.filter = stripAlpha(filter) +
  1887. 'alpha(opacity=' + (value * 100) + ')';
  1888. return element;
  1889. };
  1890. Element._attributeTranslations = {
  1891. read: {
  1892. names: {
  1893. 'class': 'className',
  1894. 'for': 'htmlFor'
  1895. },
  1896. values: {
  1897. _getAttr: function(element, attribute) {
  1898. return element.getAttribute(attribute, 2);
  1899. },
  1900. _getAttrNode: function(element, attribute) {
  1901. var node = element.getAttributeNode(attribute);
  1902. return node ? node.value : "";
  1903. },
  1904. _getEv: function(element, attribute) {
  1905. attribute = element.getAttribute(attribute);
  1906. return attribute ? attribute.toString().slice(23, -2) : null;
  1907. },
  1908. _flag: function(element, attribute) {
  1909. return $(element).hasAttribute(attribute) ? attribute : null;
  1910. },
  1911. style: function(element) {
  1912. return element.style.cssText.toLowerCase();
  1913. },
  1914. title: function(element) {
  1915. return element.title;
  1916. }
  1917. }
  1918. }
  1919. };
  1920. Element._attributeTranslations.write = {
  1921. names: Object.clone(Element._attributeTranslations.read.names),
  1922. values: {
  1923. checked: function(element, value) {
  1924. element.checked = !!value;
  1925. },
  1926. style: function(element, value) {
  1927. element.style.cssText = value ? value : '';
  1928. }
  1929. }
  1930. };
  1931. Element._attributeTranslations.has = {};
  1932. $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
  1933. 'encType maxLength readOnly longDesc').each(function(attr) {
  1934. Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
  1935. Element._attributeTranslations.has[attr.toLowerCase()] = attr;
  1936. });
  1937. (function(v) {
  1938. Object.extend(v, {
  1939. href: v._getAttr,
  1940. src: v._getAttr,
  1941. type: v._getAttr,
  1942. action: v._getAttrNode,
  1943. disabled: v._flag,
  1944. checked: v._flag,
  1945. readonly: v._flag,
  1946. multiple: v._flag,
  1947. onload: v._getEv,
  1948. onunload: v._getEv,
  1949. onclick: v._getEv,
  1950. ondblclick: v._getEv,
  1951. onmousedown: v._getEv,
  1952. onmouseup: v._getEv,
  1953. onmouseover: v._getEv,
  1954. onmousemove: v._getEv,
  1955. onmouseout: v._getEv,
  1956. onfocus: v._getEv,
  1957. onblur: v._getEv,
  1958. onkeypress: v._getEv,
  1959. onkeydown: v._getEv,
  1960. onkeyup: v._getEv,
  1961. onsubmit: v._getEv,
  1962. onreset: v._getEv,
  1963. onselect: v._getEv,
  1964. onchange: v._getEv
  1965. });
  1966. })(Element._attributeTranslations.read.values);
  1967. }
  1968. else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
  1969. Element.Methods.setOpacity = function(element, value) {
  1970. element = $(element);
  1971. element.style.opacity = (value == 1) ? 0.999999 :
  1972. (value === '') ? '' : (value < 0.00001) ? 0 : value;
  1973. return element;
  1974. };
  1975. }
  1976. else if (Prototype.Browser.WebKit) {
  1977. Element.Methods.setOpacity = function(element, value) {
  1978. element = $(element);
  1979. element.style.opacity = (value == 1 || value === '') ? '' :
  1980. (value < 0.00001) ? 0 : value;
  1981. if (value == 1)
  1982. if(element.tagName == 'IMG' && element.width) {
  1983. element.width++; element.width--;
  1984. } else try {
  1985. var n = document.createTextNode(' ');
  1986. element.appendChild(n);
  1987. element.removeChild(n);
  1988. } catch (e) { }
  1989. return element;
  1990. };
  1991. // Safari returns margins on body which is incorrect if the child is absolutely
  1992. // positioned. For performance reasons, redefine Element#cumulativeOffset for
  1993. // KHTML/WebKit only.
  1994. Element.Methods.cumulativeOffset = function(element) {
  1995. var valueT = 0, valueL = 0;
  1996. do {
  1997. valueT += element.offsetTop || 0;
  1998. valueL += element.offsetLeft || 0;
  1999. if (element.offsetParent == document.body)
  2000. if (Element.getStyle(element, 'position') == 'absolute') break;
  2001. element = element.offsetParent;
  2002. } while (element);
  2003. return Element._returnOffset(valueL, valueT);
  2004. };
  2005. }
  2006. if (Prototype.Browser.IE || Prototype.Browser.Opera) {
  2007. // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
  2008. Element.Methods.update = function(element, content) {
  2009. element = $(element);
  2010. if (content && content.toElement) content = content.toElement();
  2011. if (Object.isElement(content)) return element.update().insert(content);
  2012. content = Object.toHTML(content);
  2013. var tagName = element.tagName.toUpperCase();
  2014. if (tagName in Element._insertionTranslations.tags) {
  2015. $A(element.childNodes).each(function(node) { element.removeChild(node) });
  2016. Element._getContentFromAnonymousElement(tagName, content.stripScripts())
  2017. .each(function(node) { element.appendChild(node) });
  2018. }
  2019. else element.innerHTML = content.stripScripts();
  2020. content.evalScripts.bind(content).defer();
  2021. return element;
  2022. };
  2023. }
  2024. if (document.createElement('div').outerHTML) {
  2025. Element.Methods.replace = function(element, content) {
  2026. element = $(element);
  2027. if (content && content.toElement) content = content.toElement();
  2028. if (Object.isElement(content)) {
  2029. element.parentNode.replaceChild(content, element);
  2030. return element;
  2031. }
  2032. content = Object.toHTML(content);
  2033. var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
  2034. if (Element._insertionTranslations.tags[tagName]) {
  2035. var nextSibling = element.next();
  2036. var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
  2037. parent.removeChild(element);
  2038. if (nextSibling)
  2039. fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
  2040. else
  2041. fragments.each(function(node) { parent.appendChild(node) });
  2042. }
  2043. else element.outerHTML = content.stripScripts();
  2044. content.evalScripts.bind(content).defer();
  2045. return element;
  2046. };
  2047. }
  2048. Element._returnOffset = function(l, t) {
  2049. var result = [l, t];
  2050. result.left = l;
  2051. result.top = t;
  2052. return result;
  2053. };
  2054. Element._getContentFromAnonymousElement = function(tagName, html) {
  2055. var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
  2056. if (t) {
  2057. div.innerHTML = t[0] + html + t[1];
  2058. t[2].times(function() { div = div.firstChild });
  2059. } else div.innerHTML = html;
  2060. return $A(div.childNodes);
  2061. };
  2062. Element._insertionTranslations = {
  2063. before: function(element, node) {
  2064. element.parentNode.insertBefore(node, element);
  2065. },
  2066. top: function(element, node) {
  2067. element.insertBefore(node, element.firstChild);
  2068. },
  2069. bottom: function(element, node) {
  2070. element.appendChild(node);
  2071. },
  2072. after: function(element, node) {
  2073. element.parentNode.insertBefore(node, element.nextSibling);
  2074. },
  2075. tags: {
  2076. TABLE: ['<table>', '</table>', 1],
  2077. TBODY: ['<table><tbody>', '</tbody></table>', 2],
  2078. TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
  2079. TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
  2080. SELECT: ['<select>', '</select>', 1]
  2081. }
  2082. };
  2083. (function() {
  2084. Object.extend(this.tags, {
  2085. THEAD: this.tags.TBODY,
  2086. TFOOT: this.tags.TBODY,
  2087. TH: this.tags.TD
  2088. });
  2089. }).call(Element._insertionTranslations);
  2090. Element.Methods.Simulated = {
  2091. hasAttribute: function(element, attribute) {
  2092. attribute = Element._attributeTranslations.has[attribute] || attribute;
  2093. var node = $(element).getAttributeNode(attribute);
  2094. return node && node.specified;
  2095. }
  2096. };
  2097. Element.Methods.ByTag = { };
  2098. Object.extend(Element, Element.Methods);
  2099. if (!Prototype.BrowserFeatures.ElementExtensions &&
  2100. document.createElement('div').__proto__) {
  2101. window.HTMLElement = { };
  2102. window.HTMLElement.prototype = document.createElement('div').__proto__;
  2103. Prototype.BrowserFeatures.ElementExtensions = true;
  2104. }
  2105. Element.extend = (function() {
  2106. if (Prototype.BrowserFeatures.SpecificElementExtensions)
  2107. return Prototype.K;
  2108. var Methods = { }, ByTag = Element.Methods.ByTag;
  2109. var extend = Object.extend(function(element) {
  2110. if (!element || element._extendedByPrototype ||
  2111. element.nodeType != 1 || element == window) return element;
  2112. var methods = Object.clone(Methods),
  2113. tagName = element.tagName, property, value;
  2114. // extend methods for specific tags
  2115. if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
  2116. for (property in methods) {
  2117. value = methods[property];
  2118. if (Object.isFunction(value) && !(property in element))
  2119. element[property] = value.methodize();
  2120. }
  2121. element._extendedByPrototype = Prototype.emptyFunction;
  2122. return element;
  2123. }, {
  2124. refresh: function() {
  2125. // extend methods for all tags (Safari doesn't need this)
  2126. if (!Prototype.BrowserFeatures.ElementExtensions) {
  2127. Object.extend(Methods, Element.Methods);
  2128. Object.extend(Methods, Element.Methods.Simulated);
  2129. }
  2130. }
  2131. });
  2132. extend.refresh();
  2133. return extend;
  2134. })();
  2135. Element.hasAttribute = function(element, attribute) {
  2136. if (element.hasAttribute) return element.hasAttribute(attribute);
  2137. return Element.Methods.Simulated.hasAttribute(element, attribute);
  2138. };
  2139. Element.addMethods = function(methods) {
  2140. var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
  2141. if (!methods) {
  2142. Object.extend(Form, Form.Methods);
  2143. Object.extend(Form.Element, Form.Element.Methods);
  2144. Object.extend(Element.Methods.ByTag, {
  2145. "FORM": Object.clone(Form.Methods),
  2146. "INPUT": Object.clone(Form.Element.Methods),
  2147. "SELECT": Object.clone(Form.Element.Methods),
  2148. "TEXTAREA": Object.clone(Form.Element.Methods)
  2149. });
  2150. }
  2151. if (arguments.length == 2) {
  2152. var tagName = methods;
  2153. methods = arguments[1];
  2154. }
  2155. if (!tagName) Object.extend(Element.Methods, methods || { });
  2156. else {
  2157. if (Object.isArray(tagName)) tagName.each(extend);
  2158. else extend(tagName);
  2159. }
  2160. function extend(tagName) {
  2161. tagName = tagName.toUpperCase();
  2162. if (!Element.Methods.ByTag[tagName])
  2163. Element.Methods.ByTag[tagName] = { };
  2164. Object.extend(Element.Methods.ByTag[tagName], methods);
  2165. }
  2166. function copy(methods, destination, onlyIfAbsent) {
  2167. onlyIfAbsent = onlyIfAbsent || false;
  2168. for (var property in methods) {
  2169. var value = methods[property];
  2170. if (!Object.isFunction(value)) continue;
  2171. if (!onlyIfAbsent || !(property in destination))
  2172. destination[property] = value.methodize();
  2173. }
  2174. }
  2175. function findDOMClass(tagName) {
  2176. var klass;
  2177. var trans = {
  2178. "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
  2179. "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
  2180. "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
  2181. "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
  2182. "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
  2183. "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
  2184. "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
  2185. "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
  2186. "FrameSet", "IFRAME": "IFrame"
  2187. };
  2188. if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
  2189. if (window[klass]) return window[klass];
  2190. klass = 'HTML' + tagName + 'Element';
  2191. if (window[klass]) return window[klass];
  2192. klass = 'HTML' + tagName.capitalize() + 'Element';
  2193. if (window[klass]) return window[klass];
  2194. window[klass] = { };
  2195. window[klass].prototype = document.createElement(tagName).__proto__;
  2196. return window[klass];
  2197. }
  2198. if (F.ElementExtensions) {
  2199. copy(Element.Methods, HTMLElement.prototype);
  2200. copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  2201. }
  2202. if (F.SpecificElementExtensions) {
  2203. for (var tag in Element.Methods.ByTag) {
  2204. var klass = findDOMClass(tag);
  2205. if (Object.isUndefined(klass)) continue;
  2206. copy(T[tag], klass.prototype);
  2207. }
  2208. }
  2209. Object.extend(Element, Element.Methods);
  2210. delete Element.ByTag;
  2211. if (Element.extend.refresh) Element.extend.refresh();
  2212. Element.cache = { };
  2213. };
  2214. document.viewport = {
  2215. getDimensions: function() {
  2216. var dimensions = { };
  2217. var B = Prototype.Browser;
  2218. $w('width height').each(function(d) {
  2219. var D = d.capitalize();
  2220. dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
  2221. (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
  2222. });
  2223. return dimensions;
  2224. },
  2225. getWidth: function() {
  2226. return this.getDimensions().width;
  2227. },
  2228. getHeight: function() {
  2229. return this.getDimensions().height;
  2230. },
  2231. getScrollOffsets: function() {
  2232. return Element._returnOffset(
  2233. window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
  2234. window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
  2235. }
  2236. };
  2237. /* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
  2238. * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
  2239. * license. Please see http://www.yui-ext.com/ for more information. */
  2240. var Selector = Class.create({
  2241. initialize: function(expression) {
  2242. this.expression = expression.strip();
  2243. this.compileMatcher();
  2244. },
  2245. shouldUseXPath: function() {
  2246. if (!Prototype.BrowserFeatures.XPath) return false;
  2247. var e = this.expression;
  2248. // Safari 3 chokes on :*-of-type and :empty
  2249. if (Prototype.Browser.WebKit &&
  2250. (e.include("-of-type") || e.include(":empty")))
  2251. return false;
  2252. // XPath can't do namespaced attributes, nor can it read
  2253. // the "checked" property from DOM nodes
  2254. if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
  2255. return false;
  2256. return true;
  2257. },
  2258. compileMatcher: function() {
  2259. if (this.shouldUseXPath())
  2260. return this.compileXPathMatcher();
  2261. var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
  2262. c = Selector.criteria, le, p, m;
  2263. if (Selector._cache[e]) {
  2264. this.matcher = Selector._cache[e];
  2265. return;
  2266. }
  2267. this.matcher = ["this.matcher = function(root) {",
  2268. "var r = root, h = Selector.handlers, c = false, n;"];
  2269. while (e && le != e && (/\S/).test(e)) {
  2270. le = e;
  2271. for (var i in ps) {
  2272. p = ps[i];
  2273. if (m = e.match(p)) {
  2274. this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
  2275. new Template(c[i]).evaluate(m));
  2276. e = e.replace(m[0], '');
  2277. break;
  2278. }
  2279. }
  2280. }
  2281. this.matcher.push("return h.unique(n);\n}");
  2282. eval(this.matcher.join('\n'));
  2283. Selector._cache[this.expression] = this.matcher;
  2284. },
  2285. compileXPathMatcher: function() {
  2286. var e = this.expression, ps = Selector.patterns,
  2287. x = Selector.xpath, le, m;
  2288. if (Selector._cache[e]) {
  2289. this.xpath = Selector._cache[e]; return;
  2290. }
  2291. this.matcher = ['.//*'];
  2292. while (e && le != e && (/\S/).test(e)) {
  2293. le = e;
  2294. for (var i in ps) {
  2295. if (m = e.match(ps[i])) {
  2296. this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
  2297. new Template(x[i]).evaluate(m));
  2298. e = e.replace(m[0], '');
  2299. break;
  2300. }
  2301. }
  2302. }
  2303. this.xpath = this.matcher.join('');
  2304. Selector._cache[this.expression] = this.xpath;
  2305. },
  2306. findElements: function(root) {
  2307. root = root || document;
  2308. if (this.xpath) return document._getElementsByXPath(this.xpath, root);
  2309. return this.matcher(root);
  2310. },
  2311. match: function(element) {
  2312. this.tokens = [];
  2313. var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
  2314. var le, p, m;
  2315. while (e && le !== e && (/\S/).test(e)) {
  2316. le = e;
  2317. for (var i in ps) {
  2318. p = ps[i];
  2319. if (m = e.match(p)) {
  2320. // use the Selector.assertions methods unless the selector
  2321. // is too complex.
  2322. if (as[i]) {
  2323. this.tokens.push([i, Object.clone(m)]);
  2324. e = e.replace(m[0], '');
  2325. } else {
  2326. // reluctantly do a document-wide search
  2327. // and look for a match in the array
  2328. return this.findElements(document).include(element);
  2329. }
  2330. }
  2331. }
  2332. }
  2333. var match = true, name, matches;
  2334. for (var i = 0, token; token = this.tokens[i]; i++) {
  2335. name = token[0], matches = token[1];
  2336. if (!Selector.assertions[name](element, matches)) {
  2337. match = false; break;
  2338. }
  2339. }
  2340. return match;
  2341. },
  2342. toString: function() {
  2343. return this.expression;
  2344. },
  2345. inspect: function() {
  2346. return "#<Selector:" + this.expression.inspect() + ">";
  2347. }
  2348. });
  2349. Object.extend(Selector, {
  2350. _cache: { },
  2351. xpath: {
  2352. descendant: "//*",
  2353. child: "/*",
  2354. adjacent: "/following-sibling::*[1]",
  2355. laterSibling: '/following-sibling::*',
  2356. tagName: function(m) {
  2357. if (m[1] == '*') return '';
  2358. return "[local-name()='" + m[1].toLowerCase() +
  2359. "' or local-name()='" + m[1].toUpperCase() + "']";
  2360. },
  2361. className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
  2362. id: "[@id='#{1}']",
  2363. attrPresence: function(m) {
  2364. m[1] = m[1].toLowerCase();
  2365. return new Template("[@#{1}]").evaluate(m);
  2366. },
  2367. attr: function(m) {
  2368. m[1] = m[1].toLowerCase();
  2369. m[3] = m[5] || m[6];
  2370. return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
  2371. },
  2372. pseudo: function(m) {
  2373. var h = Selector.xpath.pseudos[m[1]];
  2374. if (!h) return '';
  2375. if (Object.isFunction(h)) return h(m);
  2376. return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
  2377. },
  2378. operators: {
  2379. '=': "[@#{1}='#{3}']",
  2380. '!=': "[@#{1}!='#{3}']",
  2381. '^=': "[starts-with(@#{1}, '#{3}')]",
  2382. '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
  2383. '*=': "[contains(@#{1}, '#{3}')]",
  2384. '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
  2385. '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
  2386. },
  2387. pseudos: {
  2388. 'first-child': '[not(preceding-sibling::*)]',
  2389. 'last-child': '[not(following-sibling::*)]',
  2390. 'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
  2391. 'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
  2392. 'checked': "[@checked]",
  2393. 'disabled': "[@disabled]",
  2394. 'enabled': "[not(@disabled)]",
  2395. 'not': function(m) {
  2396. var e = m[6], p = Selector.patterns,
  2397. x = Selector.xpath, le, v;
  2398. var exclusion = [];
  2399. while (e && le != e && (/\S/).test(e)) {
  2400. le = e;
  2401. for (var i in p) {
  2402. if (m = e.match(p[i])) {
  2403. v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
  2404. exclusion.push("(" + v.substring(1, v.length - 1) + ")");
  2405. e = e.replace(m[0], '');
  2406. break;
  2407. }
  2408. }
  2409. }
  2410. return "[not(" + exclusion.join(" and ") + ")]";
  2411. },
  2412. 'nth-child': function(m) {
  2413. return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
  2414. },
  2415. 'nth-last-child': function(m) {
  2416. return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
  2417. },
  2418. 'nth-of-type': function(m) {
  2419. return Selector.xpath.pseudos.nth("position() ", m);
  2420. },
  2421. 'nth-last-of-type': function(m) {
  2422. return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
  2423. },
  2424. 'first-of-type': function(m) {
  2425. m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
  2426. },
  2427. 'last-of-type': function(m) {
  2428. m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
  2429. },
  2430. 'only-of-type': function(m) {
  2431. var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
  2432. },
  2433. nth: function(fragment, m) {
  2434. var mm, formula = m[6], predicate;
  2435. if (formula == 'even') formula = '2n+0';
  2436. if (formula == 'odd') formula = '2n+1';
  2437. if (mm = formula.match(/^(\d+)$/)) // digit only
  2438. return '[' + fragment + "= " + mm[1] + ']';
  2439. if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
  2440. if (mm[1] == "-") mm[1] = -1;
  2441. var a = mm[1] ? Number(mm[1]) : 1;
  2442. var b = mm[2] ? Number(mm[2]) : 0;
  2443. predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
  2444. "((#{fragment} - #{b}) div #{a} >= 0)]";
  2445. return new Template(predicate).evaluate({
  2446. fragment: fragment, a: a, b: b });
  2447. }
  2448. }
  2449. }
  2450. },
  2451. criteria: {
  2452. tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
  2453. className: 'n = h.className(n, r, "#{1}", c); c = false;',
  2454. id: 'n = h.id(n, r, "#{1}", c); c = false;',
  2455. attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;',
  2456. attr: function(m) {
  2457. m[3] = (m[5] || m[6]);
  2458. return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m);
  2459. },
  2460. pseudo: function(m) {
  2461. if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
  2462. return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
  2463. },
  2464. descendant: 'c = "descendant";',
  2465. child: 'c = "child";',
  2466. adjacent: 'c = "adjacent";',
  2467. laterSibling: 'c = "laterSibling";'
  2468. },
  2469. patterns: {
  2470. // combinators must be listed first
  2471. // (and descendant needs to be last combinator)
  2472. laterSibling: /^\s*~\s*/,
  2473. child: /^\s*>\s*/,
  2474. adjacent: /^\s*\+\s*/,
  2475. descendant: /^\s/,
  2476. // selectors follow
  2477. tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
  2478. id: /^#([\w\-\*]+)(\b|$)/,
  2479. className: /^\.([\w\-\*]+)(\b|$)/,
  2480. pseudo:
  2481. /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
  2482. attrPresence: /^\[([\w]+)\]/,
  2483. attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
  2484. },
  2485. // for Selector.match and Element#match
  2486. assertions: {
  2487. tagName: function(element, matches) {
  2488. return matches[1].toUpperCase() == element.tagName.toUpperCase();
  2489. },
  2490. className: function(element, matches) {
  2491. return Element.hasClassName(element, matches[1]);
  2492. },
  2493. id: function(element, matches) {
  2494. return element.id === matches[1];
  2495. },
  2496. attrPresence: function(element, matches) {
  2497. return Element.hasAttribute(element, matches[1]);
  2498. },
  2499. attr: function(element, matches) {
  2500. var nodeValue = Element.readAttribute(element, matches[1]);
  2501. return Selector.operators[matches[2]](nodeValue, matches[3]);
  2502. }
  2503. },
  2504. handlers: {
  2505. // UTILITY FUNCTIONS
  2506. // joins two collections
  2507. concat: function(a, b) {
  2508. for (var i = 0, node; node = b[i]; i++)
  2509. a.push(node);
  2510. return a;
  2511. },
  2512. // marks an array of nodes for counting
  2513. mark: function(nodes) {
  2514. for (var i = 0, node; node = nodes[i]; i++)
  2515. node._counted = true;
  2516. return nodes;
  2517. },
  2518. unmark: function(nodes) {
  2519. for (var i = 0, node; node = nodes[i]; i++)
  2520. node._counted = undefined;
  2521. return nodes;
  2522. },
  2523. // mark each child node with its position (for nth calls)
  2524. // "ofType" flag indicates whether we're indexing for nth-of-type
  2525. // rather than nth-child
  2526. index: function(parentNode, reverse, ofType) {
  2527. parentNode._counted = true;
  2528. if (reverse) {
  2529. for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
  2530. var node = nodes[i];
  2531. if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
  2532. }
  2533. } else {
  2534. for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
  2535. if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
  2536. }
  2537. },
  2538. // filters out duplicates and extends all nodes
  2539. unique: function(nodes) {
  2540. if (nodes.length == 0) return nodes;
  2541. var results = [], n;
  2542. for (var i = 0, l = nodes.length; i < l; i++)
  2543. if (!(n = nodes[i])._counted) {
  2544. n._counted = true;
  2545. results.push(Element.extend(n));
  2546. }
  2547. return Selector.handlers.unmark(results);
  2548. },
  2549. // COMBINATOR FUNCTIONS
  2550. descendant: function(nodes) {
  2551. var h = Selector.handlers;
  2552. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2553. h.concat(results, node.getElementsByTagName('*'));
  2554. return results;
  2555. },
  2556. child: function(nodes) {
  2557. var h = Selector.handlers;
  2558. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2559. for (var j = 0, child; child = node.childNodes[j]; j++)
  2560. if (child.nodeType == 1 && child.tagName != '!') results.push(child);
  2561. }
  2562. return results;
  2563. },
  2564. adjacent: function(nodes) {
  2565. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2566. var next = this.nextElementSibling(node);
  2567. if (next) results.push(next);
  2568. }
  2569. return results;
  2570. },
  2571. laterSibling: function(nodes) {
  2572. var h = Selector.handlers;
  2573. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2574. h.concat(results, Element.nextSiblings(node));
  2575. return results;
  2576. },
  2577. nextElementSibling: function(node) {
  2578. while (node = node.nextSibling)
  2579. if (node.nodeType == 1) return node;
  2580. return null;
  2581. },
  2582. previousElementSibling: function(node) {
  2583. while (node = node.previousSibling)
  2584. if (node.nodeType == 1) return node;
  2585. return null;
  2586. },
  2587. // TOKEN FUNCTIONS
  2588. tagName: function(nodes, root, tagName, combinator) {
  2589. var uTagName = tagName.toUpperCase();
  2590. var results = [], h = Selector.handlers;
  2591. if (nodes) {
  2592. if (combinator) {
  2593. // fastlane for ordinary descendant combinators
  2594. if (combinator == "descendant") {
  2595. for (var i = 0, node; node = nodes[i]; i++)
  2596. h.concat(results, node.getElementsByTagName(tagName));
  2597. return results;
  2598. } else nodes = this[combinator](nodes);
  2599. if (tagName == "*") return nodes;
  2600. }
  2601. for (var i = 0, node; node = nodes[i]; i++)
  2602. if (node.tagName.toUpperCase() === uTagName) results.push(node);
  2603. return results;
  2604. } else return root.getElementsByTagName(tagName);
  2605. },
  2606. id: function(nodes, root, id, combinator) {
  2607. var targetNode = $(id), h = Selector.handlers;
  2608. if (!targetNode) return [];
  2609. if (!nodes && root == document) return [targetNode];
  2610. if (nodes) {
  2611. if (combinator) {
  2612. if (combinator == 'child') {
  2613. for (var i = 0, node; node = nodes[i]; i++)
  2614. if (targetNode.parentNode == node) return [targetNode];
  2615. } else if (combinator == 'descendant') {
  2616. for (var i = 0, node; node = nodes[i]; i++)
  2617. if (Element.descendantOf(targetNode, node)) return [targetNode];
  2618. } else if (combinator == 'adjacent') {
  2619. for (var i = 0, node; node = nodes[i]; i++)
  2620. if (Selector.handlers.previousElementSibling(targetNode) == node)
  2621. return [targetNode];
  2622. } else nodes = h[combinator](nodes);
  2623. }
  2624. for (var i = 0, node; node = nodes[i]; i++)
  2625. if (node == targetNode) return [targetNode];
  2626. return [];
  2627. }
  2628. return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
  2629. },
  2630. className: function(nodes, root, className, combinator) {
  2631. if (nodes && combinator) nodes = this[combinator](nodes);
  2632. return Selector.handlers.byClassName(nodes, root, className);
  2633. },
  2634. byClassName: function(nodes, root, className) {
  2635. if (!nodes) nodes = Selector.handlers.descendant([root]);
  2636. var needle = ' ' + className + ' ';
  2637. for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
  2638. nodeClassName = node.className;
  2639. if (nodeClassName.length == 0) continue;
  2640. if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
  2641. results.push(node);
  2642. }
  2643. return results;
  2644. },
  2645. attrPresence: function(nodes, root, attr) {
  2646. if (!nodes) nodes = root.getElementsByTagName("*");
  2647. var results = [];
  2648. for (var i = 0, node; node = nodes[i]; i++)
  2649. if (Element.hasAttribute(node, attr)) results.push(node);
  2650. return results;
  2651. },
  2652. attr: function(nodes, root, attr, value, operator) {
  2653. if (!nodes) nodes = root.getElementsByTagName("*");
  2654. var handler = Selector.operators[operator], results = [];
  2655. for (var i = 0, node; node = nodes[i]; i++) {
  2656. var nodeValue = Element.readAttribute(node, attr);
  2657. if (nodeValue === null) continue;
  2658. if (handler(nodeValue, value)) results.push(node);
  2659. }
  2660. return results;
  2661. },
  2662. pseudo: function(nodes, name, value, root, combinator) {
  2663. if (nodes && combinator) nodes = this[combinator](nodes);
  2664. if (!nodes) nodes = root.getElementsByTagName("*");
  2665. return Selector.pseudos[name](nodes, value, root);
  2666. }
  2667. },
  2668. pseudos: {
  2669. 'first-child': function(nodes, value, root) {
  2670. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2671. if (Selector.handlers.previousElementSibling(node)) continue;
  2672. results.push(node);
  2673. }
  2674. return results;
  2675. },
  2676. 'last-child': function(nodes, value, root) {
  2677. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2678. if (Selector.handlers.nextElementSibling(node)) continue;
  2679. results.push(node);
  2680. }
  2681. return results;
  2682. },
  2683. 'only-child': function(nodes, value, root) {
  2684. var h = Selector.handlers;
  2685. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2686. if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
  2687. results.push(node);
  2688. return results;
  2689. },
  2690. 'nth-child': function(nodes, formula, root) {
  2691. return Selector.pseudos.nth(nodes, formula, root);
  2692. },
  2693. 'nth-last-child': function(nodes, formula, root) {
  2694. return Selector.pseudos.nth(nodes, formula, root, true);
  2695. },
  2696. 'nth-of-type': function(nodes, formula, root) {
  2697. return Selector.pseudos.nth(nodes, formula, root, false, true);
  2698. },
  2699. 'nth-last-of-type': function(nodes, formula, root) {
  2700. return Selector.pseudos.nth(nodes, formula, root, true, true);
  2701. },
  2702. 'first-of-type': function(nodes, formula, root) {
  2703. return Selector.pseudos.nth(nodes, "1", root, false, true);
  2704. },
  2705. 'last-of-type': function(nodes, formula, root) {
  2706. return Selector.pseudos.nth(nodes, "1", root, true, true);
  2707. },
  2708. 'only-of-type': function(nodes, formula, root) {
  2709. var p = Selector.pseudos;
  2710. return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
  2711. },
  2712. // handles the an+b logic
  2713. getIndices: function(a, b, total) {
  2714. if (a == 0) return b > 0 ? [b] : [];
  2715. return $R(1, total).inject([], function(memo, i) {
  2716. if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
  2717. return memo;
  2718. });
  2719. },
  2720. // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
  2721. nth: function(nodes, formula, root, reverse, ofType) {
  2722. if (nodes.length == 0) return [];
  2723. if (formula == 'even') formula = '2n+0';
  2724. if (formula == 'odd') formula = '2n+1';
  2725. var h = Selector.handlers, results = [], indexed = [], m;
  2726. h.mark(nodes);
  2727. for (var i = 0, node; node = nodes[i]; i++) {
  2728. if (!node.parentNode._counted) {
  2729. h.index(node.parentNode, reverse, ofType);
  2730. indexed.push(node.parentNode);
  2731. }
  2732. }
  2733. if (formula.match(/^\d+$/)) { // just a number
  2734. formula = Number(formula);
  2735. for (var i = 0, node; node = nodes[i]; i++)
  2736. if (node.nodeIndex == formula) results.push(node);
  2737. } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
  2738. if (m[1] == "-") m[1] = -1;
  2739. var a = m[1] ? Number(m[1]) : 1;
  2740. var b = m[2] ? Number(m[2]) : 0;
  2741. var indices = Selector.pseudos.getIndices(a, b, nodes.length);
  2742. for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
  2743. for (var j = 0; j < l; j++)
  2744. if (node.nodeIndex == indices[j]) results.push(node);
  2745. }
  2746. }
  2747. h.unmark(nodes);
  2748. h.unmark(indexed);
  2749. return results;
  2750. },
  2751. 'empty': function(nodes, value, root) {
  2752. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2753. // IE treats comments as element nodes
  2754. if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
  2755. results.push(node);
  2756. }
  2757. return results;
  2758. },
  2759. 'not': function(nodes, selector, root) {
  2760. var h = Selector.handlers, selectorType, m;
  2761. var exclusions = new Selector(selector).findElements(root);
  2762. h.mark(exclusions);
  2763. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2764. if (!node._counted) results.push(node);
  2765. h.unmark(exclusions);
  2766. return results;
  2767. },
  2768. 'enabled': function(nodes, value, root) {
  2769. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2770. if (!node.disabled) results.push(node);
  2771. return results;
  2772. },
  2773. 'disabled': function(nodes, value, root) {
  2774. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2775. if (node.disabled) results.push(node);
  2776. return results;
  2777. },
  2778. 'checked': function(nodes, value, root) {
  2779. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2780. if (node.checked) results.push(node);
  2781. return results;
  2782. }
  2783. },
  2784. operators: {
  2785. '=': function(nv, v) { return nv == v; },
  2786. '!=': function(nv, v) { return nv != v; },
  2787. '^=': function(nv, v) { return nv.startsWith(v); },
  2788. '$=': function(nv, v) { return nv.endsWith(v); },
  2789. '*=': function(nv, v) { return nv.include(v); },
  2790. '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
  2791. '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
  2792. },
  2793. matchElements: function(elements, expression) {
  2794. var matches = new Selector(expression).findElements(), h = Selector.handlers;
  2795. h.mark(matches);
  2796. for (var i = 0, results = [], element; element = elements[i]; i++)
  2797. if (element._counted) results.push(element);
  2798. h.unmark(matches);
  2799. return results;
  2800. },
  2801. findElement: function(elements, expression, index) {
  2802. if (Object.isNumber(expression)) {
  2803. index = expression; expression = false;
  2804. }
  2805. return Selector.matchElements(elements, expression || '*')[index || 0];
  2806. },
  2807. findChildElements: function(element, expressions) {
  2808. var exprs = expressions.join(',');
  2809. expressions = [];
  2810. exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
  2811. expressions.push(m[1].strip());
  2812. });
  2813. var results = [], h = Selector.handlers;
  2814. for (var i = 0, l = expressions.length, selector; i < l; i++) {
  2815. selector = new Selector(expressions[i].strip());
  2816. h.concat(results, selector.findElements(element));
  2817. }
  2818. return (l > 1) ? h.unique(results) : results;
  2819. }
  2820. });
  2821. if (Prototype.Browser.IE) {
  2822. // IE returns comment nodes on getElementsByTagName("*").
  2823. // Filter them out.
  2824. Selector.handlers.concat = function(a, b) {
  2825. for (var i = 0, node; node = b[i]; i++)
  2826. if (node.tagName !== "!") a.push(node);
  2827. return a;
  2828. };
  2829. }
  2830. function $$() {
  2831. return Selector.findChildElements(document, $A(arguments));
  2832. }
  2833. var Form = {
  2834. reset: function(form) {
  2835. $(form).reset();
  2836. return form;
  2837. },
  2838. serializeElements: function(elements, options) {
  2839. if (typeof options != 'object') options = { hash: !!options };
  2840. else if (Object.isUndefined(options.hash)) options.hash = true;
  2841. var key, value, submitted = false, submit = options.submit;
  2842. var data = elements.inject({ }, function(result, element) {
  2843. if (!element.disabled && element.name) {
  2844. key = element.name; value = $(element).getValue();
  2845. if (value != null && (element.type != 'submit' || (!submitted &&
  2846. submit !== false && (!submit || key == submit) && (submitted = true)))) {
  2847. if (key in result) {
  2848. // a key is already present; construct an array of values
  2849. if (!Object.isArray(result[key])) result[key] = [result[key]];
  2850. result[key].push(value);
  2851. }
  2852. else result[key] = value;
  2853. }
  2854. }
  2855. return result;
  2856. });
  2857. return options.hash ? data : Object.toQueryString(data);
  2858. }
  2859. };
  2860. Form.Methods = {
  2861. serialize: function(form, options) {
  2862. return Form.serializeElements(Form.getElements(form), options);
  2863. },
  2864. getElements: function(form) {
  2865. return $A($(form).getElementsByTagName('*')).inject([],
  2866. function(elements, child) {
  2867. if (Form.Element.Serializers[child.tagName.toLowerCase()])
  2868. elements.push(Element.extend(child));
  2869. return elements;
  2870. }
  2871. );
  2872. },
  2873. getInputs: function(form, typeName, name) {
  2874. form = $(form);
  2875. var inputs = form.getElementsByTagName('input');
  2876. if (!typeName && !name) return $A(inputs).map(Element.extend);
  2877. for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
  2878. var input = inputs[i];
  2879. if ((typeName && input.type != typeName) || (name && input.name != name))
  2880. continue;
  2881. matchingInputs.push(Element.extend(input));
  2882. }
  2883. return matchingInputs;
  2884. },
  2885. disable: function(form) {
  2886. form = $(form);
  2887. Form.getElements(form).invoke('disable');
  2888. return form;
  2889. },
  2890. enable: function(form) {
  2891. form = $(form);
  2892. Form.getElements(form).invoke('enable');
  2893. return form;
  2894. },
  2895. findFirstElement: function(form) {
  2896. var elements = $(form).getElements().findAll(function(element) {
  2897. return 'hidden' != element.type && !element.disabled;
  2898. });
  2899. var firstByIndex = elements.findAll(function(element) {
  2900. return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
  2901. }).sortBy(function(element) { return element.tabIndex }).first();
  2902. return firstByIndex ? firstByIndex : elements.find(function(element) {
  2903. return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
  2904. });
  2905. },
  2906. focusFirstElement: function(form) {
  2907. form = $(form);
  2908. form.findFirstElement().activate();
  2909. return form;
  2910. },
  2911. request: function(form, options) {
  2912. form = $(form), options = Object.clone(options || { });
  2913. var params = options.parameters, action = form.readAttribute('action') || '';
  2914. if (action.blank()) action = window.location.href;
  2915. options.parameters = form.serialize(true);
  2916. if (params) {
  2917. if (Object.isString(params)) params = params.toQueryParams();
  2918. Object.extend(options.parameters, params);
  2919. }
  2920. if (form.hasAttribute('method') && !options.method)
  2921. options.method = form.method;
  2922. return new Ajax.Request(action, options);
  2923. }
  2924. };
  2925. /*--------------------------------------------------------------------------*/
  2926. Form.Element = {
  2927. focus: function(element) {
  2928. $(element).focus();
  2929. return element;
  2930. },
  2931. select: function(element) {
  2932. $(element).select();
  2933. return element;
  2934. }
  2935. };
  2936. Form.Element.Methods = {
  2937. serialize: function(element) {
  2938. element = $(element);
  2939. if (!element.disabled && element.name) {
  2940. var value = element.getValue();
  2941. if (value != undefined) {
  2942. var pair = { };
  2943. pair[element.name] = value;
  2944. return Object.toQueryString(pair);
  2945. }
  2946. }
  2947. return '';
  2948. },
  2949. getValue: function(element) {
  2950. element = $(element);
  2951. var method = element.tagName.toLowerCase();
  2952. return Form.Element.Serializers[method](element);
  2953. },
  2954. setValue: function(element, value) {
  2955. element = $(element);
  2956. var method = element.tagName.toLowerCase();
  2957. Form.Element.Serializers[method](element, value);
  2958. return element;
  2959. },
  2960. clear: function(element) {
  2961. $(element).value = '';
  2962. return element;
  2963. },
  2964. present: function(element) {
  2965. return $(element).value != '';
  2966. },
  2967. activate: function(element) {
  2968. element = $(element);
  2969. try {
  2970. element.focus();
  2971. if (element.select && (element.tagName.toLowerCase() != 'input' ||
  2972. !['button', 'reset', 'submit'].include(element.type)))
  2973. element.select();
  2974. } catch (e) { }
  2975. return element;
  2976. },
  2977. disable: function(element) {
  2978. element = $(element);
  2979. element.blur();
  2980. element.disabled = true;
  2981. return element;
  2982. },
  2983. enable: function(element) {
  2984. element = $(element);
  2985. element.disabled = false;
  2986. return element;
  2987. }
  2988. };
  2989. /*--------------------------------------------------------------------------*/
  2990. var Field = Form.Element;
  2991. var $F = Form.Element.Methods.getValue;
  2992. /*--------------------------------------------------------------------------*/
  2993. Form.Element.Serializers = {
  2994. input: function(element, value) {
  2995. switch (element.type.toLowerCase()) {
  2996. case 'checkbox':
  2997. case 'radio':
  2998. return Form.Element.Serializers.inputSelector(element, value);
  2999. default:
  3000. return Form.Element.Serializers.textarea(element, value);
  3001. }
  3002. },
  3003. inputSelector: function(element, value) {
  3004. if (Object.isUndefined(value)) return element.checked ? element.value : null;
  3005. else element.checked = !!value;
  3006. },
  3007. textarea: function(element, value) {
  3008. if (Object.isUndefined(value)) return element.value;
  3009. else element.value = value;
  3010. },
  3011. select: function(element, index) {
  3012. if (Object.isUndefined(index))
  3013. return this[element.type == 'select-one' ?
  3014. 'selectOne' : 'selectMany'](element);
  3015. else {
  3016. var opt, value, single = !Object.isArray(index);
  3017. for (var i = 0, length = element.length; i < length; i++) {
  3018. opt = element.options[i];
  3019. value = this.optionValue(opt);
  3020. if (single) {
  3021. if (value == index) {
  3022. opt.selected = true;
  3023. return;
  3024. }
  3025. }
  3026. else opt.selected = index.include(value);
  3027. }
  3028. }
  3029. },
  3030. selectOne: function(element) {
  3031. var index = element.selectedIndex;
  3032. return index >= 0 ? this.optionValue(element.options[index]) : null;
  3033. },
  3034. selectMany: function(element) {
  3035. var values, length = element.length;
  3036. if (!length) return null;
  3037. for (var i = 0, values = []; i < length; i++) {
  3038. var opt = element.options[i];
  3039. if (opt.selected) values.push(this.optionValue(opt));
  3040. }
  3041. return values;
  3042. },
  3043. optionValue: function(opt) {
  3044. // extend element because hasAttribute may not be native
  3045. return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  3046. }
  3047. };
  3048. /*--------------------------------------------------------------------------*/
  3049. Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
  3050. initialize: function($super, element, frequency, callback) {
  3051. $super(callback, frequency);
  3052. this.element = $(element);
  3053. this.lastValue = this.getValue();
  3054. },
  3055. execute: function() {
  3056. var value = this.getValue();
  3057. if (Object.isString(this.lastValue) && Object.isString(value) ?
  3058. this.lastValue != value : String(this.lastValue) != String(value)) {
  3059. this.callback(this.element, value);
  3060. this.lastValue = value;
  3061. }
  3062. }
  3063. });
  3064. Form.Element.Observer = Class.create(Abstract.TimedObserver, {
  3065. getValue: function() {
  3066. return Form.Element.getValue(this.element);
  3067. }
  3068. });
  3069. Form.Observer = Class.create(Abstract.TimedObserver, {
  3070. getValue: function() {
  3071. return Form.serialize(this.element);
  3072. }
  3073. });
  3074. /*--------------------------------------------------------------------------*/
  3075. Abstract.EventObserver = Class.create({
  3076. initialize: function(element, callback) {
  3077. this.element = $(element);
  3078. this.callback = callback;
  3079. this.lastValue = this.getValue();
  3080. if (this.element.tagName.toLowerCase() == 'form')
  3081. this.registerFormCallbacks();
  3082. else
  3083. this.registerCallback(this.element);
  3084. },
  3085. onElementEvent: function() {
  3086. var value = this.getValue();
  3087. if (this.lastValue != value) {
  3088. this.callback(this.element, value);
  3089. this.lastValue = value;
  3090. }
  3091. },
  3092. registerFormCallbacks: function() {
  3093. Form.getElements(this.element).each(this.registerCallback, this);
  3094. },
  3095. registerCallback: function(element) {
  3096. if (element.type) {
  3097. switch (element.type.toLowerCase()) {
  3098. case 'checkbox':
  3099. case 'radio':
  3100. Event.observe(element, 'click', this.onElementEvent.bind(this));
  3101. break;
  3102. default:
  3103. Event.observe(element, 'change', this.onElementEvent.bind(this));
  3104. break;
  3105. }
  3106. }
  3107. }
  3108. });
  3109. Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
  3110. getValue: function() {
  3111. return Form.Element.getValue(this.element);
  3112. }
  3113. });
  3114. Form.EventObserver = Class.create(Abstract.EventObserver, {
  3115. getValue: function() {
  3116. return Form.serialize(this.element);
  3117. }
  3118. });
  3119. if (!window.Event) var Event = { };
  3120. Object.extend(Event, {
  3121. KEY_BACKSPACE: 8,
  3122. KEY_TAB: 9,
  3123. KEY_RETURN: 13,
  3124. KEY_ESC: 27,
  3125. KEY_LEFT: 37,
  3126. KEY_UP: 38,
  3127. KEY_RIGHT: 39,
  3128. KEY_DOWN: 40,
  3129. KEY_DELETE: 46,
  3130. KEY_HOME: 36,
  3131. KEY_END: 35,
  3132. KEY_PAGEUP: 33,
  3133. KEY_PAGEDOWN: 34,
  3134. KEY_INSERT: 45,
  3135. cache: { },
  3136. relatedTarget: function(event) {
  3137. var element;
  3138. switch(event.type) {
  3139. case 'mouseover': element = event.fromElement; break;
  3140. case 'mouseout': element = event.toElement; break;
  3141. default: return null;
  3142. }
  3143. return Element.extend(element);
  3144. }
  3145. });
  3146. Event.Methods = (function() {
  3147. var isButton;
  3148. if (Prototype.Browser.IE) {
  3149. var buttonMap = { 0: 1, 1: 4, 2: 2 };
  3150. isButton = function(event, code) {
  3151. return event.button == buttonMap[code];
  3152. };
  3153. } else if (Prototype.Browser.WebKit) {
  3154. isButton = function(event, code) {
  3155. switch (code) {
  3156. case 0: return event.which == 1 && !event.metaKey;
  3157. case 1: return event.which == 1 && event.metaKey;
  3158. default: return false;
  3159. }
  3160. };
  3161. } else {
  3162. isButton = function(event, code) {
  3163. return event.which ? (event.which === code + 1) : (event.button === code);
  3164. };
  3165. }
  3166. return {
  3167. isLeftClick: function(event) { return isButton(event, 0) },
  3168. isMiddleClick: function(event) { return isButton(event, 1) },
  3169. isRightClick: function(event) { return isButton(event, 2) },
  3170. element: function(event) {
  3171. var node = Event.extend(event).target;
  3172. return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
  3173. },
  3174. findElement: function(event, expression) {
  3175. var element = Event.element(event);
  3176. if (!expression) return element;
  3177. var elements = [element].concat(element.ancestors());
  3178. return Selector.findElement(elements, expression, 0);
  3179. },
  3180. pointer: function(event) {
  3181. return {
  3182. x: event.pageX || (event.clientX +
  3183. (document.documentElement.scrollLeft || document.body.scrollLeft)),
  3184. y: event.pageY || (event.clientY +
  3185. (document.documentElement.scrollTop || document.body.scrollTop))
  3186. };
  3187. },
  3188. pointerX: function(event) { return Event.pointer(event).x },
  3189. pointerY: function(event) { return Event.pointer(event).y },
  3190. stop: function(event) {
  3191. Event.extend(event);
  3192. event.preventDefault();
  3193. event.stopPropagation();
  3194. event.stopped = true;
  3195. }
  3196. };
  3197. })();
  3198. Event.extend = (function() {
  3199. var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
  3200. m[name] = Event.Methods[name].methodize();
  3201. return m;
  3202. });
  3203. if (Prototype.Browser.IE) {
  3204. Object.extend(methods, {
  3205. stopPropagation: function() { this.cancelBubble = true },
  3206. preventDefault: function() { this.returnValue = false },
  3207. inspect: function() { return "[object Event]" }
  3208. });
  3209. return function(event) {
  3210. if (!event) return false;
  3211. if (event._extendedByPrototype) return event;
  3212. event._extendedByPrototype = Prototype.emptyFunction;
  3213. var pointer = Event.pointer(event);
  3214. Object.extend(event, {
  3215. target: event.srcElement,
  3216. relatedTarget: Event.relatedTarget(event),
  3217. pageX: pointer.x,
  3218. pageY: pointer.y
  3219. });
  3220. return Object.extend(event, methods);
  3221. };
  3222. } else {
  3223. Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
  3224. Object.extend(Event.prototype, methods);
  3225. return Prototype.K;
  3226. }
  3227. })();
  3228. Object.extend(Event, (function() {
  3229. var cache = Event.cache;
  3230. function getEventID(element) {
  3231. if (element._eventID) return element._eventID;
  3232. arguments.callee.id = arguments.callee.id || 1;
  3233. return element._eventID = ++arguments.callee.id;
  3234. }
  3235. function getDOMEventName(eventName) {
  3236. if (eventName && eventName.include(':')) return "dataavailable";
  3237. return eventName;
  3238. }
  3239. function getCacheForID(id) {
  3240. return cache[id] = cache[id] || { };
  3241. }
  3242. function getWrappersForEventName(id, eventName) {
  3243. var c = getCacheForID(id);
  3244. return c[eventName] = c[eventName] || [];
  3245. }
  3246. function createWrapper(element, eventName, handler) {
  3247. var id = getEventID(element);
  3248. var c = getWrappersForEventName(id, eventName);
  3249. if (c.pluck("handler").include(handler)) return false;
  3250. var wrapper = function(event) {
  3251. if (!Event || !Event.extend ||
  3252. (event.eventName && event.eventName != eventName))
  3253. return false;
  3254. Event.extend(event);
  3255. handler.call(element, event);
  3256. };
  3257. wrapper.handler = handler;
  3258. c.push(wrapper);
  3259. return wrapper;
  3260. }
  3261. function findWrapper(id, eventName, handler) {
  3262. var c = getWrappersForEventName(id, eventName);
  3263. return c.find(function(wrapper) { return wrapper.handler == handler });
  3264. }
  3265. function destroyWrapper(id, eventName, handler) {
  3266. var c = getCacheForID(id);
  3267. if (!c[eventName]) return false;
  3268. c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
  3269. }
  3270. function destroyCache() {
  3271. for (var id in cache)
  3272. for (var eventName in cache[id])
  3273. cache[id][eventName] = null;
  3274. }
  3275. if (window.attachEvent) {
  3276. window.attachEvent("onunload", destroyCache);
  3277. }
  3278. return {
  3279. observe: function(element, eventName, handler) {
  3280. element = $(element);
  3281. var name = getDOMEventName(eventName);
  3282. var wrapper = createWrapper(element, eventName, handler);
  3283. if (!wrapper) return element;
  3284. if (element.addEventListener) {
  3285. element.addEventListener(name, wrapper, false);
  3286. } else {
  3287. element.attachEvent("on" + name, wrapper);
  3288. }
  3289. return element;
  3290. },
  3291. stopObserving: function(element, eventName, handler) {
  3292. element = $(element);
  3293. var id = getEventID(element), name = getDOMEventName(eventName);
  3294. if (!handler && eventName) {
  3295. getWrappersForEventName(id, eventName).each(function(wrapper) {
  3296. element.stopObserving(eventName, wrapper.handler);
  3297. });
  3298. return element;
  3299. } else if (!eventName) {
  3300. Object.keys(getCacheForID(id)).each(function(eventName) {
  3301. element.stopObserving(eventName);
  3302. });
  3303. return element;
  3304. }
  3305. var wrapper = findWrapper(id, eventName, handler);
  3306. if (!wrapper) return element;
  3307. if (element.removeEventListener) {
  3308. element.removeEventListener(name, wrapper, false);
  3309. } else {
  3310. element.detachEvent("on" + name, wrapper);
  3311. }
  3312. destroyWrapper(id, eventName, handler);
  3313. return element;
  3314. },
  3315. fire: function(element, eventName, memo) {
  3316. element = $(element);
  3317. if (element == document && document.createEvent && !element.dispatchEvent)
  3318. element = document.documentElement;
  3319. var event;
  3320. if (document.createEvent) {
  3321. event = document.createEvent("HTMLEvents");
  3322. event.initEvent("dataavailable", true, true);
  3323. } else {
  3324. event = document.createEventObject();
  3325. event.eventType = "ondataavailable";
  3326. }
  3327. event.eventName = eventName;
  3328. event.memo = memo || { };
  3329. if (document.createEvent) {
  3330. element.dispatchEvent(event);
  3331. } else {
  3332. element.fireEvent(event.eventType, event);
  3333. }
  3334. return Event.extend(event);
  3335. }
  3336. };
  3337. })());
  3338. Object.extend(Event, Event.Methods);
  3339. Element.addMethods({
  3340. fire: Event.fire,
  3341. observe: Event.observe,
  3342. stopObserving: Event.stopObserving
  3343. });
  3344. Object.extend(document, {
  3345. fire: Element.Methods.fire.methodize(),
  3346. observe: Element.Methods.observe.methodize(),
  3347. stopObserving: Element.Methods.stopObserving.methodize(),
  3348. loaded: false
  3349. });
  3350. (function() {
  3351. /* Support for the DOMContentLoaded event is based on work by Dan Webb,
  3352. Matthias Miller, Dean Edwards and John Resig. */
  3353. var timer;
  3354. function fireContentLoadedEvent() {
  3355. if (document.loaded) return;
  3356. if (timer) window.clearInterval(timer);
  3357. document.fire("dom:loaded");
  3358. document.loaded = true;
  3359. }
  3360. if (document.addEventListener) {
  3361. if (Prototype.Browser.WebKit) {
  3362. timer = window.setInterval(function() {
  3363. if (/loaded|complete/.test(document.readyState))
  3364. fireContentLoadedEvent();
  3365. }, 0);
  3366. Event.observe(window, "load", fireContentLoadedEvent);
  3367. } else {
  3368. document.addEventListener("DOMContentLoaded",
  3369. fireContentLoadedEvent, false);
  3370. }
  3371. } else {
  3372. document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
  3373. $("__onDOMContentLoaded").onreadystatechange = function() {
  3374. if (this.readyState == "complete") {
  3375. this.onreadystatechange = null;
  3376. fireContentLoadedEvent();
  3377. }
  3378. };
  3379. }
  3380. })();
  3381. /*------------------------------- DEPRECATED -------------------------------*/
  3382. Hash.toQueryString = Object.toQueryString;
  3383. var Toggle = { display: Element.toggle };
  3384. Element.Methods.childOf = Element.Methods.descendantOf;
  3385. var Insertion = {
  3386. Before: function(element, content) {
  3387. return Element.insert(element, {before:content});
  3388. },
  3389. Top: function(element, content) {
  3390. return Element.insert(element, {top:content});
  3391. },
  3392. Bottom: function(element, content) {
  3393. return Element.insert(element, {bottom:content});
  3394. },
  3395. After: function(element, content) {
  3396. return Element.insert(element, {after:content});
  3397. }
  3398. };
  3399. var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
  3400. // This should be moved to script.aculo.us; notice the deprecated methods
  3401. // further below, that map to the newer Element methods.
  3402. var Position = {
  3403. // set to true if needed, warning: firefox performance problems
  3404. // NOT neeeded for page scrolling, only if draggable contained in
  3405. // scrollable elements
  3406. includeScrollOffsets: false,
  3407. // must be called before calling withinIncludingScrolloffset, every time the
  3408. // page is scrolled
  3409. prepare: function() {
  3410. this.deltaX = window.pageXOffset
  3411. || document.documentElement.scrollLeft
  3412. || document.body.scrollLeft
  3413. || 0;
  3414. this.deltaY = window.pageYOffset
  3415. || document.documentElement.scrollTop
  3416. || document.body.scrollTop
  3417. || 0;
  3418. },
  3419. // caches x/y coordinate pair to use with overlap
  3420. within: function(element, x, y) {
  3421. if (this.includeScrollOffsets)
  3422. return this.withinIncludingScrolloffsets(element, x, y);
  3423. this.xcomp = x;
  3424. this.ycomp = y;
  3425. this.offset = Element.cumulativeOffset(element);
  3426. return (y >= this.offset[1] &&
  3427. y < this.offset[1] + element.offsetHeight &&
  3428. x >= this.offset[0] &&
  3429. x < this.offset[0] + element.offsetWidth);
  3430. },
  3431. withinIncludingScrolloffsets: function(element, x, y) {
  3432. var offsetcache = Element.cumulativeScrollOffset(element);
  3433. this.xcomp = x + offsetcache[0] - this.deltaX;
  3434. this.ycomp = y + offsetcache[1] - this.deltaY;
  3435. this.offset = Element.cumulativeOffset(element);
  3436. return (this.ycomp >= this.offset[1] &&
  3437. this.ycomp < this.offset[1] + element.offsetHeight &&
  3438. this.xcomp >= this.offset[0] &&
  3439. this.xcomp < this.offset[0] + element.offsetWidth);
  3440. },
  3441. // within must be called directly before
  3442. overlap: function(mode, element) {
  3443. if (!mode) return 0;
  3444. if (mode == 'vertical')
  3445. return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
  3446. element.offsetHeight;
  3447. if (mode == 'horizontal')
  3448. return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
  3449. element.offsetWidth;
  3450. },
  3451. // Deprecation layer -- use newer Element methods now (1.5.2).
  3452. cumulativeOffset: Element.Methods.cumulativeOffset,
  3453. positionedOffset: Element.Methods.positionedOffset,
  3454. absolutize: function(element) {
  3455. Position.prepare();
  3456. return Element.absolutize(element);
  3457. },
  3458. relativize: function(element) {
  3459. Position.prepare();
  3460. return Element.relativize(element);
  3461. },
  3462. realOffset: Element.Methods.cumulativeScrollOffset,
  3463. offsetParent: Element.Methods.getOffsetParent,
  3464. page: Element.Methods.viewportOffset,
  3465. clone: function(source, target, options) {
  3466. options = options || { };
  3467. return Element.clonePosition(target, source, options);
  3468. }
  3469. };
  3470. /*--------------------------------------------------------------------------*/
  3471. if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
  3472. function iter(name) {
  3473. return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
  3474. }
  3475. instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
  3476. function(element, className) {
  3477. className = className.toString().strip();
  3478. var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
  3479. return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
  3480. } : function(element, className) {
  3481. className = className.toString().strip();
  3482. var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
  3483. if (!classNames && !className) return elements;
  3484. var nodes = $(element).getElementsByTagName('*');
  3485. className = ' ' + className + ' ';
  3486. for (var i = 0, child, cn; child = nodes[i]; i++) {
  3487. if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
  3488. (classNames && classNames.all(function(name) {
  3489. return !name.toString().blank() && cn.include(' ' + name + ' ');
  3490. }))))
  3491. elements.push(Element.extend(child));
  3492. }
  3493. return elements;
  3494. };
  3495. return function(className, parentElement) {
  3496. return $(parentElement || document.body).getElementsByClassName(className);
  3497. };
  3498. }(Element.Methods);
  3499. /*--------------------------------------------------------------------------*/
  3500. Element.ClassNames = Class.create();
  3501. Element.ClassNames.prototype = {
  3502. initialize: function(element) {
  3503. this.element = $(element);
  3504. },
  3505. _each: function(iterator) {
  3506. this.element.className.split(/\s+/).select(function(name) {
  3507. return name.length > 0;
  3508. })._each(iterator);
  3509. },
  3510. set: function(className) {
  3511. this.element.className = className;
  3512. },
  3513. add: function(classNameToAdd) {
  3514. if (this.include(classNameToAdd)) return;
  3515. this.set($A(this).concat(classNameToAdd).join(' '));
  3516. },
  3517. remove: function(classNameToRemove) {
  3518. if (!this.include(classNameToRemove)) return;
  3519. this.set($A(this).without(classNameToRemove).join(' '));
  3520. },
  3521. toString: function() {
  3522. return $A(this).join(' ');
  3523. }
  3524. };
  3525. Object.extend(Element.ClassNames.prototype, Enumerable);
  3526. /*--------------------------------------------------------------------------*/
  3527. Element.addMethods();