v8-raytrace.html 97 KB

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