michael@0: // The ray tracer code in this file is written by Adam Burmister. It michael@0: // is available in its original form from: michael@0: // michael@0: // http://labs.flog.nz.co/raytracer/ michael@0: // michael@0: // It has been modified slightly by Google to work as a standalone michael@0: // benchmark, but the all the computational code remains michael@0: // untouched. This file also contains a copy of the Prototype michael@0: // JavaScript framework which is used by the ray tracer. michael@0: michael@0: var RayTrace = new BenchmarkSuite('RayTrace', 932666, [ michael@0: new Benchmark('RayTrace', renderScene) michael@0: ]); michael@0: michael@0: michael@0: // Create dummy objects if we're not running in a browser. michael@0: if (typeof document == 'undefined') { michael@0: document = { }; michael@0: window = { opera: null }; michael@0: navigator = { userAgent: null, appVersion: "" }; michael@0: } michael@0: michael@0: michael@0: // ------------------------------------------------------------------------ michael@0: // ------------------------------------------------------------------------ michael@0: michael@0: michael@0: /* Prototype JavaScript framework, version 1.5.0 michael@0: * (c) 2005-2007 Sam Stephenson michael@0: * michael@0: * Prototype is freely distributable under the terms of an MIT-style license. michael@0: * For details, see the Prototype web site: http://prototype.conio.net/ michael@0: * michael@0: /*--------------------------------------------------------------------------*/ michael@0: michael@0: //-------------------- michael@0: var Prototype = { michael@0: Version: '1.5.0', michael@0: BrowserFeatures: { michael@0: XPath: !!document.evaluate michael@0: }, michael@0: michael@0: ScriptFragment: '(?:)((\n|\r|.)*?)(?:<\/script>)', michael@0: emptyFunction: function() {}, michael@0: K: function(x) { return x } michael@0: } michael@0: michael@0: var Class = { michael@0: create: function() { michael@0: return function() { michael@0: this.initialize.apply(this, arguments); michael@0: } michael@0: } michael@0: } michael@0: michael@0: var Abstract = new Object(); michael@0: michael@0: Object.extend = function(destination, source) { michael@0: for (var property in source) { michael@0: destination[property] = source[property]; michael@0: } michael@0: return destination; michael@0: } michael@0: michael@0: Object.extend(Object, { michael@0: inspect: function(object) { michael@0: try { michael@0: if (object === undefined) return 'undefined'; michael@0: if (object === null) return 'null'; michael@0: return object.inspect ? object.inspect() : object.toString(); michael@0: } catch (e) { michael@0: if (e instanceof RangeError) return '...'; michael@0: throw e; michael@0: } michael@0: }, michael@0: michael@0: keys: function(object) { michael@0: var keys = []; michael@0: for (var property in object) michael@0: keys.push(property); michael@0: return keys; michael@0: }, michael@0: michael@0: values: function(object) { michael@0: var values = []; michael@0: for (var property in object) michael@0: values.push(object[property]); michael@0: return values; michael@0: }, michael@0: michael@0: clone: function(object) { michael@0: return Object.extend({}, object); michael@0: } michael@0: }); michael@0: michael@0: Function.prototype.bind = function() { michael@0: var __method = this, args = $A(arguments), object = args.shift(); michael@0: return function() { michael@0: return __method.apply(object, args.concat($A(arguments))); michael@0: } michael@0: } michael@0: michael@0: Function.prototype.bindAsEventListener = function(object) { michael@0: var __method = this, args = $A(arguments), object = args.shift(); michael@0: return function(event) { michael@0: return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments))); michael@0: } michael@0: } michael@0: michael@0: Object.extend(Number.prototype, { michael@0: toColorPart: function() { michael@0: var digits = this.toString(16); michael@0: if (this < 16) return '0' + digits; michael@0: return digits; michael@0: }, michael@0: michael@0: succ: function() { michael@0: return this + 1; michael@0: }, michael@0: michael@0: times: function(iterator) { michael@0: $R(0, this, true).each(iterator); michael@0: return this; michael@0: } michael@0: }); michael@0: michael@0: var Try = { michael@0: these: function() { michael@0: var returnValue; michael@0: michael@0: for (var i = 0, length = arguments.length; i < length; i++) { michael@0: var lambda = arguments[i]; michael@0: try { michael@0: returnValue = lambda(); michael@0: break; michael@0: } catch (e) {} michael@0: } michael@0: michael@0: return returnValue; michael@0: } michael@0: } michael@0: michael@0: /*--------------------------------------------------------------------------*/ michael@0: michael@0: var PeriodicalExecuter = Class.create(); michael@0: PeriodicalExecuter.prototype = { michael@0: initialize: function(callback, frequency) { michael@0: this.callback = callback; michael@0: this.frequency = frequency; michael@0: this.currentlyExecuting = false; michael@0: michael@0: this.registerCallback(); michael@0: }, michael@0: michael@0: registerCallback: function() { michael@0: this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); michael@0: }, michael@0: michael@0: stop: function() { michael@0: if (!this.timer) return; michael@0: clearInterval(this.timer); michael@0: this.timer = null; michael@0: }, michael@0: michael@0: onTimerEvent: function() { michael@0: if (!this.currentlyExecuting) { michael@0: try { michael@0: this.currentlyExecuting = true; michael@0: this.callback(this); michael@0: } finally { michael@0: this.currentlyExecuting = false; michael@0: } michael@0: } michael@0: } michael@0: } michael@0: String.interpret = function(value){ michael@0: return value == null ? '' : String(value); michael@0: } michael@0: michael@0: Object.extend(String.prototype, { michael@0: gsub: function(pattern, replacement) { michael@0: var result = '', source = this, match; michael@0: replacement = arguments.callee.prepareReplacement(replacement); michael@0: michael@0: while (source.length > 0) { michael@0: if (match = source.match(pattern)) { michael@0: result += source.slice(0, match.index); michael@0: result += String.interpret(replacement(match)); michael@0: source = source.slice(match.index + match[0].length); michael@0: } else { michael@0: result += source, source = ''; michael@0: } michael@0: } michael@0: return result; michael@0: }, michael@0: michael@0: sub: function(pattern, replacement, count) { michael@0: replacement = this.gsub.prepareReplacement(replacement); michael@0: count = count === undefined ? 1 : count; michael@0: michael@0: return this.gsub(pattern, function(match) { michael@0: if (--count < 0) return match[0]; michael@0: return replacement(match); michael@0: }); michael@0: }, michael@0: michael@0: scan: function(pattern, iterator) { michael@0: this.gsub(pattern, iterator); michael@0: return this; michael@0: }, michael@0: michael@0: truncate: function(length, truncation) { michael@0: length = length || 30; michael@0: truncation = truncation === undefined ? '...' : truncation; michael@0: return this.length > length ? michael@0: this.slice(0, length - truncation.length) + truncation : this; michael@0: }, michael@0: michael@0: strip: function() { michael@0: return this.replace(/^\s+/, '').replace(/\s+$/, ''); michael@0: }, michael@0: michael@0: stripTags: function() { michael@0: return this.replace(/<\/?[^>]+>/gi, ''); michael@0: }, michael@0: michael@0: stripScripts: function() { michael@0: return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); michael@0: }, michael@0: michael@0: extractScripts: function() { michael@0: var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); michael@0: var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); michael@0: return (this.match(matchAll) || []).map(function(scriptTag) { michael@0: return (scriptTag.match(matchOne) || ['', ''])[1]; michael@0: }); michael@0: }, michael@0: michael@0: evalScripts: function() { michael@0: return this.extractScripts().map(function(script) { return eval(script) }); michael@0: }, michael@0: michael@0: escapeHTML: function() { michael@0: var div = document.createElement('div'); michael@0: var text = document.createTextNode(this); michael@0: div.appendChild(text); michael@0: return div.innerHTML; michael@0: }, michael@0: michael@0: unescapeHTML: function() { michael@0: var div = document.createElement('div'); michael@0: div.innerHTML = this.stripTags(); michael@0: return div.childNodes[0] ? (div.childNodes.length > 1 ? michael@0: $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) : michael@0: div.childNodes[0].nodeValue) : ''; michael@0: }, michael@0: michael@0: toQueryParams: function(separator) { michael@0: var match = this.strip().match(/([^?#]*)(#.*)?$/); michael@0: if (!match) return {}; michael@0: michael@0: return match[1].split(separator || '&').inject({}, function(hash, pair) { michael@0: if ((pair = pair.split('='))[0]) { michael@0: var name = decodeURIComponent(pair[0]); michael@0: var value = pair[1] ? decodeURIComponent(pair[1]) : undefined; michael@0: michael@0: if (hash[name] !== undefined) { michael@0: if (hash[name].constructor != Array) michael@0: hash[name] = [hash[name]]; michael@0: if (value) hash[name].push(value); michael@0: } michael@0: else hash[name] = value; michael@0: } michael@0: return hash; michael@0: }); michael@0: }, michael@0: michael@0: toArray: function() { michael@0: return this.split(''); michael@0: }, michael@0: michael@0: succ: function() { michael@0: return this.slice(0, this.length - 1) + michael@0: String.fromCharCode(this.charCodeAt(this.length - 1) + 1); michael@0: }, michael@0: michael@0: camelize: function() { michael@0: var parts = this.split('-'), len = parts.length; michael@0: if (len == 1) return parts[0]; michael@0: michael@0: var camelized = this.charAt(0) == '-' michael@0: ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) michael@0: : parts[0]; michael@0: michael@0: for (var i = 1; i < len; i++) michael@0: camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1); michael@0: michael@0: return camelized; michael@0: }, michael@0: michael@0: capitalize: function(){ michael@0: return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); michael@0: }, michael@0: michael@0: underscore: function() { michael@0: return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase(); michael@0: }, michael@0: michael@0: dasherize: function() { michael@0: return this.gsub(/_/,'-'); michael@0: }, michael@0: michael@0: inspect: function(useDoubleQuotes) { michael@0: var escapedString = this.replace(/\\/g, '\\\\'); michael@0: if (useDoubleQuotes) michael@0: return '"' + escapedString.replace(/"/g, '\\"') + '"'; michael@0: else michael@0: return "'" + escapedString.replace(/'/g, '\\\'') + "'"; michael@0: } michael@0: }); michael@0: michael@0: String.prototype.gsub.prepareReplacement = function(replacement) { michael@0: if (typeof replacement == 'function') return replacement; michael@0: var template = new Template(replacement); michael@0: return function(match) { return template.evaluate(match) }; michael@0: } michael@0: michael@0: String.prototype.parseQuery = String.prototype.toQueryParams; michael@0: michael@0: var Template = Class.create(); michael@0: Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; michael@0: Template.prototype = { michael@0: initialize: function(template, pattern) { michael@0: this.template = template.toString(); michael@0: this.pattern = pattern || Template.Pattern; michael@0: }, michael@0: michael@0: evaluate: function(object) { michael@0: return this.template.gsub(this.pattern, function(match) { michael@0: var before = match[1]; michael@0: if (before == '\\') return match[2]; michael@0: return before + String.interpret(object[match[3]]); michael@0: }); michael@0: } michael@0: } michael@0: michael@0: var $break = new Object(); michael@0: var $continue = new Object(); michael@0: michael@0: var Enumerable = { michael@0: each: function(iterator) { michael@0: var index = 0; michael@0: try { michael@0: this._each(function(value) { michael@0: try { michael@0: iterator(value, index++); michael@0: } catch (e) { michael@0: if (e != $continue) throw e; michael@0: } michael@0: }); michael@0: } catch (e) { michael@0: if (e != $break) throw e; michael@0: } michael@0: return this; michael@0: }, michael@0: michael@0: eachSlice: function(number, iterator) { michael@0: var index = -number, slices = [], array = this.toArray(); michael@0: while ((index += number) < array.length) michael@0: slices.push(array.slice(index, index+number)); michael@0: return slices.map(iterator); michael@0: }, michael@0: michael@0: all: function(iterator) { michael@0: var result = true; michael@0: this.each(function(value, index) { michael@0: result = result && !!(iterator || Prototype.K)(value, index); michael@0: if (!result) throw $break; michael@0: }); michael@0: return result; michael@0: }, michael@0: michael@0: any: function(iterator) { michael@0: var result = false; michael@0: this.each(function(value, index) { michael@0: if (result = !!(iterator || Prototype.K)(value, index)) michael@0: throw $break; michael@0: }); michael@0: return result; michael@0: }, michael@0: michael@0: collect: function(iterator) { michael@0: var results = []; michael@0: this.each(function(value, index) { michael@0: results.push((iterator || Prototype.K)(value, index)); michael@0: }); michael@0: return results; michael@0: }, michael@0: michael@0: detect: function(iterator) { michael@0: var result; michael@0: this.each(function(value, index) { michael@0: if (iterator(value, index)) { michael@0: result = value; michael@0: throw $break; michael@0: } michael@0: }); michael@0: return result; michael@0: }, michael@0: michael@0: findAll: function(iterator) { michael@0: var results = []; michael@0: this.each(function(value, index) { michael@0: if (iterator(value, index)) michael@0: results.push(value); michael@0: }); michael@0: return results; michael@0: }, michael@0: michael@0: grep: function(pattern, iterator) { michael@0: var results = []; michael@0: this.each(function(value, index) { michael@0: var stringValue = value.toString(); michael@0: if (stringValue.match(pattern)) michael@0: results.push((iterator || Prototype.K)(value, index)); michael@0: }) michael@0: return results; michael@0: }, michael@0: michael@0: include: function(object) { michael@0: var found = false; michael@0: this.each(function(value) { michael@0: if (value == object) { michael@0: found = true; michael@0: throw $break; michael@0: } michael@0: }); michael@0: return found; michael@0: }, michael@0: michael@0: inGroupsOf: function(number, fillWith) { michael@0: fillWith = fillWith === undefined ? null : fillWith; michael@0: return this.eachSlice(number, function(slice) { michael@0: while(slice.length < number) slice.push(fillWith); michael@0: return slice; michael@0: }); michael@0: }, michael@0: michael@0: inject: function(memo, iterator) { michael@0: this.each(function(value, index) { michael@0: memo = iterator(memo, value, index); michael@0: }); michael@0: return memo; michael@0: }, michael@0: michael@0: invoke: function(method) { michael@0: var args = $A(arguments).slice(1); michael@0: return this.map(function(value) { michael@0: return value[method].apply(value, args); michael@0: }); michael@0: }, michael@0: michael@0: max: function(iterator) { michael@0: var result; michael@0: this.each(function(value, index) { michael@0: value = (iterator || Prototype.K)(value, index); michael@0: if (result == undefined || value >= result) michael@0: result = value; michael@0: }); michael@0: return result; michael@0: }, michael@0: michael@0: min: function(iterator) { michael@0: var result; michael@0: this.each(function(value, index) { michael@0: value = (iterator || Prototype.K)(value, index); michael@0: if (result == undefined || value < result) michael@0: result = value; michael@0: }); michael@0: return result; michael@0: }, michael@0: michael@0: partition: function(iterator) { michael@0: var trues = [], falses = []; michael@0: this.each(function(value, index) { michael@0: ((iterator || Prototype.K)(value, index) ? michael@0: trues : falses).push(value); michael@0: }); michael@0: return [trues, falses]; michael@0: }, michael@0: michael@0: pluck: function(property) { michael@0: var results = []; michael@0: this.each(function(value, index) { michael@0: results.push(value[property]); michael@0: }); michael@0: return results; michael@0: }, michael@0: michael@0: reject: function(iterator) { michael@0: var results = []; michael@0: this.each(function(value, index) { michael@0: if (!iterator(value, index)) michael@0: results.push(value); michael@0: }); michael@0: return results; michael@0: }, michael@0: michael@0: sortBy: function(iterator) { michael@0: return this.map(function(value, index) { michael@0: return {value: value, criteria: iterator(value, index)}; michael@0: }).sort(function(left, right) { michael@0: var a = left.criteria, b = right.criteria; michael@0: return a < b ? -1 : a > b ? 1 : 0; michael@0: }).pluck('value'); michael@0: }, michael@0: michael@0: toArray: function() { michael@0: return this.map(); michael@0: }, michael@0: michael@0: zip: function() { michael@0: var iterator = Prototype.K, args = $A(arguments); michael@0: if (typeof args.last() == 'function') michael@0: iterator = args.pop(); michael@0: michael@0: var collections = [this].concat(args).map($A); michael@0: return this.map(function(value, index) { michael@0: return iterator(collections.pluck(index)); michael@0: }); michael@0: }, michael@0: michael@0: size: function() { michael@0: return this.toArray().length; michael@0: }, michael@0: michael@0: inspect: function() { michael@0: return '#'; michael@0: } michael@0: } michael@0: michael@0: Object.extend(Enumerable, { michael@0: map: Enumerable.collect, michael@0: find: Enumerable.detect, michael@0: select: Enumerable.findAll, michael@0: member: Enumerable.include, michael@0: entries: Enumerable.toArray michael@0: }); michael@0: var $A = Array.from = function(iterable) { michael@0: if (!iterable) return []; michael@0: if (iterable.toArray) { michael@0: return iterable.toArray(); michael@0: } else { michael@0: var results = []; michael@0: for (var i = 0, length = iterable.length; i < length; i++) michael@0: results.push(iterable[i]); michael@0: return results; michael@0: } michael@0: } michael@0: michael@0: Object.extend(Array.prototype, Enumerable); michael@0: michael@0: if (!Array.prototype._reverse) michael@0: Array.prototype._reverse = Array.prototype.reverse; michael@0: michael@0: Object.extend(Array.prototype, { michael@0: _each: function(iterator) { michael@0: for (var i = 0, length = this.length; i < length; i++) michael@0: iterator(this[i]); michael@0: }, michael@0: michael@0: clear: function() { michael@0: this.length = 0; michael@0: return this; michael@0: }, michael@0: michael@0: first: function() { michael@0: return this[0]; michael@0: }, michael@0: michael@0: last: function() { michael@0: return this[this.length - 1]; michael@0: }, michael@0: michael@0: compact: function() { michael@0: return this.select(function(value) { michael@0: return value != null; michael@0: }); michael@0: }, michael@0: michael@0: flatten: function() { michael@0: return this.inject([], function(array, value) { michael@0: return array.concat(value && value.constructor == Array ? michael@0: value.flatten() : [value]); michael@0: }); michael@0: }, michael@0: michael@0: without: function() { michael@0: var values = $A(arguments); michael@0: return this.select(function(value) { michael@0: return !values.include(value); michael@0: }); michael@0: }, michael@0: michael@0: indexOf: function(object) { michael@0: for (var i = 0, length = this.length; i < length; i++) michael@0: if (this[i] == object) return i; michael@0: return -1; michael@0: }, michael@0: michael@0: reverse: function(inline) { michael@0: return (inline !== false ? this : this.toArray())._reverse(); michael@0: }, michael@0: michael@0: reduce: function() { michael@0: return this.length > 1 ? this : this[0]; michael@0: }, michael@0: michael@0: uniq: function() { michael@0: return this.inject([], function(array, value) { michael@0: return array.include(value) ? array : array.concat([value]); michael@0: }); michael@0: }, michael@0: michael@0: clone: function() { michael@0: return [].concat(this); michael@0: }, michael@0: michael@0: size: function() { michael@0: return this.length; michael@0: }, michael@0: michael@0: inspect: function() { michael@0: return '[' + this.map(Object.inspect).join(', ') + ']'; michael@0: } michael@0: }); michael@0: michael@0: Array.prototype.toArray = Array.prototype.clone; michael@0: michael@0: function $w(string){ michael@0: string = string.strip(); michael@0: return string ? string.split(/\s+/) : []; michael@0: } michael@0: michael@0: if(window.opera){ michael@0: Array.prototype.concat = function(){ michael@0: var array = []; michael@0: for(var i = 0, length = this.length; i < length; i++) array.push(this[i]); michael@0: for(var i = 0, length = arguments.length; i < length; i++) { michael@0: if(arguments[i].constructor == Array) { michael@0: for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++) michael@0: array.push(arguments[i][j]); michael@0: } else { michael@0: array.push(arguments[i]); michael@0: } michael@0: } michael@0: return array; michael@0: } michael@0: } michael@0: var Hash = function(obj) { michael@0: Object.extend(this, obj || {}); michael@0: }; michael@0: michael@0: Object.extend(Hash, { michael@0: toQueryString: function(obj) { michael@0: var parts = []; michael@0: michael@0: this.prototype._each.call(obj, function(pair) { michael@0: if (!pair.key) return; michael@0: michael@0: if (pair.value && pair.value.constructor == Array) { michael@0: var values = pair.value.compact(); michael@0: if (values.length < 2) pair.value = values.reduce(); michael@0: else { michael@0: key = encodeURIComponent(pair.key); michael@0: values.each(function(value) { michael@0: value = value != undefined ? encodeURIComponent(value) : ''; michael@0: parts.push(key + '=' + encodeURIComponent(value)); michael@0: }); michael@0: return; michael@0: } michael@0: } michael@0: if (pair.value == undefined) pair[1] = ''; michael@0: parts.push(pair.map(encodeURIComponent).join('=')); michael@0: }); michael@0: michael@0: return parts.join('&'); michael@0: } michael@0: }); michael@0: michael@0: Object.extend(Hash.prototype, Enumerable); michael@0: Object.extend(Hash.prototype, { michael@0: _each: function(iterator) { michael@0: for (var key in this) { michael@0: var value = this[key]; michael@0: if (value && value == Hash.prototype[key]) continue; michael@0: michael@0: var pair = [key, value]; michael@0: pair.key = key; michael@0: pair.value = value; michael@0: iterator(pair); michael@0: } michael@0: }, michael@0: michael@0: keys: function() { michael@0: return this.pluck('key'); michael@0: }, michael@0: michael@0: values: function() { michael@0: return this.pluck('value'); michael@0: }, michael@0: michael@0: merge: function(hash) { michael@0: return $H(hash).inject(this, function(mergedHash, pair) { michael@0: mergedHash[pair.key] = pair.value; michael@0: return mergedHash; michael@0: }); michael@0: }, michael@0: michael@0: remove: function() { michael@0: var result; michael@0: for(var i = 0, length = arguments.length; i < length; i++) { michael@0: var value = this[arguments[i]]; michael@0: if (value !== undefined){ michael@0: if (result === undefined) result = value; michael@0: else { michael@0: if (result.constructor != Array) result = [result]; michael@0: result.push(value) michael@0: } michael@0: } michael@0: delete this[arguments[i]]; michael@0: } michael@0: return result; michael@0: }, michael@0: michael@0: toQueryString: function() { michael@0: return Hash.toQueryString(this); michael@0: }, michael@0: michael@0: inspect: function() { michael@0: return '#'; michael@0: } michael@0: }); michael@0: michael@0: function $H(object) { michael@0: if (object && object.constructor == Hash) return object; michael@0: return new Hash(object); michael@0: }; michael@0: ObjectRange = Class.create(); michael@0: Object.extend(ObjectRange.prototype, Enumerable); michael@0: Object.extend(ObjectRange.prototype, { michael@0: initialize: function(start, end, exclusive) { michael@0: this.start = start; michael@0: this.end = end; michael@0: this.exclusive = exclusive; michael@0: }, michael@0: michael@0: _each: function(iterator) { michael@0: var value = this.start; michael@0: while (this.include(value)) { michael@0: iterator(value); michael@0: value = value.succ(); michael@0: } michael@0: }, michael@0: michael@0: include: function(value) { michael@0: if (value < this.start) michael@0: return false; michael@0: if (this.exclusive) michael@0: return value < this.end; michael@0: return value <= this.end; michael@0: } michael@0: }); michael@0: michael@0: var $R = function(start, end, exclusive) { michael@0: return new ObjectRange(start, end, exclusive); michael@0: } michael@0: michael@0: var Ajax = { michael@0: getTransport: function() { michael@0: return Try.these( michael@0: function() {return new XMLHttpRequest()}, michael@0: function() {return new ActiveXObject('Msxml2.XMLHTTP')}, michael@0: function() {return new ActiveXObject('Microsoft.XMLHTTP')} michael@0: ) || false; michael@0: }, michael@0: michael@0: activeRequestCount: 0 michael@0: } michael@0: michael@0: Ajax.Responders = { michael@0: responders: [], michael@0: michael@0: _each: function(iterator) { michael@0: this.responders._each(iterator); michael@0: }, michael@0: michael@0: register: function(responder) { michael@0: if (!this.include(responder)) michael@0: this.responders.push(responder); michael@0: }, michael@0: michael@0: unregister: function(responder) { michael@0: this.responders = this.responders.without(responder); michael@0: }, michael@0: michael@0: dispatch: function(callback, request, transport, json) { michael@0: this.each(function(responder) { michael@0: if (typeof responder[callback] == 'function') { michael@0: try { michael@0: responder[callback].apply(responder, [request, transport, json]); michael@0: } catch (e) {} michael@0: } michael@0: }); michael@0: } michael@0: }; michael@0: michael@0: Object.extend(Ajax.Responders, Enumerable); michael@0: michael@0: Ajax.Responders.register({ michael@0: onCreate: function() { michael@0: Ajax.activeRequestCount++; michael@0: }, michael@0: onComplete: function() { michael@0: Ajax.activeRequestCount--; michael@0: } michael@0: }); michael@0: michael@0: Ajax.Base = function() {}; michael@0: Ajax.Base.prototype = { michael@0: setOptions: function(options) { michael@0: this.options = { michael@0: method: 'post', michael@0: asynchronous: true, michael@0: contentType: 'application/x-www-form-urlencoded', michael@0: encoding: 'UTF-8', michael@0: parameters: '' michael@0: } michael@0: Object.extend(this.options, options || {}); michael@0: michael@0: this.options.method = this.options.method.toLowerCase(); michael@0: if (typeof this.options.parameters == 'string') michael@0: this.options.parameters = this.options.parameters.toQueryParams(); michael@0: } michael@0: } michael@0: michael@0: Ajax.Request = Class.create(); michael@0: Ajax.Request.Events = michael@0: ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; michael@0: michael@0: Ajax.Request.prototype = Object.extend(new Ajax.Base(), { michael@0: _complete: false, michael@0: michael@0: initialize: function(url, options) { michael@0: this.transport = Ajax.getTransport(); michael@0: this.setOptions(options); michael@0: this.request(url); michael@0: }, michael@0: michael@0: request: function(url) { michael@0: this.url = url; michael@0: this.method = this.options.method; michael@0: var params = this.options.parameters; michael@0: michael@0: if (!['get', 'post'].include(this.method)) { michael@0: // simulate other verbs over post michael@0: params['_method'] = this.method; michael@0: this.method = 'post'; michael@0: } michael@0: michael@0: params = Hash.toQueryString(params); michael@0: if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_=' michael@0: michael@0: // when GET, append parameters to URL michael@0: if (this.method == 'get' && params) michael@0: this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params; michael@0: michael@0: try { michael@0: Ajax.Responders.dispatch('onCreate', this, this.transport); michael@0: michael@0: this.transport.open(this.method.toUpperCase(), this.url, michael@0: this.options.asynchronous); michael@0: michael@0: if (this.options.asynchronous) michael@0: setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10); michael@0: michael@0: this.transport.onreadystatechange = this.onStateChange.bind(this); michael@0: this.setRequestHeaders(); michael@0: michael@0: var body = this.method == 'post' ? (this.options.postBody || params) : null; michael@0: michael@0: this.transport.send(body); michael@0: michael@0: /* Force Firefox to handle ready state 4 for synchronous requests */ michael@0: if (!this.options.asynchronous && this.transport.overrideMimeType) michael@0: this.onStateChange(); michael@0: michael@0: } michael@0: catch (e) { michael@0: this.dispatchException(e); michael@0: } michael@0: }, michael@0: michael@0: onStateChange: function() { michael@0: var readyState = this.transport.readyState; michael@0: if (readyState > 1 && !((readyState == 4) && this._complete)) michael@0: this.respondToReadyState(this.transport.readyState); michael@0: }, michael@0: michael@0: setRequestHeaders: function() { michael@0: var headers = { michael@0: 'X-Requested-With': 'XMLHttpRequest', michael@0: 'X-Prototype-Version': Prototype.Version, michael@0: 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' michael@0: }; michael@0: michael@0: if (this.method == 'post') { michael@0: headers['Content-type'] = this.options.contentType + michael@0: (this.options.encoding ? '; charset=' + this.options.encoding : ''); michael@0: michael@0: /* Force "Connection: close" for older Mozilla browsers to work michael@0: * around a bug where XMLHttpRequest sends an incorrect michael@0: * Content-length header. See Mozilla Bugzilla #246651. michael@0: */ michael@0: if (this.transport.overrideMimeType && michael@0: (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) michael@0: headers['Connection'] = 'close'; michael@0: } michael@0: michael@0: // user-defined headers michael@0: if (typeof this.options.requestHeaders == 'object') { michael@0: var extras = this.options.requestHeaders; michael@0: michael@0: if (typeof extras.push == 'function') michael@0: for (var i = 0, length = extras.length; i < length; i += 2) michael@0: headers[extras[i]] = extras[i+1]; michael@0: else michael@0: $H(extras).each(function(pair) { headers[pair.key] = pair.value }); michael@0: } michael@0: michael@0: for (var name in headers) michael@0: this.transport.setRequestHeader(name, headers[name]); michael@0: }, michael@0: michael@0: success: function() { michael@0: return !this.transport.status michael@0: || (this.transport.status >= 200 && this.transport.status < 300); michael@0: }, michael@0: michael@0: respondToReadyState: function(readyState) { michael@0: var state = Ajax.Request.Events[readyState]; michael@0: var transport = this.transport, json = this.evalJSON(); michael@0: michael@0: if (state == 'Complete') { michael@0: try { michael@0: this._complete = true; michael@0: (this.options['on' + this.transport.status] michael@0: || this.options['on' + (this.success() ? 'Success' : 'Failure')] michael@0: || Prototype.emptyFunction)(transport, json); michael@0: } catch (e) { michael@0: this.dispatchException(e); michael@0: } michael@0: michael@0: if ((this.getHeader('Content-type') || 'text/javascript').strip(). michael@0: match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i)) michael@0: this.evalResponse(); michael@0: } michael@0: michael@0: try { michael@0: (this.options['on' + state] || Prototype.emptyFunction)(transport, json); michael@0: Ajax.Responders.dispatch('on' + state, this, transport, json); michael@0: } catch (e) { michael@0: this.dispatchException(e); michael@0: } michael@0: michael@0: if (state == 'Complete') { michael@0: // avoid memory leak in MSIE: clean up michael@0: this.transport.onreadystatechange = Prototype.emptyFunction; michael@0: } michael@0: }, michael@0: michael@0: getHeader: function(name) { michael@0: try { michael@0: return this.transport.getResponseHeader(name); michael@0: } catch (e) { return null } michael@0: }, michael@0: michael@0: evalJSON: function() { michael@0: try { michael@0: var json = this.getHeader('X-JSON'); michael@0: return json ? eval('(' + json + ')') : null; michael@0: } catch (e) { return null } michael@0: }, michael@0: michael@0: evalResponse: function() { michael@0: try { michael@0: return eval(this.transport.responseText); michael@0: } catch (e) { michael@0: this.dispatchException(e); michael@0: } michael@0: }, michael@0: michael@0: dispatchException: function(exception) { michael@0: (this.options.onException || Prototype.emptyFunction)(this, exception); michael@0: Ajax.Responders.dispatch('onException', this, exception); michael@0: } michael@0: }); michael@0: michael@0: Ajax.Updater = Class.create(); michael@0: michael@0: Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), { michael@0: initialize: function(container, url, options) { michael@0: this.container = { michael@0: success: (container.success || container), michael@0: failure: (container.failure || (container.success ? null : container)) michael@0: } michael@0: michael@0: this.transport = Ajax.getTransport(); michael@0: this.setOptions(options); michael@0: michael@0: var onComplete = this.options.onComplete || Prototype.emptyFunction; michael@0: this.options.onComplete = (function(transport, param) { michael@0: this.updateContent(); michael@0: onComplete(transport, param); michael@0: }).bind(this); michael@0: michael@0: this.request(url); michael@0: }, michael@0: michael@0: updateContent: function() { michael@0: var receiver = this.container[this.success() ? 'success' : 'failure']; michael@0: var response = this.transport.responseText; michael@0: michael@0: if (!this.options.evalScripts) response = response.stripScripts(); michael@0: michael@0: if (receiver = $(receiver)) { michael@0: if (this.options.insertion) michael@0: new this.options.insertion(receiver, response); michael@0: else michael@0: receiver.update(response); michael@0: } michael@0: michael@0: if (this.success()) { michael@0: if (this.onComplete) michael@0: setTimeout(this.onComplete.bind(this), 10); michael@0: } michael@0: } michael@0: }); michael@0: michael@0: Ajax.PeriodicalUpdater = Class.create(); michael@0: Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), { michael@0: initialize: function(container, url, options) { michael@0: this.setOptions(options); michael@0: this.onComplete = this.options.onComplete; michael@0: michael@0: this.frequency = (this.options.frequency || 2); michael@0: this.decay = (this.options.decay || 1); michael@0: michael@0: this.updater = {}; michael@0: this.container = container; michael@0: this.url = url; michael@0: michael@0: this.start(); michael@0: }, michael@0: michael@0: start: function() { michael@0: this.options.onComplete = this.updateComplete.bind(this); michael@0: this.onTimerEvent(); michael@0: }, michael@0: michael@0: stop: function() { michael@0: this.updater.options.onComplete = undefined; michael@0: clearTimeout(this.timer); michael@0: (this.onComplete || Prototype.emptyFunction).apply(this, arguments); michael@0: }, michael@0: michael@0: updateComplete: function(request) { michael@0: if (this.options.decay) { michael@0: this.decay = (request.responseText == this.lastText ? michael@0: this.decay * this.options.decay : 1); michael@0: michael@0: this.lastText = request.responseText; michael@0: } michael@0: this.timer = setTimeout(this.onTimerEvent.bind(this), michael@0: this.decay * this.frequency * 1000); michael@0: }, michael@0: michael@0: onTimerEvent: function() { michael@0: this.updater = new Ajax.Updater(this.container, this.url, this.options); michael@0: } michael@0: }); michael@0: function $(element) { michael@0: if (arguments.length > 1) { michael@0: for (var i = 0, elements = [], length = arguments.length; i < length; i++) michael@0: elements.push($(arguments[i])); michael@0: return elements; michael@0: } michael@0: if (typeof element == 'string') michael@0: element = document.getElementById(element); michael@0: return Element.extend(element); michael@0: } michael@0: michael@0: if (Prototype.BrowserFeatures.XPath) { michael@0: document._getElementsByXPath = function(expression, parentElement) { michael@0: var results = []; michael@0: var query = document.evaluate(expression, $(parentElement) || document, michael@0: null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); michael@0: for (var i = 0, length = query.snapshotLength; i < length; i++) michael@0: results.push(query.snapshotItem(i)); michael@0: return results; michael@0: }; michael@0: } michael@0: michael@0: document.getElementsByClassName = function(className, parentElement) { michael@0: if (Prototype.BrowserFeatures.XPath) { michael@0: var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]"; michael@0: return document._getElementsByXPath(q, parentElement); michael@0: } else { michael@0: var children = ($(parentElement) || document.body).getElementsByTagName('*'); michael@0: var elements = [], child; michael@0: for (var i = 0, length = children.length; i < length; i++) { michael@0: child = children[i]; michael@0: if (Element.hasClassName(child, className)) michael@0: elements.push(Element.extend(child)); michael@0: } michael@0: return elements; michael@0: } michael@0: }; michael@0: michael@0: /*--------------------------------------------------------------------------*/ michael@0: michael@0: if (!window.Element) michael@0: var Element = new Object(); michael@0: michael@0: Element.extend = function(element) { michael@0: if (!element || _nativeExtensions || element.nodeType == 3) return element; michael@0: michael@0: if (!element._extended && element.tagName && element != window) { michael@0: var methods = Object.clone(Element.Methods), cache = Element.extend.cache; michael@0: michael@0: if (element.tagName == 'FORM') michael@0: Object.extend(methods, Form.Methods); michael@0: if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName)) michael@0: Object.extend(methods, Form.Element.Methods); michael@0: michael@0: Object.extend(methods, Element.Methods.Simulated); michael@0: michael@0: for (var property in methods) { michael@0: var value = methods[property]; michael@0: if (typeof value == 'function' && !(property in element)) michael@0: element[property] = cache.findOrStore(value); michael@0: } michael@0: } michael@0: michael@0: element._extended = true; michael@0: return element; michael@0: }; michael@0: michael@0: Element.extend.cache = { michael@0: findOrStore: function(value) { michael@0: return this[value] = this[value] || function() { michael@0: return value.apply(null, [this].concat($A(arguments))); michael@0: } michael@0: } michael@0: }; michael@0: michael@0: Element.Methods = { michael@0: visible: function(element) { michael@0: return $(element).style.display != 'none'; michael@0: }, michael@0: michael@0: toggle: function(element) { michael@0: element = $(element); michael@0: Element[Element.visible(element) ? 'hide' : 'show'](element); michael@0: return element; michael@0: }, michael@0: michael@0: hide: function(element) { michael@0: $(element).style.display = 'none'; michael@0: return element; michael@0: }, michael@0: michael@0: show: function(element) { michael@0: $(element).style.display = ''; michael@0: return element; michael@0: }, michael@0: michael@0: remove: function(element) { michael@0: element = $(element); michael@0: element.parentNode.removeChild(element); michael@0: return element; michael@0: }, michael@0: michael@0: update: function(element, html) { michael@0: html = typeof html == 'undefined' ? '' : html.toString(); michael@0: $(element).innerHTML = html.stripScripts(); michael@0: setTimeout(function() {html.evalScripts()}, 10); michael@0: return element; michael@0: }, michael@0: michael@0: replace: function(element, html) { michael@0: element = $(element); michael@0: html = typeof html == 'undefined' ? '' : html.toString(); michael@0: if (element.outerHTML) { michael@0: element.outerHTML = html.stripScripts(); michael@0: } else { michael@0: var range = element.ownerDocument.createRange(); michael@0: range.selectNodeContents(element); michael@0: element.parentNode.replaceChild( michael@0: range.createContextualFragment(html.stripScripts()), element); michael@0: } michael@0: setTimeout(function() {html.evalScripts()}, 10); michael@0: return element; michael@0: }, michael@0: michael@0: inspect: function(element) { michael@0: element = $(element); michael@0: var result = '<' + element.tagName.toLowerCase(); michael@0: $H({'id': 'id', 'className': 'class'}).each(function(pair) { michael@0: var property = pair.first(), attribute = pair.last(); michael@0: var value = (element[property] || '').toString(); michael@0: if (value) result += ' ' + attribute + '=' + value.inspect(true); michael@0: }); michael@0: return result + '>'; michael@0: }, michael@0: michael@0: recursivelyCollect: function(element, property) { michael@0: element = $(element); michael@0: var elements = []; michael@0: while (element = element[property]) michael@0: if (element.nodeType == 1) michael@0: elements.push(Element.extend(element)); michael@0: return elements; michael@0: }, michael@0: michael@0: ancestors: function(element) { michael@0: return $(element).recursivelyCollect('parentNode'); michael@0: }, michael@0: michael@0: descendants: function(element) { michael@0: return $A($(element).getElementsByTagName('*')); michael@0: }, michael@0: michael@0: immediateDescendants: function(element) { michael@0: if (!(element = $(element).firstChild)) return []; michael@0: while (element && element.nodeType != 1) element = element.nextSibling; michael@0: if (element) return [element].concat($(element).nextSiblings()); michael@0: return []; michael@0: }, michael@0: michael@0: previousSiblings: function(element) { michael@0: return $(element).recursivelyCollect('previousSibling'); michael@0: }, michael@0: michael@0: nextSiblings: function(element) { michael@0: return $(element).recursivelyCollect('nextSibling'); michael@0: }, michael@0: michael@0: siblings: function(element) { michael@0: element = $(element); michael@0: return element.previousSiblings().reverse().concat(element.nextSiblings()); michael@0: }, michael@0: michael@0: match: function(element, selector) { michael@0: if (typeof selector == 'string') michael@0: selector = new Selector(selector); michael@0: return selector.match($(element)); michael@0: }, michael@0: michael@0: up: function(element, expression, index) { michael@0: return Selector.findElement($(element).ancestors(), expression, index); michael@0: }, michael@0: michael@0: down: function(element, expression, index) { michael@0: return Selector.findElement($(element).descendants(), expression, index); michael@0: }, michael@0: michael@0: previous: function(element, expression, index) { michael@0: return Selector.findElement($(element).previousSiblings(), expression, index); michael@0: }, michael@0: michael@0: next: function(element, expression, index) { michael@0: return Selector.findElement($(element).nextSiblings(), expression, index); michael@0: }, michael@0: michael@0: getElementsBySelector: function() { michael@0: var args = $A(arguments), element = $(args.shift()); michael@0: return Selector.findChildElements(element, args); michael@0: }, michael@0: michael@0: getElementsByClassName: function(element, className) { michael@0: return document.getElementsByClassName(className, element); michael@0: }, michael@0: michael@0: readAttribute: function(element, name) { michael@0: element = $(element); michael@0: if (document.all && !window.opera) { michael@0: var t = Element._attributeTranslations; michael@0: if (t.values[name]) return t.values[name](element, name); michael@0: if (t.names[name]) name = t.names[name]; michael@0: var attribute = element.attributes[name]; michael@0: if(attribute) return attribute.nodeValue; michael@0: } michael@0: return element.getAttribute(name); michael@0: }, michael@0: michael@0: getHeight: function(element) { michael@0: return $(element).getDimensions().height; michael@0: }, michael@0: michael@0: getWidth: function(element) { michael@0: return $(element).getDimensions().width; michael@0: }, michael@0: michael@0: classNames: function(element) { michael@0: return new Element.ClassNames(element); michael@0: }, michael@0: michael@0: hasClassName: function(element, className) { michael@0: if (!(element = $(element))) return; michael@0: var elementClassName = element.className; michael@0: if (elementClassName.length == 0) return false; michael@0: if (elementClassName == className || michael@0: elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) michael@0: return true; michael@0: return false; michael@0: }, michael@0: michael@0: addClassName: function(element, className) { michael@0: if (!(element = $(element))) return; michael@0: Element.classNames(element).add(className); michael@0: return element; michael@0: }, michael@0: michael@0: removeClassName: function(element, className) { michael@0: if (!(element = $(element))) return; michael@0: Element.classNames(element).remove(className); michael@0: return element; michael@0: }, michael@0: michael@0: toggleClassName: function(element, className) { michael@0: if (!(element = $(element))) return; michael@0: Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className); michael@0: return element; michael@0: }, michael@0: michael@0: observe: function() { michael@0: Event.observe.apply(Event, arguments); michael@0: return $A(arguments).first(); michael@0: }, michael@0: michael@0: stopObserving: function() { michael@0: Event.stopObserving.apply(Event, arguments); michael@0: return $A(arguments).first(); michael@0: }, michael@0: michael@0: // removes whitespace-only text node children michael@0: cleanWhitespace: function(element) { michael@0: element = $(element); michael@0: var node = element.firstChild; michael@0: while (node) { michael@0: var nextNode = node.nextSibling; michael@0: if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) michael@0: element.removeChild(node); michael@0: node = nextNode; michael@0: } michael@0: return element; michael@0: }, michael@0: michael@0: empty: function(element) { michael@0: return $(element).innerHTML.match(/^\s*$/); michael@0: }, michael@0: michael@0: descendantOf: function(element, ancestor) { michael@0: element = $(element), ancestor = $(ancestor); michael@0: while (element = element.parentNode) michael@0: if (element == ancestor) return true; michael@0: return false; michael@0: }, michael@0: michael@0: scrollTo: function(element) { michael@0: element = $(element); michael@0: var pos = Position.cumulativeOffset(element); michael@0: window.scrollTo(pos[0], pos[1]); michael@0: return element; michael@0: }, michael@0: michael@0: getStyle: function(element, style) { michael@0: element = $(element); michael@0: if (['float','cssFloat'].include(style)) michael@0: style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat'); michael@0: style = style.camelize(); michael@0: var value = element.style[style]; michael@0: if (!value) { michael@0: if (document.defaultView && document.defaultView.getComputedStyle) { michael@0: var css = document.defaultView.getComputedStyle(element, null); michael@0: value = css ? css[style] : null; michael@0: } else if (element.currentStyle) { michael@0: value = element.currentStyle[style]; michael@0: } michael@0: } michael@0: michael@0: if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none')) michael@0: value = element['offset'+style.capitalize()] + 'px'; michael@0: michael@0: if (window.opera && ['left', 'top', 'right', 'bottom'].include(style)) michael@0: if (Element.getStyle(element, 'position') == 'static') value = 'auto'; michael@0: if(style == 'opacity') { michael@0: if(value) return parseFloat(value); michael@0: if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/)) michael@0: if(value[1]) return parseFloat(value[1]) / 100; michael@0: return 1.0; michael@0: } michael@0: return value == 'auto' ? null : value; michael@0: }, michael@0: michael@0: setStyle: function(element, style) { michael@0: element = $(element); michael@0: for (var name in style) { michael@0: var value = style[name]; michael@0: if(name == 'opacity') { michael@0: if (value == 1) { michael@0: value = (/Gecko/.test(navigator.userAgent) && michael@0: !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0; michael@0: if(/MSIE/.test(navigator.userAgent) && !window.opera) michael@0: element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,''); michael@0: } else if(value == '') { michael@0: if(/MSIE/.test(navigator.userAgent) && !window.opera) michael@0: element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,''); michael@0: } else { michael@0: if(value < 0.00001) value = 0; michael@0: if(/MSIE/.test(navigator.userAgent) && !window.opera) michael@0: element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') + michael@0: 'alpha(opacity='+value*100+')'; michael@0: } michael@0: } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat'; michael@0: element.style[name.camelize()] = value; michael@0: } michael@0: return element; michael@0: }, michael@0: michael@0: getDimensions: function(element) { michael@0: element = $(element); michael@0: var display = $(element).getStyle('display'); michael@0: if (display != 'none' && display != null) // Safari bug michael@0: return {width: element.offsetWidth, height: element.offsetHeight}; michael@0: michael@0: // All *Width and *Height properties give 0 on elements with display none, michael@0: // so enable the element temporarily michael@0: var els = element.style; michael@0: var originalVisibility = els.visibility; michael@0: var originalPosition = els.position; michael@0: var originalDisplay = els.display; michael@0: els.visibility = 'hidden'; michael@0: els.position = 'absolute'; michael@0: els.display = 'block'; michael@0: var originalWidth = element.clientWidth; michael@0: var originalHeight = element.clientHeight; michael@0: els.display = originalDisplay; michael@0: els.position = originalPosition; michael@0: els.visibility = originalVisibility; michael@0: return {width: originalWidth, height: originalHeight}; michael@0: }, michael@0: michael@0: makePositioned: function(element) { michael@0: element = $(element); michael@0: var pos = Element.getStyle(element, 'position'); michael@0: if (pos == 'static' || !pos) { michael@0: element._madePositioned = true; michael@0: element.style.position = 'relative'; michael@0: // Opera returns the offset relative to the positioning context, when an michael@0: // element is position relative but top and left have not been defined michael@0: if (window.opera) { michael@0: element.style.top = 0; michael@0: element.style.left = 0; michael@0: } michael@0: } michael@0: return element; michael@0: }, michael@0: michael@0: undoPositioned: function(element) { michael@0: element = $(element); michael@0: if (element._madePositioned) { michael@0: element._madePositioned = undefined; michael@0: element.style.position = michael@0: element.style.top = michael@0: element.style.left = michael@0: element.style.bottom = michael@0: element.style.right = ''; michael@0: } michael@0: return element; michael@0: }, michael@0: michael@0: makeClipping: function(element) { michael@0: element = $(element); michael@0: if (element._overflow) return element; michael@0: element._overflow = element.style.overflow || 'auto'; michael@0: if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden') michael@0: element.style.overflow = 'hidden'; michael@0: return element; michael@0: }, michael@0: michael@0: undoClipping: function(element) { michael@0: element = $(element); michael@0: if (!element._overflow) return element; michael@0: element.style.overflow = element._overflow == 'auto' ? '' : element._overflow; michael@0: element._overflow = null; michael@0: return element; michael@0: } michael@0: }; michael@0: michael@0: Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf}); michael@0: michael@0: Element._attributeTranslations = {}; michael@0: michael@0: Element._attributeTranslations.names = { michael@0: colspan: "colSpan", michael@0: rowspan: "rowSpan", michael@0: valign: "vAlign", michael@0: datetime: "dateTime", michael@0: accesskey: "accessKey", michael@0: tabindex: "tabIndex", michael@0: enctype: "encType", michael@0: maxlength: "maxLength", michael@0: readonly: "readOnly", michael@0: longdesc: "longDesc" michael@0: }; michael@0: michael@0: Element._attributeTranslations.values = { michael@0: _getAttr: function(element, attribute) { michael@0: return element.getAttribute(attribute, 2); michael@0: }, michael@0: michael@0: _flag: function(element, attribute) { michael@0: return $(element).hasAttribute(attribute) ? attribute : null; michael@0: }, michael@0: michael@0: style: function(element) { michael@0: return element.style.cssText.toLowerCase(); michael@0: }, michael@0: michael@0: title: function(element) { michael@0: var node = element.getAttributeNode('title'); michael@0: return node.specified ? node.nodeValue : null; michael@0: } michael@0: }; michael@0: michael@0: Object.extend(Element._attributeTranslations.values, { michael@0: href: Element._attributeTranslations.values._getAttr, michael@0: src: Element._attributeTranslations.values._getAttr, michael@0: disabled: Element._attributeTranslations.values._flag, michael@0: checked: Element._attributeTranslations.values._flag, michael@0: readonly: Element._attributeTranslations.values._flag, michael@0: multiple: Element._attributeTranslations.values._flag michael@0: }); michael@0: michael@0: Element.Methods.Simulated = { michael@0: hasAttribute: function(element, attribute) { michael@0: var t = Element._attributeTranslations; michael@0: attribute = t.names[attribute] || attribute; michael@0: return $(element).getAttributeNode(attribute).specified; michael@0: } michael@0: }; michael@0: michael@0: // IE is missing .innerHTML support for TABLE-related elements michael@0: if (document.all && !window.opera){ michael@0: Element.Methods.update = function(element, html) { michael@0: element = $(element); michael@0: html = typeof html == 'undefined' ? '' : html.toString(); michael@0: var tagName = element.tagName.toUpperCase(); michael@0: if (['THEAD','TBODY','TR','TD'].include(tagName)) { michael@0: var div = document.createElement('div'); michael@0: switch (tagName) { michael@0: case 'THEAD': michael@0: case 'TBODY': michael@0: div.innerHTML = '' + html.stripScripts() + '
'; michael@0: depth = 2; michael@0: break; michael@0: case 'TR': michael@0: div.innerHTML = '' + html.stripScripts() + '
'; michael@0: depth = 3; michael@0: break; michael@0: case 'TD': michael@0: div.innerHTML = '
' + html.stripScripts() + '
'; michael@0: depth = 4; michael@0: } michael@0: $A(element.childNodes).each(function(node){ michael@0: element.removeChild(node) michael@0: }); michael@0: depth.times(function(){ div = div.firstChild }); michael@0: michael@0: $A(div.childNodes).each( michael@0: function(node){ element.appendChild(node) }); michael@0: } else { michael@0: element.innerHTML = html.stripScripts(); michael@0: } michael@0: setTimeout(function() {html.evalScripts()}, 10); michael@0: return element; michael@0: } michael@0: }; michael@0: michael@0: Object.extend(Element, Element.Methods); michael@0: michael@0: var _nativeExtensions = false; michael@0: michael@0: if(/Konqueror|Safari|KHTML/.test(navigator.userAgent)) michael@0: ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) { michael@0: var className = 'HTML' + tag + 'Element'; michael@0: if(window[className]) return; michael@0: var klass = window[className] = {}; michael@0: klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__; michael@0: }); michael@0: michael@0: Element.addMethods = function(methods) { michael@0: Object.extend(Element.Methods, methods || {}); michael@0: michael@0: function copy(methods, destination, onlyIfAbsent) { michael@0: onlyIfAbsent = onlyIfAbsent || false; michael@0: var cache = Element.extend.cache; michael@0: for (var property in methods) { michael@0: var value = methods[property]; michael@0: if (!onlyIfAbsent || !(property in destination)) michael@0: destination[property] = cache.findOrStore(value); michael@0: } michael@0: } michael@0: michael@0: if (typeof HTMLElement != 'undefined') { michael@0: copy(Element.Methods, HTMLElement.prototype); michael@0: copy(Element.Methods.Simulated, HTMLElement.prototype, true); michael@0: copy(Form.Methods, HTMLFormElement.prototype); michael@0: [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) { michael@0: copy(Form.Element.Methods, klass.prototype); michael@0: }); michael@0: _nativeExtensions = true; michael@0: } michael@0: } michael@0: michael@0: var Toggle = new Object(); michael@0: Toggle.display = Element.toggle; michael@0: michael@0: /*--------------------------------------------------------------------------*/ michael@0: michael@0: Abstract.Insertion = function(adjacency) { michael@0: this.adjacency = adjacency; michael@0: } michael@0: michael@0: Abstract.Insertion.prototype = { michael@0: initialize: function(element, content) { michael@0: this.element = $(element); michael@0: this.content = content.stripScripts(); michael@0: michael@0: if (this.adjacency && this.element.insertAdjacentHTML) { michael@0: try { michael@0: this.element.insertAdjacentHTML(this.adjacency, this.content); michael@0: } catch (e) { michael@0: var tagName = this.element.tagName.toUpperCase(); michael@0: if (['TBODY', 'TR'].include(tagName)) { michael@0: this.insertContent(this.contentFromAnonymousTable()); michael@0: } else { michael@0: throw e; michael@0: } michael@0: } michael@0: } else { michael@0: this.range = this.element.ownerDocument.createRange(); michael@0: if (this.initializeRange) this.initializeRange(); michael@0: this.insertContent([this.range.createContextualFragment(this.content)]); michael@0: } michael@0: michael@0: setTimeout(function() {content.evalScripts()}, 10); michael@0: }, michael@0: michael@0: contentFromAnonymousTable: function() { michael@0: var div = document.createElement('div'); michael@0: div.innerHTML = '' + this.content + '
'; michael@0: return $A(div.childNodes[0].childNodes[0].childNodes); michael@0: } michael@0: } michael@0: michael@0: var Insertion = new Object(); michael@0: michael@0: Insertion.Before = Class.create(); michael@0: Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), { michael@0: initializeRange: function() { michael@0: this.range.setStartBefore(this.element); michael@0: }, michael@0: michael@0: insertContent: function(fragments) { michael@0: fragments.each((function(fragment) { michael@0: this.element.parentNode.insertBefore(fragment, this.element); michael@0: }).bind(this)); michael@0: } michael@0: }); michael@0: michael@0: Insertion.Top = Class.create(); michael@0: Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), { michael@0: initializeRange: function() { michael@0: this.range.selectNodeContents(this.element); michael@0: this.range.collapse(true); michael@0: }, michael@0: michael@0: insertContent: function(fragments) { michael@0: fragments.reverse(false).each((function(fragment) { michael@0: this.element.insertBefore(fragment, this.element.firstChild); michael@0: }).bind(this)); michael@0: } michael@0: }); michael@0: michael@0: Insertion.Bottom = Class.create(); michael@0: Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), { michael@0: initializeRange: function() { michael@0: this.range.selectNodeContents(this.element); michael@0: this.range.collapse(this.element); michael@0: }, michael@0: michael@0: insertContent: function(fragments) { michael@0: fragments.each((function(fragment) { michael@0: this.element.appendChild(fragment); michael@0: }).bind(this)); michael@0: } michael@0: }); michael@0: michael@0: Insertion.After = Class.create(); michael@0: Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), { michael@0: initializeRange: function() { michael@0: this.range.setStartAfter(this.element); michael@0: }, michael@0: michael@0: insertContent: function(fragments) { michael@0: fragments.each((function(fragment) { michael@0: this.element.parentNode.insertBefore(fragment, michael@0: this.element.nextSibling); michael@0: }).bind(this)); michael@0: } michael@0: }); michael@0: michael@0: /*--------------------------------------------------------------------------*/ michael@0: michael@0: Element.ClassNames = Class.create(); michael@0: Element.ClassNames.prototype = { michael@0: initialize: function(element) { michael@0: this.element = $(element); michael@0: }, michael@0: michael@0: _each: function(iterator) { michael@0: this.element.className.split(/\s+/).select(function(name) { michael@0: return name.length > 0; michael@0: })._each(iterator); michael@0: }, michael@0: michael@0: set: function(className) { michael@0: this.element.className = className; michael@0: }, michael@0: michael@0: add: function(classNameToAdd) { michael@0: if (this.include(classNameToAdd)) return; michael@0: this.set($A(this).concat(classNameToAdd).join(' ')); michael@0: }, michael@0: michael@0: remove: function(classNameToRemove) { michael@0: if (!this.include(classNameToRemove)) return; michael@0: this.set($A(this).without(classNameToRemove).join(' ')); michael@0: }, michael@0: michael@0: toString: function() { michael@0: return $A(this).join(' '); michael@0: } michael@0: }; michael@0: michael@0: Object.extend(Element.ClassNames.prototype, Enumerable); michael@0: var Selector = Class.create(); michael@0: Selector.prototype = { michael@0: initialize: function(expression) { michael@0: this.params = {classNames: []}; michael@0: this.expression = expression.toString().strip(); michael@0: this.parseExpression(); michael@0: this.compileMatcher(); michael@0: }, michael@0: michael@0: parseExpression: function() { michael@0: function abort(message) { throw 'Parse error in selector: ' + message; } michael@0: michael@0: if (this.expression == '') abort('empty expression'); michael@0: michael@0: var params = this.params, expr = this.expression, match, modifier, clause, rest; michael@0: while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) { michael@0: params.attributes = params.attributes || []; michael@0: params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''}); michael@0: expr = match[1]; michael@0: } michael@0: michael@0: if (expr == '*') return this.params.wildcard = true; michael@0: michael@0: while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) { michael@0: modifier = match[1], clause = match[2], rest = match[3]; michael@0: switch (modifier) { michael@0: case '#': params.id = clause; break; michael@0: case '.': params.classNames.push(clause); break; michael@0: case '': michael@0: case undefined: params.tagName = clause.toUpperCase(); break; michael@0: default: abort(expr.inspect()); michael@0: } michael@0: expr = rest; michael@0: } michael@0: michael@0: if (expr.length > 0) abort(expr.inspect()); michael@0: }, michael@0: michael@0: buildMatchExpression: function() { michael@0: var params = this.params, conditions = [], clause; michael@0: michael@0: if (params.wildcard) michael@0: conditions.push('true'); michael@0: if (clause = params.id) michael@0: conditions.push('element.readAttribute("id") == ' + clause.inspect()); michael@0: if (clause = params.tagName) michael@0: conditions.push('element.tagName.toUpperCase() == ' + clause.inspect()); michael@0: if ((clause = params.classNames).length > 0) michael@0: for (var i = 0, length = clause.length; i < length; i++) michael@0: conditions.push('element.hasClassName(' + clause[i].inspect() + ')'); michael@0: if (clause = params.attributes) { michael@0: clause.each(function(attribute) { michael@0: var value = 'element.readAttribute(' + attribute.name.inspect() + ')'; michael@0: var splitValueBy = function(delimiter) { michael@0: return value + ' && ' + value + '.split(' + delimiter.inspect() + ')'; michael@0: } michael@0: michael@0: switch (attribute.operator) { michael@0: case '=': conditions.push(value + ' == ' + attribute.value.inspect()); break; michael@0: case '~=': conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break; michael@0: case '|=': conditions.push( michael@0: splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect() michael@0: ); break; michael@0: case '!=': conditions.push(value + ' != ' + attribute.value.inspect()); break; michael@0: case '': michael@0: case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break; michael@0: default: throw 'Unknown operator ' + attribute.operator + ' in selector'; michael@0: } michael@0: }); michael@0: } michael@0: michael@0: return conditions.join(' && '); michael@0: }, michael@0: michael@0: compileMatcher: function() { michael@0: this.match = new Function('element', 'if (!element.tagName) return false; \ michael@0: element = $(element); \ michael@0: return ' + this.buildMatchExpression()); michael@0: }, michael@0: michael@0: findElements: function(scope) { michael@0: var element; michael@0: michael@0: if (element = $(this.params.id)) michael@0: if (this.match(element)) michael@0: if (!scope || Element.childOf(element, scope)) michael@0: return [element]; michael@0: michael@0: scope = (scope || document).getElementsByTagName(this.params.tagName || '*'); michael@0: michael@0: var results = []; michael@0: for (var i = 0, length = scope.length; i < length; i++) michael@0: if (this.match(element = scope[i])) michael@0: results.push(Element.extend(element)); michael@0: michael@0: return results; michael@0: }, michael@0: michael@0: toString: function() { michael@0: return this.expression; michael@0: } michael@0: } michael@0: michael@0: Object.extend(Selector, { michael@0: matchElements: function(elements, expression) { michael@0: var selector = new Selector(expression); michael@0: return elements.select(selector.match.bind(selector)).map(Element.extend); michael@0: }, michael@0: michael@0: findElement: function(elements, expression, index) { michael@0: if (typeof expression == 'number') index = expression, expression = false; michael@0: return Selector.matchElements(elements, expression || '*')[index || 0]; michael@0: }, michael@0: michael@0: findChildElements: function(element, expressions) { michael@0: return expressions.map(function(expression) { michael@0: return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) { michael@0: var selector = new Selector(expr); michael@0: return results.inject([], function(elements, result) { michael@0: return elements.concat(selector.findElements(result || element)); michael@0: }); michael@0: }); michael@0: }).flatten(); michael@0: } michael@0: }); michael@0: michael@0: function $$() { michael@0: return Selector.findChildElements(document, $A(arguments)); michael@0: } michael@0: var Form = { michael@0: reset: function(form) { michael@0: $(form).reset(); michael@0: return form; michael@0: }, michael@0: michael@0: serializeElements: function(elements, getHash) { michael@0: var data = elements.inject({}, function(result, element) { michael@0: if (!element.disabled && element.name) { michael@0: var key = element.name, value = $(element).getValue(); michael@0: if (value != undefined) { michael@0: if (result[key]) { michael@0: if (result[key].constructor != Array) result[key] = [result[key]]; michael@0: result[key].push(value); michael@0: } michael@0: else result[key] = value; michael@0: } michael@0: } michael@0: return result; michael@0: }); michael@0: michael@0: return getHash ? data : Hash.toQueryString(data); michael@0: } michael@0: }; michael@0: michael@0: Form.Methods = { michael@0: serialize: function(form, getHash) { michael@0: return Form.serializeElements(Form.getElements(form), getHash); michael@0: }, michael@0: michael@0: getElements: function(form) { michael@0: return $A($(form).getElementsByTagName('*')).inject([], michael@0: function(elements, child) { michael@0: if (Form.Element.Serializers[child.tagName.toLowerCase()]) michael@0: elements.push(Element.extend(child)); michael@0: return elements; michael@0: } michael@0: ); michael@0: }, michael@0: michael@0: getInputs: function(form, typeName, name) { michael@0: form = $(form); michael@0: var inputs = form.getElementsByTagName('input'); michael@0: michael@0: if (!typeName && !name) return $A(inputs).map(Element.extend); michael@0: michael@0: for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) { michael@0: var input = inputs[i]; michael@0: if ((typeName && input.type != typeName) || (name && input.name != name)) michael@0: continue; michael@0: matchingInputs.push(Element.extend(input)); michael@0: } michael@0: michael@0: return matchingInputs; michael@0: }, michael@0: michael@0: disable: function(form) { michael@0: form = $(form); michael@0: form.getElements().each(function(element) { michael@0: element.blur(); michael@0: element.disabled = 'true'; michael@0: }); michael@0: return form; michael@0: }, michael@0: michael@0: enable: function(form) { michael@0: form = $(form); michael@0: form.getElements().each(function(element) { michael@0: element.disabled = ''; michael@0: }); michael@0: return form; michael@0: }, michael@0: michael@0: findFirstElement: function(form) { michael@0: return $(form).getElements().find(function(element) { michael@0: return element.type != 'hidden' && !element.disabled && michael@0: ['input', 'select', 'textarea'].include(element.tagName.toLowerCase()); michael@0: }); michael@0: }, michael@0: michael@0: focusFirstElement: function(form) { michael@0: form = $(form); michael@0: form.findFirstElement().activate(); michael@0: return form; michael@0: } michael@0: } michael@0: michael@0: Object.extend(Form, Form.Methods); michael@0: michael@0: /*--------------------------------------------------------------------------*/ michael@0: michael@0: Form.Element = { michael@0: focus: function(element) { michael@0: $(element).focus(); michael@0: return element; michael@0: }, michael@0: michael@0: select: function(element) { michael@0: $(element).select(); michael@0: return element; michael@0: } michael@0: } michael@0: michael@0: Form.Element.Methods = { michael@0: serialize: function(element) { michael@0: element = $(element); michael@0: if (!element.disabled && element.name) { michael@0: var value = element.getValue(); michael@0: if (value != undefined) { michael@0: var pair = {}; michael@0: pair[element.name] = value; michael@0: return Hash.toQueryString(pair); michael@0: } michael@0: } michael@0: return ''; michael@0: }, michael@0: michael@0: getValue: function(element) { michael@0: element = $(element); michael@0: var method = element.tagName.toLowerCase(); michael@0: return Form.Element.Serializers[method](element); michael@0: }, michael@0: michael@0: clear: function(element) { michael@0: $(element).value = ''; michael@0: return element; michael@0: }, michael@0: michael@0: present: function(element) { michael@0: return $(element).value != ''; michael@0: }, michael@0: michael@0: activate: function(element) { michael@0: element = $(element); michael@0: element.focus(); michael@0: if (element.select && ( element.tagName.toLowerCase() != 'input' || michael@0: !['button', 'reset', 'submit'].include(element.type) ) ) michael@0: element.select(); michael@0: return element; michael@0: }, michael@0: michael@0: disable: function(element) { michael@0: element = $(element); michael@0: element.disabled = true; michael@0: return element; michael@0: }, michael@0: michael@0: enable: function(element) { michael@0: element = $(element); michael@0: element.blur(); michael@0: element.disabled = false; michael@0: return element; michael@0: } michael@0: } michael@0: michael@0: Object.extend(Form.Element, Form.Element.Methods); michael@0: var Field = Form.Element; michael@0: var $F = Form.Element.getValue; michael@0: michael@0: /*--------------------------------------------------------------------------*/ michael@0: michael@0: Form.Element.Serializers = { michael@0: input: function(element) { michael@0: switch (element.type.toLowerCase()) { michael@0: case 'checkbox': michael@0: case 'radio': michael@0: return Form.Element.Serializers.inputSelector(element); michael@0: default: michael@0: return Form.Element.Serializers.textarea(element); michael@0: } michael@0: }, michael@0: michael@0: inputSelector: function(element) { michael@0: return element.checked ? element.value : null; michael@0: }, michael@0: michael@0: textarea: function(element) { michael@0: return element.value; michael@0: }, michael@0: michael@0: select: function(element) { michael@0: return this[element.type == 'select-one' ? michael@0: 'selectOne' : 'selectMany'](element); michael@0: }, michael@0: michael@0: selectOne: function(element) { michael@0: var index = element.selectedIndex; michael@0: return index >= 0 ? this.optionValue(element.options[index]) : null; michael@0: }, michael@0: michael@0: selectMany: function(element) { michael@0: var values, length = element.length; michael@0: if (!length) return null; michael@0: michael@0: for (var i = 0, values = []; i < length; i++) { michael@0: var opt = element.options[i]; michael@0: if (opt.selected) values.push(this.optionValue(opt)); michael@0: } michael@0: return values; michael@0: }, michael@0: michael@0: optionValue: function(opt) { michael@0: // extend element because hasAttribute may not be native michael@0: return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text; michael@0: } michael@0: } michael@0: michael@0: /*--------------------------------------------------------------------------*/ michael@0: michael@0: Abstract.TimedObserver = function() {} michael@0: Abstract.TimedObserver.prototype = { michael@0: initialize: function(element, frequency, callback) { michael@0: this.frequency = frequency; michael@0: this.element = $(element); michael@0: this.callback = callback; michael@0: michael@0: this.lastValue = this.getValue(); michael@0: this.registerCallback(); michael@0: }, michael@0: michael@0: registerCallback: function() { michael@0: setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); michael@0: }, michael@0: michael@0: onTimerEvent: function() { michael@0: var value = this.getValue(); michael@0: var changed = ('string' == typeof this.lastValue && 'string' == typeof value michael@0: ? this.lastValue != value : String(this.lastValue) != String(value)); michael@0: if (changed) { michael@0: this.callback(this.element, value); michael@0: this.lastValue = value; michael@0: } michael@0: } michael@0: } michael@0: michael@0: Form.Element.Observer = Class.create(); michael@0: Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), { michael@0: getValue: function() { michael@0: return Form.Element.getValue(this.element); michael@0: } michael@0: }); michael@0: michael@0: Form.Observer = Class.create(); michael@0: Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), { michael@0: getValue: function() { michael@0: return Form.serialize(this.element); michael@0: } michael@0: }); michael@0: michael@0: /*--------------------------------------------------------------------------*/ michael@0: michael@0: Abstract.EventObserver = function() {} michael@0: Abstract.EventObserver.prototype = { michael@0: initialize: function(element, callback) { michael@0: this.element = $(element); michael@0: this.callback = callback; michael@0: michael@0: this.lastValue = this.getValue(); michael@0: if (this.element.tagName.toLowerCase() == 'form') michael@0: this.registerFormCallbacks(); michael@0: else michael@0: this.registerCallback(this.element); michael@0: }, michael@0: michael@0: onElementEvent: function() { michael@0: var value = this.getValue(); michael@0: if (this.lastValue != value) { michael@0: this.callback(this.element, value); michael@0: this.lastValue = value; michael@0: } michael@0: }, michael@0: michael@0: registerFormCallbacks: function() { michael@0: Form.getElements(this.element).each(this.registerCallback.bind(this)); michael@0: }, michael@0: michael@0: registerCallback: function(element) { michael@0: if (element.type) { michael@0: switch (element.type.toLowerCase()) { michael@0: case 'checkbox': michael@0: case 'radio': michael@0: Event.observe(element, 'click', this.onElementEvent.bind(this)); michael@0: break; michael@0: default: michael@0: Event.observe(element, 'change', this.onElementEvent.bind(this)); michael@0: break; michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: Form.Element.EventObserver = Class.create(); michael@0: Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), { michael@0: getValue: function() { michael@0: return Form.Element.getValue(this.element); michael@0: } michael@0: }); michael@0: michael@0: Form.EventObserver = Class.create(); michael@0: Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), { michael@0: getValue: function() { michael@0: return Form.serialize(this.element); michael@0: } michael@0: }); michael@0: if (!window.Event) { michael@0: var Event = new Object(); michael@0: } michael@0: michael@0: Object.extend(Event, { michael@0: KEY_BACKSPACE: 8, michael@0: KEY_TAB: 9, michael@0: KEY_RETURN: 13, michael@0: KEY_ESC: 27, michael@0: KEY_LEFT: 37, michael@0: KEY_UP: 38, michael@0: KEY_RIGHT: 39, michael@0: KEY_DOWN: 40, michael@0: KEY_DELETE: 46, michael@0: KEY_HOME: 36, michael@0: KEY_END: 35, michael@0: KEY_PAGEUP: 33, michael@0: KEY_PAGEDOWN: 34, michael@0: michael@0: element: function(event) { michael@0: return event.target || event.srcElement; michael@0: }, michael@0: michael@0: isLeftClick: function(event) { michael@0: return (((event.which) && (event.which == 1)) || michael@0: ((event.button) && (event.button == 1))); michael@0: }, michael@0: michael@0: pointerX: function(event) { michael@0: return event.pageX || (event.clientX + michael@0: (document.documentElement.scrollLeft || document.body.scrollLeft)); michael@0: }, michael@0: michael@0: pointerY: function(event) { michael@0: return event.pageY || (event.clientY + michael@0: (document.documentElement.scrollTop || document.body.scrollTop)); michael@0: }, michael@0: michael@0: stop: function(event) { michael@0: if (event.preventDefault) { michael@0: event.preventDefault(); michael@0: event.stopPropagation(); michael@0: } else { michael@0: event.returnValue = false; michael@0: event.cancelBubble = true; michael@0: } michael@0: }, michael@0: michael@0: // find the first node with the given tagName, starting from the michael@0: // node the event was triggered on; traverses the DOM upwards michael@0: findElement: function(event, tagName) { michael@0: var element = Event.element(event); michael@0: while (element.parentNode && (!element.tagName || michael@0: (element.tagName.toUpperCase() != tagName.toUpperCase()))) michael@0: element = element.parentNode; michael@0: return element; michael@0: }, michael@0: michael@0: observers: false, michael@0: michael@0: _observeAndCache: function(element, name, observer, useCapture) { michael@0: if (!this.observers) this.observers = []; michael@0: if (element.addEventListener) { michael@0: this.observers.push([element, name, observer, useCapture]); michael@0: element.addEventListener(name, observer, useCapture); michael@0: } else if (element.attachEvent) { michael@0: this.observers.push([element, name, observer, useCapture]); michael@0: element.attachEvent('on' + name, observer); michael@0: } michael@0: }, michael@0: michael@0: unloadCache: function() { michael@0: if (!Event.observers) return; michael@0: for (var i = 0, length = Event.observers.length; i < length; i++) { michael@0: Event.stopObserving.apply(this, Event.observers[i]); michael@0: Event.observers[i][0] = null; michael@0: } michael@0: Event.observers = false; michael@0: }, michael@0: michael@0: observe: function(element, name, observer, useCapture) { michael@0: element = $(element); michael@0: useCapture = useCapture || false; michael@0: michael@0: if (name == 'keypress' && michael@0: (navigator.appVersion.match(/Konqueror|Safari|KHTML/) michael@0: || element.attachEvent)) michael@0: name = 'keydown'; michael@0: michael@0: Event._observeAndCache(element, name, observer, useCapture); michael@0: }, michael@0: michael@0: stopObserving: function(element, name, observer, useCapture) { michael@0: element = $(element); michael@0: useCapture = useCapture || false; michael@0: michael@0: if (name == 'keypress' && michael@0: (navigator.appVersion.match(/Konqueror|Safari|KHTML/) michael@0: || element.detachEvent)) michael@0: name = 'keydown'; michael@0: michael@0: if (element.removeEventListener) { michael@0: element.removeEventListener(name, observer, useCapture); michael@0: } else if (element.detachEvent) { michael@0: try { michael@0: element.detachEvent('on' + name, observer); michael@0: } catch (e) {} michael@0: } michael@0: } michael@0: }); michael@0: michael@0: /* prevent memory leaks in IE */ michael@0: if (navigator.appVersion.match(/\bMSIE\b/)) michael@0: Event.observe(window, 'unload', Event.unloadCache, false); michael@0: var Position = { michael@0: // set to true if needed, warning: firefox performance problems michael@0: // NOT neeeded for page scrolling, only if draggable contained in michael@0: // scrollable elements michael@0: includeScrollOffsets: false, michael@0: michael@0: // must be called before calling withinIncludingScrolloffset, every time the michael@0: // page is scrolled michael@0: prepare: function() { michael@0: this.deltaX = window.pageXOffset michael@0: || document.documentElement.scrollLeft michael@0: || document.body.scrollLeft michael@0: || 0; michael@0: this.deltaY = window.pageYOffset michael@0: || document.documentElement.scrollTop michael@0: || document.body.scrollTop michael@0: || 0; michael@0: }, michael@0: michael@0: realOffset: function(element) { michael@0: var valueT = 0, valueL = 0; michael@0: do { michael@0: valueT += element.scrollTop || 0; michael@0: valueL += element.scrollLeft || 0; michael@0: element = element.parentNode; michael@0: } while (element); michael@0: return [valueL, valueT]; michael@0: }, michael@0: michael@0: cumulativeOffset: function(element) { michael@0: var valueT = 0, valueL = 0; michael@0: do { michael@0: valueT += element.offsetTop || 0; michael@0: valueL += element.offsetLeft || 0; michael@0: element = element.offsetParent; michael@0: } while (element); michael@0: return [valueL, valueT]; michael@0: }, michael@0: michael@0: positionedOffset: function(element) { michael@0: var valueT = 0, valueL = 0; michael@0: do { michael@0: valueT += element.offsetTop || 0; michael@0: valueL += element.offsetLeft || 0; michael@0: element = element.offsetParent; michael@0: if (element) { michael@0: if(element.tagName=='BODY') break; michael@0: var p = Element.getStyle(element, 'position'); michael@0: if (p == 'relative' || p == 'absolute') break; michael@0: } michael@0: } while (element); michael@0: return [valueL, valueT]; michael@0: }, michael@0: michael@0: offsetParent: function(element) { michael@0: if (element.offsetParent) return element.offsetParent; michael@0: if (element == document.body) return element; michael@0: michael@0: while ((element = element.parentNode) && element != document.body) michael@0: if (Element.getStyle(element, 'position') != 'static') michael@0: return element; michael@0: michael@0: return document.body; michael@0: }, michael@0: michael@0: // caches x/y coordinate pair to use with overlap michael@0: within: function(element, x, y) { michael@0: if (this.includeScrollOffsets) michael@0: return this.withinIncludingScrolloffsets(element, x, y); michael@0: this.xcomp = x; michael@0: this.ycomp = y; michael@0: this.offset = this.cumulativeOffset(element); michael@0: michael@0: return (y >= this.offset[1] && michael@0: y < this.offset[1] + element.offsetHeight && michael@0: x >= this.offset[0] && michael@0: x < this.offset[0] + element.offsetWidth); michael@0: }, michael@0: michael@0: withinIncludingScrolloffsets: function(element, x, y) { michael@0: var offsetcache = this.realOffset(element); michael@0: michael@0: this.xcomp = x + offsetcache[0] - this.deltaX; michael@0: this.ycomp = y + offsetcache[1] - this.deltaY; michael@0: this.offset = this.cumulativeOffset(element); michael@0: michael@0: return (this.ycomp >= this.offset[1] && michael@0: this.ycomp < this.offset[1] + element.offsetHeight && michael@0: this.xcomp >= this.offset[0] && michael@0: this.xcomp < this.offset[0] + element.offsetWidth); michael@0: }, michael@0: michael@0: // within must be called directly before michael@0: overlap: function(mode, element) { michael@0: if (!mode) return 0; michael@0: if (mode == 'vertical') michael@0: return ((this.offset[1] + element.offsetHeight) - this.ycomp) / michael@0: element.offsetHeight; michael@0: if (mode == 'horizontal') michael@0: return ((this.offset[0] + element.offsetWidth) - this.xcomp) / michael@0: element.offsetWidth; michael@0: }, michael@0: michael@0: page: function(forElement) { michael@0: var valueT = 0, valueL = 0; michael@0: michael@0: var element = forElement; michael@0: do { michael@0: valueT += element.offsetTop || 0; michael@0: valueL += element.offsetLeft || 0; michael@0: michael@0: // Safari fix michael@0: if (element.offsetParent==document.body) michael@0: if (Element.getStyle(element,'position')=='absolute') break; michael@0: michael@0: } while (element = element.offsetParent); michael@0: michael@0: element = forElement; michael@0: do { michael@0: if (!window.opera || element.tagName=='BODY') { michael@0: valueT -= element.scrollTop || 0; michael@0: valueL -= element.scrollLeft || 0; michael@0: } michael@0: } while (element = element.parentNode); michael@0: michael@0: return [valueL, valueT]; michael@0: }, michael@0: michael@0: clone: function(source, target) { michael@0: var options = Object.extend({ michael@0: setLeft: true, michael@0: setTop: true, michael@0: setWidth: true, michael@0: setHeight: true, michael@0: offsetTop: 0, michael@0: offsetLeft: 0 michael@0: }, arguments[2] || {}) michael@0: michael@0: // find page position of source michael@0: source = $(source); michael@0: var p = Position.page(source); michael@0: michael@0: // find coordinate system to use michael@0: target = $(target); michael@0: var delta = [0, 0]; michael@0: var parent = null; michael@0: // delta [0,0] will do fine with position: fixed elements, michael@0: // position:absolute needs offsetParent deltas michael@0: if (Element.getStyle(target,'position') == 'absolute') { michael@0: parent = Position.offsetParent(target); michael@0: delta = Position.page(parent); michael@0: } michael@0: michael@0: // correct by body offsets (fixes Safari) michael@0: if (parent == document.body) { michael@0: delta[0] -= document.body.offsetLeft; michael@0: delta[1] -= document.body.offsetTop; michael@0: } michael@0: michael@0: // set position michael@0: if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; michael@0: if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; michael@0: if(options.setWidth) target.style.width = source.offsetWidth + 'px'; michael@0: if(options.setHeight) target.style.height = source.offsetHeight + 'px'; michael@0: }, michael@0: michael@0: absolutize: function(element) { michael@0: element = $(element); michael@0: if (element.style.position == 'absolute') return; michael@0: Position.prepare(); michael@0: michael@0: var offsets = Position.positionedOffset(element); michael@0: var top = offsets[1]; michael@0: var left = offsets[0]; michael@0: var width = element.clientWidth; michael@0: var height = element.clientHeight; michael@0: michael@0: element._originalLeft = left - parseFloat(element.style.left || 0); michael@0: element._originalTop = top - parseFloat(element.style.top || 0); michael@0: element._originalWidth = element.style.width; michael@0: element._originalHeight = element.style.height; michael@0: michael@0: element.style.position = 'absolute'; michael@0: element.style.top = top + 'px'; michael@0: element.style.left = left + 'px'; michael@0: element.style.width = width + 'px'; michael@0: element.style.height = height + 'px'; michael@0: }, michael@0: michael@0: relativize: function(element) { michael@0: element = $(element); michael@0: if (element.style.position == 'relative') return; michael@0: Position.prepare(); michael@0: michael@0: element.style.position = 'relative'; michael@0: var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); michael@0: var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); michael@0: michael@0: element.style.top = top + 'px'; michael@0: element.style.left = left + 'px'; michael@0: element.style.height = element._originalHeight; michael@0: element.style.width = element._originalWidth; michael@0: } michael@0: } michael@0: michael@0: // Safari returns margins on body which is incorrect if the child is absolutely michael@0: // positioned. For performance reasons, redefine Position.cumulativeOffset for michael@0: // KHTML/WebKit only. michael@0: if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) { michael@0: Position.cumulativeOffset = function(element) { michael@0: var valueT = 0, valueL = 0; michael@0: do { michael@0: valueT += element.offsetTop || 0; michael@0: valueL += element.offsetLeft || 0; michael@0: if (element.offsetParent == document.body) michael@0: if (Element.getStyle(element, 'position') == 'absolute') break; michael@0: michael@0: element = element.offsetParent; michael@0: } while (element); michael@0: michael@0: return [valueL, valueT]; michael@0: } michael@0: } michael@0: michael@0: Element.addMethods(); michael@0: michael@0: michael@0: // ------------------------------------------------------------------------ michael@0: // ------------------------------------------------------------------------ michael@0: michael@0: // The rest of this file is the actual ray tracer written by Adam michael@0: // Burmister. It's a concatenation of the following files: michael@0: // michael@0: // flog/color.js michael@0: // flog/light.js michael@0: // flog/vector.js michael@0: // flog/ray.js michael@0: // flog/scene.js michael@0: // flog/material/basematerial.js michael@0: // flog/material/solid.js michael@0: // flog/material/chessboard.js michael@0: // flog/shape/baseshape.js michael@0: // flog/shape/sphere.js michael@0: // flog/shape/plane.js michael@0: // flog/intersectioninfo.js michael@0: // flog/camera.js michael@0: // flog/background.js michael@0: // flog/engine.js michael@0: michael@0: michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: michael@0: Flog.RayTracer.Color = Class.create(); michael@0: michael@0: Flog.RayTracer.Color.prototype = { michael@0: red : 0.0, michael@0: green : 0.0, michael@0: blue : 0.0, michael@0: michael@0: initialize : function(r, g, b) { michael@0: if(!r) r = 0.0; michael@0: if(!g) g = 0.0; michael@0: if(!b) b = 0.0; michael@0: michael@0: this.red = r; michael@0: this.green = g; michael@0: this.blue = b; michael@0: }, michael@0: michael@0: add : function(c1, c2){ michael@0: var result = new Flog.RayTracer.Color(0,0,0); michael@0: michael@0: result.red = c1.red + c2.red; michael@0: result.green = c1.green + c2.green; michael@0: result.blue = c1.blue + c2.blue; michael@0: michael@0: return result; michael@0: }, michael@0: michael@0: addScalar: function(c1, s){ michael@0: var result = new Flog.RayTracer.Color(0,0,0); michael@0: michael@0: result.red = c1.red + s; michael@0: result.green = c1.green + s; michael@0: result.blue = c1.blue + s; michael@0: michael@0: result.limit(); michael@0: michael@0: return result; michael@0: }, michael@0: michael@0: subtract: function(c1, c2){ michael@0: var result = new Flog.RayTracer.Color(0,0,0); michael@0: michael@0: result.red = c1.red - c2.red; michael@0: result.green = c1.green - c2.green; michael@0: result.blue = c1.blue - c2.blue; michael@0: michael@0: return result; michael@0: }, michael@0: michael@0: multiply : function(c1, c2) { michael@0: var result = new Flog.RayTracer.Color(0,0,0); michael@0: michael@0: result.red = c1.red * c2.red; michael@0: result.green = c1.green * c2.green; michael@0: result.blue = c1.blue * c2.blue; michael@0: michael@0: return result; michael@0: }, michael@0: michael@0: multiplyScalar : function(c1, f) { michael@0: var result = new Flog.RayTracer.Color(0,0,0); michael@0: michael@0: result.red = c1.red * f; michael@0: result.green = c1.green * f; michael@0: result.blue = c1.blue * f; michael@0: michael@0: return result; michael@0: }, michael@0: michael@0: divideFactor : function(c1, f) { michael@0: var result = new Flog.RayTracer.Color(0,0,0); michael@0: michael@0: result.red = c1.red / f; michael@0: result.green = c1.green / f; michael@0: result.blue = c1.blue / f; michael@0: michael@0: return result; michael@0: }, michael@0: michael@0: limit: function(){ michael@0: this.red = (this.red > 0.0) ? ( (this.red > 1.0) ? 1.0 : this.red ) : 0.0; michael@0: this.green = (this.green > 0.0) ? ( (this.green > 1.0) ? 1.0 : this.green ) : 0.0; michael@0: this.blue = (this.blue > 0.0) ? ( (this.blue > 1.0) ? 1.0 : this.blue ) : 0.0; michael@0: }, michael@0: michael@0: distance : function(color) { michael@0: var d = Math.abs(this.red - color.red) + Math.abs(this.green - color.green) + Math.abs(this.blue - color.blue); michael@0: return d; michael@0: }, michael@0: michael@0: blend: function(c1, c2, w){ michael@0: var result = new Flog.RayTracer.Color(0,0,0); michael@0: result = Flog.RayTracer.Color.prototype.add( michael@0: Flog.RayTracer.Color.prototype.multiplyScalar(c1, 1 - w), michael@0: Flog.RayTracer.Color.prototype.multiplyScalar(c2, w) michael@0: ); michael@0: return result; michael@0: }, michael@0: michael@0: toString : function () { michael@0: var r = Math.floor(this.red*255); michael@0: var g = Math.floor(this.green*255); michael@0: var b = Math.floor(this.blue*255); michael@0: michael@0: return "rgb("+ r +","+ g +","+ b +")"; michael@0: } michael@0: } michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: michael@0: Flog.RayTracer.Light = Class.create(); michael@0: michael@0: Flog.RayTracer.Light.prototype = { michael@0: position: null, michael@0: color: null, michael@0: intensity: 10.0, michael@0: michael@0: initialize : function(pos, color, intensity) { michael@0: this.position = pos; michael@0: this.color = color; michael@0: this.intensity = (intensity ? intensity : 10.0); michael@0: }, michael@0: michael@0: getIntensity: function(distance){ michael@0: if(distance >= intensity) return 0; michael@0: michael@0: return Math.pow((intensity - distance) / strength, 0.2); michael@0: }, michael@0: michael@0: toString : function () { michael@0: return 'Light [' + this.position.x + ',' + this.position.y + ',' + this.position.z + ']'; michael@0: } michael@0: } michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: michael@0: Flog.RayTracer.Vector = Class.create(); michael@0: michael@0: Flog.RayTracer.Vector.prototype = { michael@0: x : 0.0, michael@0: y : 0.0, michael@0: z : 0.0, michael@0: michael@0: initialize : function(x, y, z) { michael@0: this.x = (x ? x : 0); michael@0: this.y = (y ? y : 0); michael@0: this.z = (z ? z : 0); michael@0: }, michael@0: michael@0: copy: function(vector){ michael@0: this.x = vector.x; michael@0: this.y = vector.y; michael@0: this.z = vector.z; michael@0: }, michael@0: michael@0: normalize : function() { michael@0: var m = this.magnitude(); michael@0: return new Flog.RayTracer.Vector(this.x / m, this.y / m, this.z / m); michael@0: }, michael@0: michael@0: magnitude : function() { michael@0: return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z)); michael@0: }, michael@0: michael@0: cross : function(w) { michael@0: return new Flog.RayTracer.Vector( michael@0: -this.z * w.y + this.y * w.z, michael@0: this.z * w.x - this.x * w.z, michael@0: -this.y * w.x + this.x * w.y); michael@0: }, michael@0: michael@0: dot : function(w) { michael@0: return this.x * w.x + this.y * w.y + this.z * w.z; michael@0: }, michael@0: michael@0: add : function(v, w) { michael@0: return new Flog.RayTracer.Vector(w.x + v.x, w.y + v.y, w.z + v.z); michael@0: }, michael@0: michael@0: subtract : function(v, w) { michael@0: if(!w || !v) throw 'Vectors must be defined [' + v + ',' + w + ']'; michael@0: return new Flog.RayTracer.Vector(v.x - w.x, v.y - w.y, v.z - w.z); michael@0: }, michael@0: michael@0: multiplyVector : function(v, w) { michael@0: return new Flog.RayTracer.Vector(v.x * w.x, v.y * w.y, v.z * w.z); michael@0: }, michael@0: michael@0: multiplyScalar : function(v, w) { michael@0: return new Flog.RayTracer.Vector(v.x * w, v.y * w, v.z * w); michael@0: }, michael@0: michael@0: toString : function () { michael@0: return 'Vector [' + this.x + ',' + this.y + ',' + this.z + ']'; michael@0: } michael@0: } michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: michael@0: Flog.RayTracer.Ray = Class.create(); michael@0: michael@0: Flog.RayTracer.Ray.prototype = { michael@0: position : null, michael@0: direction : null, michael@0: initialize : function(pos, dir) { michael@0: this.position = pos; michael@0: this.direction = dir; michael@0: }, michael@0: michael@0: toString : function () { michael@0: return 'Ray [' + this.position + ',' + this.direction + ']'; michael@0: } michael@0: } michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: michael@0: Flog.RayTracer.Scene = Class.create(); michael@0: michael@0: Flog.RayTracer.Scene.prototype = { michael@0: camera : null, michael@0: shapes : [], michael@0: lights : [], michael@0: background : null, michael@0: michael@0: initialize : function() { michael@0: this.camera = new Flog.RayTracer.Camera( michael@0: new Flog.RayTracer.Vector(0,0,-5), michael@0: new Flog.RayTracer.Vector(0,0,1), michael@0: new Flog.RayTracer.Vector(0,1,0) michael@0: ); michael@0: this.shapes = new Array(); michael@0: this.lights = new Array(); michael@0: this.background = new Flog.RayTracer.Background(new Flog.RayTracer.Color(0,0,0.5), 0.2); michael@0: } michael@0: } michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: if(typeof(Flog.RayTracer.Material) == 'undefined') Flog.RayTracer.Material = {}; michael@0: michael@0: Flog.RayTracer.Material.BaseMaterial = Class.create(); michael@0: michael@0: Flog.RayTracer.Material.BaseMaterial.prototype = { michael@0: michael@0: gloss: 2.0, // [0...infinity] 0 = matt michael@0: transparency: 0.0, // 0=opaque michael@0: reflection: 0.0, // [0...infinity] 0 = no reflection michael@0: refraction: 0.50, michael@0: hasTexture: false, michael@0: michael@0: initialize : function() { michael@0: michael@0: }, michael@0: michael@0: getColor: function(u, v){ michael@0: michael@0: }, michael@0: michael@0: wrapUp: function(t){ michael@0: t = t % 2.0; michael@0: if(t < -1) t += 2.0; michael@0: if(t >= 1) t -= 2.0; michael@0: return t; michael@0: }, michael@0: michael@0: toString : function () { michael@0: return 'Material [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; michael@0: } michael@0: } michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: michael@0: Flog.RayTracer.Material.Solid = Class.create(); michael@0: michael@0: Flog.RayTracer.Material.Solid.prototype = Object.extend( michael@0: new Flog.RayTracer.Material.BaseMaterial(), { michael@0: initialize : function(color, reflection, refraction, transparency, gloss) { michael@0: this.color = color; michael@0: this.reflection = reflection; michael@0: this.transparency = transparency; michael@0: this.gloss = gloss; michael@0: this.hasTexture = false; michael@0: }, michael@0: michael@0: getColor: function(u, v){ michael@0: return this.color; michael@0: }, michael@0: michael@0: toString : function () { michael@0: return 'SolidMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; michael@0: } michael@0: } michael@0: ); michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: michael@0: Flog.RayTracer.Material.Chessboard = Class.create(); michael@0: michael@0: Flog.RayTracer.Material.Chessboard.prototype = Object.extend( michael@0: new Flog.RayTracer.Material.BaseMaterial(), { michael@0: colorEven: null, michael@0: colorOdd: null, michael@0: density: 0.5, michael@0: michael@0: initialize : function(colorEven, colorOdd, reflection, transparency, gloss, density) { michael@0: this.colorEven = colorEven; michael@0: this.colorOdd = colorOdd; michael@0: this.reflection = reflection; michael@0: this.transparency = transparency; michael@0: this.gloss = gloss; michael@0: this.density = density; michael@0: this.hasTexture = true; michael@0: }, michael@0: michael@0: getColor: function(u, v){ michael@0: var t = this.wrapUp(u * this.density) * this.wrapUp(v * this.density); michael@0: michael@0: if(t < 0.0) michael@0: return this.colorEven; michael@0: else michael@0: return this.colorOdd; michael@0: }, michael@0: michael@0: toString : function () { michael@0: return 'ChessMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; michael@0: } michael@0: } michael@0: ); michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {}; michael@0: michael@0: Flog.RayTracer.Shape.BaseShape = Class.create(); michael@0: michael@0: Flog.RayTracer.Shape.BaseShape.prototype = { michael@0: position: null, michael@0: material: null, michael@0: michael@0: initialize : function() { michael@0: this.position = new Vector(0,0,0); michael@0: this.material = new Flog.RayTracer.Material.SolidMaterial( michael@0: new Flog.RayTracer.Color(1,0,1), michael@0: 0, michael@0: 0, michael@0: 0 michael@0: ); michael@0: }, michael@0: michael@0: toString : function () { michael@0: return 'Material [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; michael@0: } michael@0: } michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {}; michael@0: michael@0: Flog.RayTracer.Shape.Sphere = Class.create(); michael@0: michael@0: Flog.RayTracer.Shape.Sphere.prototype = { michael@0: initialize : function(pos, radius, material) { michael@0: this.radius = radius; michael@0: this.position = pos; michael@0: this.material = material; michael@0: }, michael@0: michael@0: intersect: function(ray){ michael@0: var info = new Flog.RayTracer.IntersectionInfo(); michael@0: info.shape = this; michael@0: michael@0: var dst = Flog.RayTracer.Vector.prototype.subtract(ray.position, this.position); michael@0: michael@0: var B = dst.dot(ray.direction); michael@0: var C = dst.dot(dst) - (this.radius * this.radius); michael@0: var D = (B * B) - C; michael@0: michael@0: if(D > 0){ // intersection! michael@0: info.isHit = true; michael@0: info.distance = (-B) - Math.sqrt(D); michael@0: info.position = Flog.RayTracer.Vector.prototype.add( michael@0: ray.position, michael@0: Flog.RayTracer.Vector.prototype.multiplyScalar( michael@0: ray.direction, michael@0: info.distance michael@0: ) michael@0: ); michael@0: info.normal = Flog.RayTracer.Vector.prototype.subtract( michael@0: info.position, michael@0: this.position michael@0: ).normalize(); michael@0: michael@0: info.color = this.material.getColor(0,0); michael@0: } else { michael@0: info.isHit = false; michael@0: } michael@0: return info; michael@0: }, michael@0: michael@0: toString : function () { michael@0: return 'Sphere [position=' + this.position + ', radius=' + this.radius + ']'; michael@0: } michael@0: } michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {}; michael@0: michael@0: Flog.RayTracer.Shape.Plane = Class.create(); michael@0: michael@0: Flog.RayTracer.Shape.Plane.prototype = { michael@0: d: 0.0, michael@0: michael@0: initialize : function(pos, d, material) { michael@0: this.position = pos; michael@0: this.d = d; michael@0: this.material = material; michael@0: }, michael@0: michael@0: intersect: function(ray){ michael@0: var info = new Flog.RayTracer.IntersectionInfo(); michael@0: michael@0: var Vd = this.position.dot(ray.direction); michael@0: if(Vd == 0) return info; // no intersection michael@0: michael@0: var t = -(this.position.dot(ray.position) + this.d) / Vd; michael@0: if(t <= 0) return info; michael@0: michael@0: info.shape = this; michael@0: info.isHit = true; michael@0: info.position = Flog.RayTracer.Vector.prototype.add( michael@0: ray.position, michael@0: Flog.RayTracer.Vector.prototype.multiplyScalar( michael@0: ray.direction, michael@0: t michael@0: ) michael@0: ); michael@0: info.normal = this.position; michael@0: info.distance = t; michael@0: michael@0: if(this.material.hasTexture){ michael@0: var vU = new Flog.RayTracer.Vector(this.position.y, this.position.z, -this.position.x); michael@0: var vV = vU.cross(this.position); michael@0: var u = info.position.dot(vU); michael@0: var v = info.position.dot(vV); michael@0: info.color = this.material.getColor(u,v); michael@0: } else { michael@0: info.color = this.material.getColor(0,0); michael@0: } michael@0: michael@0: return info; michael@0: }, michael@0: michael@0: toString : function () { michael@0: return 'Plane [' + this.position + ', d=' + this.d + ']'; michael@0: } michael@0: } michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: michael@0: Flog.RayTracer.IntersectionInfo = Class.create(); michael@0: michael@0: Flog.RayTracer.IntersectionInfo.prototype = { michael@0: isHit: false, michael@0: hitCount: 0, michael@0: shape: null, michael@0: position: null, michael@0: normal: null, michael@0: color: null, michael@0: distance: null, michael@0: michael@0: initialize : function() { michael@0: this.color = new Flog.RayTracer.Color(0,0,0); michael@0: }, michael@0: michael@0: toString : function () { michael@0: return 'Intersection [' + this.position + ']'; michael@0: } michael@0: } michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: michael@0: Flog.RayTracer.Camera = Class.create(); michael@0: michael@0: Flog.RayTracer.Camera.prototype = { michael@0: position: null, michael@0: lookAt: null, michael@0: equator: null, michael@0: up: null, michael@0: screen: null, michael@0: michael@0: initialize : function(pos, lookAt, up) { michael@0: this.position = pos; michael@0: this.lookAt = lookAt; michael@0: this.up = up; michael@0: this.equator = lookAt.normalize().cross(this.up); michael@0: this.screen = Flog.RayTracer.Vector.prototype.add(this.position, this.lookAt); michael@0: }, michael@0: michael@0: getRay: function(vx, vy){ michael@0: var pos = Flog.RayTracer.Vector.prototype.subtract( michael@0: this.screen, michael@0: Flog.RayTracer.Vector.prototype.subtract( michael@0: Flog.RayTracer.Vector.prototype.multiplyScalar(this.equator, vx), michael@0: Flog.RayTracer.Vector.prototype.multiplyScalar(this.up, vy) michael@0: ) michael@0: ); michael@0: pos.y = pos.y * -1; michael@0: var dir = Flog.RayTracer.Vector.prototype.subtract( michael@0: pos, michael@0: this.position michael@0: ); michael@0: michael@0: var ray = new Flog.RayTracer.Ray(pos, dir.normalize()); michael@0: michael@0: return ray; michael@0: }, michael@0: michael@0: toString : function () { michael@0: return 'Ray []'; michael@0: } michael@0: } michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: michael@0: Flog.RayTracer.Background = Class.create(); michael@0: michael@0: Flog.RayTracer.Background.prototype = { michael@0: color : null, michael@0: ambience : 0.0, michael@0: michael@0: initialize : function(color, ambience) { michael@0: this.color = color; michael@0: this.ambience = ambience; michael@0: } michael@0: } michael@0: /* Fake a Flog.* namespace */ michael@0: if(typeof(Flog) == 'undefined') var Flog = {}; michael@0: if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; michael@0: michael@0: Flog.RayTracer.Engine = Class.create(); michael@0: michael@0: Flog.RayTracer.Engine.prototype = { michael@0: canvas: null, /* 2d context we can render to */ michael@0: michael@0: initialize: function(options){ michael@0: this.options = Object.extend({ michael@0: canvasHeight: 100, michael@0: canvasWidth: 100, michael@0: pixelWidth: 2, michael@0: pixelHeight: 2, michael@0: renderDiffuse: false, michael@0: renderShadows: false, michael@0: renderHighlights: false, michael@0: renderReflections: false, michael@0: rayDepth: 2 michael@0: }, options || {}); michael@0: michael@0: this.options.canvasHeight /= this.options.pixelHeight; michael@0: this.options.canvasWidth /= this.options.pixelWidth; michael@0: michael@0: /* TODO: dynamically include other scripts */ michael@0: }, michael@0: michael@0: setPixel: function(x, y, color){ michael@0: var pxW, pxH; michael@0: pxW = this.options.pixelWidth; michael@0: pxH = this.options.pixelHeight; michael@0: michael@0: if (this.canvas) { michael@0: this.canvas.fillStyle = color.toString(); michael@0: this.canvas.fillRect (x * pxW, y * pxH, pxW, pxH); michael@0: } else { michael@0: // print(x * pxW, y * pxH, pxW, pxH); michael@0: } michael@0: }, michael@0: michael@0: renderScene: function(scene, canvas){ michael@0: /* Get canvas */ michael@0: if (canvas) { michael@0: this.canvas = canvas.getContext("2d"); michael@0: } else { michael@0: this.canvas = null; michael@0: } michael@0: michael@0: var canvasHeight = this.options.canvasHeight; michael@0: var canvasWidth = this.options.canvasWidth; michael@0: michael@0: for(var y=0; y < canvasHeight; y++){ michael@0: for(var x=0; x < canvasWidth; x++){ michael@0: var yp = y * 1.0 / canvasHeight * 2 - 1; michael@0: var xp = x * 1.0 / canvasWidth * 2 - 1; michael@0: michael@0: var ray = scene.camera.getRay(xp, yp); michael@0: michael@0: var color = this.getPixelColor(ray, scene); michael@0: michael@0: this.setPixel(x, y, color); michael@0: } michael@0: } michael@0: }, michael@0: michael@0: getPixelColor: function(ray, scene){ michael@0: var info = this.testIntersection(ray, scene, null); michael@0: if(info.isHit){ michael@0: var color = this.rayTrace(info, ray, scene, 0); michael@0: return color; michael@0: } michael@0: return scene.background.color; michael@0: }, michael@0: michael@0: testIntersection: function(ray, scene, exclude){ michael@0: var hits = 0; michael@0: var best = new Flog.RayTracer.IntersectionInfo(); michael@0: best.distance = 2000; michael@0: michael@0: for(var i=0; i= 0 && info.distance < best.distance){ michael@0: best = info; michael@0: hits++; michael@0: } michael@0: } michael@0: } michael@0: best.hitCount = hits; michael@0: return best; michael@0: }, michael@0: michael@0: getReflectionRay: function(P,N,V){ michael@0: var c1 = -N.dot(V); michael@0: var R1 = Flog.RayTracer.Vector.prototype.add( michael@0: Flog.RayTracer.Vector.prototype.multiplyScalar(N, 2*c1), michael@0: V michael@0: ); michael@0: return new Flog.RayTracer.Ray(P, R1); michael@0: }, michael@0: michael@0: rayTrace: function(info, ray, scene, depth){ michael@0: // Calc ambient michael@0: var color = Flog.RayTracer.Color.prototype.multiplyScalar(info.color, scene.background.ambience); michael@0: var oldColor = color; michael@0: var shininess = Math.pow(10, info.shape.material.gloss + 1); michael@0: michael@0: for(var i=0; i 0.0){ michael@0: color = Flog.RayTracer.Color.prototype.add( michael@0: color, michael@0: Flog.RayTracer.Color.prototype.multiply( michael@0: info.color, michael@0: Flog.RayTracer.Color.prototype.multiplyScalar( michael@0: light.color, michael@0: L michael@0: ) michael@0: ) michael@0: ); michael@0: } michael@0: } michael@0: michael@0: // The greater the depth the more accurate the colours, but michael@0: // this is exponentially (!) expensive michael@0: if(depth <= this.options.rayDepth){ michael@0: // calculate reflection ray michael@0: if(this.options.renderReflections && info.shape.material.reflection > 0) michael@0: { michael@0: var reflectionRay = this.getReflectionRay(info.position, info.normal, ray.direction); michael@0: var refl = this.testIntersection(reflectionRay, scene, info.shape); michael@0: michael@0: if (refl.isHit && refl.distance > 0){ michael@0: refl.color = this.rayTrace(refl, reflectionRay, scene, depth + 1); michael@0: } else { michael@0: refl.color = scene.background.color; michael@0: } michael@0: michael@0: color = Flog.RayTracer.Color.prototype.blend( michael@0: color, michael@0: refl.color, michael@0: info.shape.material.reflection michael@0: ); michael@0: } michael@0: michael@0: // Refraction michael@0: /* TODO */ michael@0: } michael@0: michael@0: /* Render shadows and highlights */ michael@0: michael@0: var shadowInfo = new Flog.RayTracer.IntersectionInfo(); michael@0: michael@0: if(this.options.renderShadows){ michael@0: var shadowRay = new Flog.RayTracer.Ray(info.position, v); michael@0: michael@0: shadowInfo = this.testIntersection(shadowRay, scene, info.shape); michael@0: if(shadowInfo.isHit && shadowInfo.shape != info.shape /*&& shadowInfo.shape.type != 'PLANE'*/){ michael@0: var vA = Flog.RayTracer.Color.prototype.multiplyScalar(color, 0.5); michael@0: var dB = (0.5 * Math.pow(shadowInfo.shape.material.transparency, 0.5)); michael@0: color = Flog.RayTracer.Color.prototype.addScalar(vA,dB); michael@0: } michael@0: } michael@0: michael@0: // Phong specular highlights michael@0: if(this.options.renderHighlights && !shadowInfo.isHit && info.shape.material.gloss > 0){ michael@0: var Lv = Flog.RayTracer.Vector.prototype.subtract( michael@0: info.shape.position, michael@0: light.position michael@0: ).normalize(); michael@0: michael@0: var E = Flog.RayTracer.Vector.prototype.subtract( michael@0: scene.camera.position, michael@0: info.shape.position michael@0: ).normalize(); michael@0: michael@0: var H = Flog.RayTracer.Vector.prototype.subtract( michael@0: E, michael@0: Lv michael@0: ).normalize(); michael@0: michael@0: var glossWeight = Math.pow(Math.max(info.normal.dot(H), 0), shininess); michael@0: color = Flog.RayTracer.Color.prototype.add( michael@0: Flog.RayTracer.Color.prototype.multiplyScalar(light.color, glossWeight), michael@0: color michael@0: ); michael@0: } michael@0: } michael@0: color.limit(); michael@0: return color; michael@0: } michael@0: }; michael@0: michael@0: michael@0: function renderScene(){ michael@0: var scene = new Flog.RayTracer.Scene(); michael@0: michael@0: scene.camera = new Flog.RayTracer.Camera( michael@0: new Flog.RayTracer.Vector(0, 0, -15), michael@0: new Flog.RayTracer.Vector(-0.2, 0, 5), michael@0: new Flog.RayTracer.Vector(0, 1, 0) michael@0: ); michael@0: michael@0: scene.background = new Flog.RayTracer.Background( michael@0: new Flog.RayTracer.Color(0.5, 0.5, 0.5), michael@0: 0.4 michael@0: ); michael@0: michael@0: var sphere = new Flog.RayTracer.Shape.Sphere( michael@0: new Flog.RayTracer.Vector(-1.5, 1.5, 2), michael@0: 1.5, michael@0: new Flog.RayTracer.Material.Solid( michael@0: new Flog.RayTracer.Color(0,0.5,0.5), michael@0: 0.3, michael@0: 0.0, michael@0: 0.0, michael@0: 2.0 michael@0: ) michael@0: ); michael@0: michael@0: var sphere1 = new Flog.RayTracer.Shape.Sphere( michael@0: new Flog.RayTracer.Vector(1, 0.25, 1), michael@0: 0.5, michael@0: new Flog.RayTracer.Material.Solid( michael@0: new Flog.RayTracer.Color(0.9,0.9,0.9), michael@0: 0.1, michael@0: 0.0, michael@0: 0.0, michael@0: 1.5 michael@0: ) michael@0: ); michael@0: michael@0: var plane = new Flog.RayTracer.Shape.Plane( michael@0: new Flog.RayTracer.Vector(0.1, 0.9, -0.5).normalize(), michael@0: 1.2, michael@0: new Flog.RayTracer.Material.Chessboard( michael@0: new Flog.RayTracer.Color(1,1,1), michael@0: new Flog.RayTracer.Color(0,0,0), michael@0: 0.2, michael@0: 0.0, michael@0: 1.0, michael@0: 0.7 michael@0: ) michael@0: ); michael@0: michael@0: scene.shapes.push(plane); michael@0: scene.shapes.push(sphere); michael@0: scene.shapes.push(sphere1); michael@0: michael@0: var light = new Flog.RayTracer.Light( michael@0: new Flog.RayTracer.Vector(5, 10, -1), michael@0: new Flog.RayTracer.Color(0.8, 0.8, 0.8) michael@0: ); michael@0: michael@0: var light1 = new Flog.RayTracer.Light( michael@0: new Flog.RayTracer.Vector(-3, 5, -15), michael@0: new Flog.RayTracer.Color(0.8, 0.8, 0.8), michael@0: 100 michael@0: ); michael@0: michael@0: scene.lights.push(light); michael@0: scene.lights.push(light1); michael@0: michael@0: var imageWidth = 100; // $F('imageWidth'); michael@0: var imageHeight = 100; // $F('imageHeight'); michael@0: var pixelSize = "5,5".split(','); // $F('pixelSize').split(','); michael@0: var renderDiffuse = true; // $F('renderDiffuse'); michael@0: var renderShadows = true; // $F('renderShadows'); michael@0: var renderHighlights = true; // $F('renderHighlights'); michael@0: var renderReflections = true; // $F('renderReflections'); michael@0: var rayDepth = 2;//$F('rayDepth'); michael@0: michael@0: var raytracer = new Flog.RayTracer.Engine( michael@0: { michael@0: canvasWidth: imageWidth, michael@0: canvasHeight: imageHeight, michael@0: pixelWidth: pixelSize[0], michael@0: pixelHeight: pixelSize[1], michael@0: "renderDiffuse": renderDiffuse, michael@0: "renderHighlights": renderHighlights, michael@0: "renderShadows": renderShadows, michael@0: "renderReflections": renderReflections, michael@0: "rayDepth": rayDepth michael@0: } michael@0: ); michael@0: michael@0: raytracer.renderScene(scene, null, 0); michael@0: } michael@0: