code
stringlengths
1
2.08M
language
stringclasses
1 value
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ studio.forms = {}; /** * Class defining a data entry form for use in the Asset Studio. */ studio.forms.Form = Base.extend({ /** * Creates a new form with the given parameters. * @constructor * @param {Function} [params.onChange] A function * @param {Array} [params.inputs] A list of inputs */ constructor: function(id, params) { this.id_ = id; this.params_ = params; this.fields_ = params.fields; this.pauseNotify_ = false; for (var i = 0; i < this.fields_.length; i++) { this.fields_[i].setForm_(this); } this.onChange = this.params_.onChange || function(){}; }, /** * Creates the user interface for the form in the given container. * @private * @param {HTMLElement} container The container node for the form UI. */ createUI: function(container) { for (var i = 0; i < this.fields_.length; i++) { var field = this.fields_[i]; field.createUI(container); } }, /** * Notifies that the form contents have changed; * @private */ notifyChanged_: function(field) { if (this.pauseNotify_) { return; } this.onChange(field); }, /** * Returns the current values of the form fields, as an object. * @type Object */ getValues: function() { var values = {}; for (var i = 0; i < this.fields_.length; i++) { var field = this.fields_[i]; values[field.id_] = field.getValue(); } return values; }, /** * Returns all available serialized values of the form fields, as an object. * All values in the returned object are either strings or objects. * @type Object */ getValuesSerialized: function() { var values = {}; for (var i = 0; i < this.fields_.length; i++) { var field = this.fields_[i]; var value = field.serializeValue ? field.serializeValue() : undefined; if (value !== undefined) { values[field.id_] = field.serializeValue(); } } return values; }, /** * Sets the form field values for the key/value pairs in the given object. * Values must be serialized forms of the form values. The form must be * initialized before calling this method. */ setValuesSerialized: function(serializedValues) { this.pauseNotify_ = true; for (var i = 0; i < this.fields_.length; i++) { var field = this.fields_[i]; if (field.id_ in serializedValues && field.deserializeValue) { field.deserializeValue(serializedValues[field.id_]); } } this.pauseNotify_ = false; this.notifyChanged_(null); } });
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //#INSERTFILE "../lib/base.js"
JavaScript
/* * glfx.js * http://evanw.github.com/glfx.js/ * * Copyright 2011 Evan Wallace * Released under the MIT license */ var fx = (function() { var exports = {}; // src/OES_texture_float_linear-polyfill.js // From: https://github.com/evanw/OES_texture_float_linear-polyfill (function() { // Uploads a 2x2 floating-point texture where one pixel is 2 and the other // three pixels are 0. Linear filtering is only supported if a sample taken // from the center of that texture is (2 + 0 + 0 + 0) / 4 = 0.5. function supportsOESTextureFloatLinear(gl) { // Need floating point textures in the first place if (!gl.getExtension('OES_texture_float')) { return false; } // Create a render target var framebuffer = gl.createFramebuffer(); var byteTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, byteTexture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, byteTexture, 0); // Create a simple floating-point texture with value of 0.5 in the center var rgba = [ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; var floatTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, floatTexture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.FLOAT, new Float32Array(rgba)); // Create the test shader var program = gl.createProgram(); var vertexShader = gl.createShader(gl.VERTEX_SHADER); var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(vertexShader, '\ attribute vec2 vertex;\ void main() {\ gl_Position = vec4(vertex, 0.0, 1.0);\ }\ '); gl.shaderSource(fragmentShader, '\ uniform sampler2D texture;\ void main() {\ gl_FragColor = texture2D(texture, vec2(0.5));\ }\ '); gl.compileShader(vertexShader); gl.compileShader(fragmentShader); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); // Create a buffer containing a single point var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0]), gl.STREAM_DRAW); gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); // Render the point and read back the rendered pixel var pixel = new Uint8Array(4); gl.useProgram(program); gl.viewport(0, 0, 1, 1); gl.bindTexture(gl.TEXTURE_2D, floatTexture); gl.drawArrays(gl.POINTS, 0, 1); gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel); // The center sample will only have a value of 0.5 if linear filtering works return pixel[0] === 127 || pixel[0] === 128; } // The constructor for the returned extension object function OESTextureFloatLinear() { } // Cache the extension so it's specific to each context like extensions should be function getOESTextureFloatLinear(gl) { if (gl.$OES_texture_float_linear$ === void 0) { Object.defineProperty(gl, '$OES_texture_float_linear$', { enumerable: false, configurable: false, writable: false, value: new OESTextureFloatLinear() }); } return gl.$OES_texture_float_linear$; } // This replaces the real getExtension() function getExtension(name) { return name === 'OES_texture_float_linear' ? getOESTextureFloatLinear(this) : oldGetExtension.call(this, name); } // This replaces the real getSupportedExtensions() function getSupportedExtensions() { var extensions = oldGetSupportedExtensions.call(this); if (extensions.indexOf('OES_texture_float_linear') === -1) { extensions.push('OES_texture_float_linear'); } return extensions; } // Get a WebGL context try { var gl = document.createElement('canvas').getContext('experimental-webgl'); } catch (e) { } // Don't install the polyfill if the browser already supports it or doesn't have WebGL if (!gl || gl.getSupportedExtensions().indexOf('OES_texture_float_linear') !== -1) { return; } // Install the polyfill if linear filtering works with floating-point textures if (supportsOESTextureFloatLinear(gl)) { var oldGetExtension = WebGLRenderingContext.prototype.getExtension; var oldGetSupportedExtensions = WebGLRenderingContext.prototype.getSupportedExtensions; WebGLRenderingContext.prototype.getExtension = getExtension; WebGLRenderingContext.prototype.getSupportedExtensions = getSupportedExtensions; } }()); // src/core/canvas.js var gl; function clamp(lo, value, hi) { return Math.max(lo, Math.min(value, hi)); } function wrapTexture(texture) { return { _: texture, loadContentsOf: function(element) { // Make sure that we're using the correct global WebGL context gl = this._.gl; this._.loadContentsOf(element); }, destroy: function() { // Make sure that we're using the correct global WebGL context gl = this._.gl; this._.destroy(); } }; } function texture(element) { return wrapTexture(Texture.fromElement(element)); } function initialize(width, height) { var type = gl.UNSIGNED_BYTE; // Go for floating point buffer textures if we can, it'll make the bokeh // filter look a lot better. Note that on Windows, ANGLE does not let you // render to a floating-point texture when linear filtering is enabled. // See http://crbug.com/172278 for more information. if (gl.getExtension('OES_texture_float') && gl.getExtension('OES_texture_float_linear')) { var testTexture = new Texture(100, 100, gl.RGBA, gl.FLOAT); try { // Only use gl.FLOAT if we can render to it testTexture.drawTo(function() { type = gl.FLOAT; }); } catch (e) { } testTexture.destroy(); } if (this._.texture) this._.texture.destroy(); if (this._.spareTexture) this._.spareTexture.destroy(); this.width = width; this.height = height; this._.texture = new Texture(width, height, gl.RGBA, type); this._.spareTexture = new Texture(width, height, gl.RGBA, type); this._.extraTexture = this._.extraTexture || new Texture(0, 0, gl.RGBA, type); this._.flippedShader = this._.flippedShader || new Shader(null, '\ uniform sampler2D texture;\ varying vec2 texCoord;\ void main() {\ gl_FragColor = texture2D(texture, vec2(texCoord.x, 1.0 - texCoord.y));\ }\ '); this._.isInitialized = true; } /* Draw a texture to the canvas, with an optional width and height to scale to. If no width and height are given then the original texture width and height are used. */ function draw(texture, width, height) { if (!this._.isInitialized || texture._.width != this.width || texture._.height != this.height) { initialize.call(this, width ? width : texture._.width, height ? height : texture._.height); } texture._.use(); this._.texture.drawTo(function() { Shader.getDefaultShader().drawRect(); }); return this; } function update() { this._.texture.use(); this._.flippedShader.drawRect(); return this; } function simpleShader(shader, uniforms, textureIn, textureOut) { (textureIn || this._.texture).use(); this._.spareTexture.drawTo(function() { shader.uniforms(uniforms).drawRect(); }); this._.spareTexture.swapWith(textureOut || this._.texture); } function replace(node) { node.parentNode.insertBefore(this, node); node.parentNode.removeChild(node); return this; } function contents() { var texture = new Texture(this._.texture.width, this._.texture.height, gl.RGBA, gl.UNSIGNED_BYTE); this._.texture.use(); texture.drawTo(function() { Shader.getDefaultShader().drawRect(); }); return wrapTexture(texture); } /* Get a Uint8 array of pixel values: [r, g, b, a, r, g, b, a, ...] Length of the array will be width * height * 4. */ function getPixelArray() { var w = this._.texture.width; var h = this._.texture.height; var array = new Uint8Array(w * h * 4); this._.texture.drawTo(function() { gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, array); }); return array; } function wrap(func) { return function() { // Make sure that we're using the correct global WebGL context gl = this._.gl; // Now that the context has been switched, we can call the wrapped function return func.apply(this, arguments); }; } exports.canvas = function() { var canvas = document.createElement('canvas'); try { gl = canvas.getContext('experimental-webgl', { premultipliedAlpha: false }); } catch (e) { gl = null; } if (!gl) { throw 'This browser does not support WebGL'; } canvas._ = { gl: gl, isInitialized: false, texture: null, spareTexture: null, flippedShader: null }; // Core methods canvas.texture = wrap(texture); canvas.draw = wrap(draw); canvas.update = wrap(update); canvas.replace = wrap(replace); canvas.contents = wrap(contents); canvas.getPixelArray = wrap(getPixelArray); // Filter methods canvas.brightnessContrast = wrap(brightnessContrast); canvas.hexagonalPixelate = wrap(hexagonalPixelate); canvas.hueSaturation = wrap(hueSaturation); canvas.colorHalftone = wrap(colorHalftone); canvas.triangleBlur = wrap(triangleBlur); canvas.unsharpMask = wrap(unsharpMask); canvas.perspective = wrap(perspective); canvas.matrixWarp = wrap(matrixWarp); canvas.bulgePinch = wrap(bulgePinch); canvas.tiltShift = wrap(tiltShift); canvas.dotScreen = wrap(dotScreen); canvas.edgeWork = wrap(edgeWork); canvas.lensBlur = wrap(lensBlur); canvas.zoomBlur = wrap(zoomBlur); canvas.noise = wrap(noise); canvas.denoise = wrap(denoise); canvas.curves = wrap(curves); canvas.swirl = wrap(swirl); canvas.ink = wrap(ink); canvas.vignette = wrap(vignette); canvas.vibrance = wrap(vibrance); canvas.sepia = wrap(sepia); return canvas; }; exports.splineInterpolate = splineInterpolate; // src/core/matrix.js // from javax.media.jai.PerspectiveTransform function getSquareToQuad(x0, y0, x1, y1, x2, y2, x3, y3) { var dx1 = x1 - x2; var dy1 = y1 - y2; var dx2 = x3 - x2; var dy2 = y3 - y2; var dx3 = x0 - x1 + x2 - x3; var dy3 = y0 - y1 + y2 - y3; var det = dx1*dy2 - dx2*dy1; var a = (dx3*dy2 - dx2*dy3) / det; var b = (dx1*dy3 - dx3*dy1) / det; return [ x1 - x0 + a*x1, y1 - y0 + a*y1, a, x3 - x0 + b*x3, y3 - y0 + b*y3, b, x0, y0, 1 ]; } function getInverse(m) { var a = m[0], b = m[1], c = m[2]; var d = m[3], e = m[4], f = m[5]; var g = m[6], h = m[7], i = m[8]; var det = a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g; return [ (e*i - f*h) / det, (c*h - b*i) / det, (b*f - c*e) / det, (f*g - d*i) / det, (a*i - c*g) / det, (c*d - a*f) / det, (d*h - e*g) / det, (b*g - a*h) / det, (a*e - b*d) / det ]; } function multiply(a, b) { return [ a[0]*b[0] + a[1]*b[3] + a[2]*b[6], a[0]*b[1] + a[1]*b[4] + a[2]*b[7], a[0]*b[2] + a[1]*b[5] + a[2]*b[8], a[3]*b[0] + a[4]*b[3] + a[5]*b[6], a[3]*b[1] + a[4]*b[4] + a[5]*b[7], a[3]*b[2] + a[4]*b[5] + a[5]*b[8], a[6]*b[0] + a[7]*b[3] + a[8]*b[6], a[6]*b[1] + a[7]*b[4] + a[8]*b[7], a[6]*b[2] + a[7]*b[5] + a[8]*b[8] ]; } // src/core/shader.js var Shader = (function() { function isArray(obj) { return Object.prototype.toString.call(obj) == '[object Array]'; } function isNumber(obj) { return Object.prototype.toString.call(obj) == '[object Number]'; } function compileSource(type, source) { var shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { throw 'compile error: ' + gl.getShaderInfoLog(shader); } return shader; } var defaultVertexSource = '\ attribute vec2 vertex;\ attribute vec2 _texCoord;\ varying vec2 texCoord;\ void main() {\ texCoord = _texCoord;\ gl_Position = vec4(vertex * 2.0 - 1.0, 0.0, 1.0);\ }'; var defaultFragmentSource = '\ uniform sampler2D texture;\ varying vec2 texCoord;\ void main() {\ gl_FragColor = texture2D(texture, texCoord);\ }'; function Shader(vertexSource, fragmentSource) { this.vertexAttribute = null; this.texCoordAttribute = null; this.program = gl.createProgram(); vertexSource = vertexSource || defaultVertexSource; fragmentSource = fragmentSource || defaultFragmentSource; fragmentSource = 'precision highp float;' + fragmentSource; // annoying requirement is annoying gl.attachShader(this.program, compileSource(gl.VERTEX_SHADER, vertexSource)); gl.attachShader(this.program, compileSource(gl.FRAGMENT_SHADER, fragmentSource)); gl.linkProgram(this.program); if (!gl.getProgramParameter(this.program, gl.LINK_STATUS)) { throw 'link error: ' + gl.getProgramInfoLog(this.program); } } Shader.prototype.destroy = function() { gl.deleteProgram(this.program); this.program = null; }; Shader.prototype.uniforms = function(uniforms) { gl.useProgram(this.program); for (var name in uniforms) { if (!uniforms.hasOwnProperty(name)) continue; var location = gl.getUniformLocation(this.program, name); if (location === null) continue; // will be null if the uniform isn't used in the shader var value = uniforms[name]; if (isArray(value)) { switch (value.length) { case 1: gl.uniform1fv(location, new Float32Array(value)); break; case 2: gl.uniform2fv(location, new Float32Array(value)); break; case 3: gl.uniform3fv(location, new Float32Array(value)); break; case 4: gl.uniform4fv(location, new Float32Array(value)); break; case 9: gl.uniformMatrix3fv(location, false, new Float32Array(value)); break; case 16: gl.uniformMatrix4fv(location, false, new Float32Array(value)); break; default: throw 'dont\'t know how to load uniform "' + name + '" of length ' + value.length; } } else if (isNumber(value)) { gl.uniform1f(location, value); } else { throw 'attempted to set uniform "' + name + '" to invalid value ' + (value || 'undefined').toString(); } } // allow chaining return this; }; // textures are uniforms too but for some reason can't be specified by gl.uniform1f, // even though floating point numbers represent the integers 0 through 7 exactly Shader.prototype.textures = function(textures) { gl.useProgram(this.program); for (var name in textures) { if (!textures.hasOwnProperty(name)) continue; gl.uniform1i(gl.getUniformLocation(this.program, name), textures[name]); } // allow chaining return this; }; Shader.prototype.drawRect = function(left, top, right, bottom) { var undefined; var viewport = gl.getParameter(gl.VIEWPORT); top = top !== undefined ? (top - viewport[1]) / viewport[3] : 0; left = left !== undefined ? (left - viewport[0]) / viewport[2] : 0; right = right !== undefined ? (right - viewport[0]) / viewport[2] : 1; bottom = bottom !== undefined ? (bottom - viewport[1]) / viewport[3] : 1; if (gl.vertexBuffer == null) { gl.vertexBuffer = gl.createBuffer(); } gl.bindBuffer(gl.ARRAY_BUFFER, gl.vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ left, top, left, bottom, right, top, right, bottom ]), gl.STATIC_DRAW); if (gl.texCoordBuffer == null) { gl.texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, gl.texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, 0, 1, 1, 0, 1, 1 ]), gl.STATIC_DRAW); } if (this.vertexAttribute == null) { this.vertexAttribute = gl.getAttribLocation(this.program, 'vertex'); gl.enableVertexAttribArray(this.vertexAttribute); } if (this.texCoordAttribute == null) { this.texCoordAttribute = gl.getAttribLocation(this.program, '_texCoord'); gl.enableVertexAttribArray(this.texCoordAttribute); } gl.useProgram(this.program); gl.bindBuffer(gl.ARRAY_BUFFER, gl.vertexBuffer); gl.vertexAttribPointer(this.vertexAttribute, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, gl.texCoordBuffer); gl.vertexAttribPointer(this.texCoordAttribute, 2, gl.FLOAT, false, 0, 0); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); }; Shader.getDefaultShader = function() { gl.defaultShader = gl.defaultShader || new Shader(); return gl.defaultShader; }; return Shader; })(); // src/core/spline.js // from SplineInterpolator.cs in the Paint.NET source code function SplineInterpolator(points) { var n = points.length; this.xa = []; this.ya = []; this.u = []; this.y2 = []; points.sort(function(a, b) { return a[0] - b[0]; }); for (var i = 0; i < n; i++) { this.xa.push(points[i][0]); this.ya.push(points[i][1]); } this.u[0] = 0; this.y2[0] = 0; for (var i = 1; i < n - 1; ++i) { // This is the decomposition loop of the tridiagonal algorithm. // y2 and u are used for temporary storage of the decomposed factors. var wx = this.xa[i + 1] - this.xa[i - 1]; var sig = (this.xa[i] - this.xa[i - 1]) / wx; var p = sig * this.y2[i - 1] + 2.0; this.y2[i] = (sig - 1.0) / p; var ddydx = (this.ya[i + 1] - this.ya[i]) / (this.xa[i + 1] - this.xa[i]) - (this.ya[i] - this.ya[i - 1]) / (this.xa[i] - this.xa[i - 1]); this.u[i] = (6.0 * ddydx / wx - sig * this.u[i - 1]) / p; } this.y2[n - 1] = 0; // This is the backsubstitution loop of the tridiagonal algorithm for (var i = n - 2; i >= 0; --i) { this.y2[i] = this.y2[i] * this.y2[i + 1] + this.u[i]; } } SplineInterpolator.prototype.interpolate = function(x) { var n = this.ya.length; var klo = 0; var khi = n - 1; // We will find the right place in the table by means of // bisection. This is optimal if sequential calls to this // routine are at random values of x. If sequential calls // are in order, and closely spaced, one would do better // to store previous values of klo and khi. while (khi - klo > 1) { var k = (khi + klo) >> 1; if (this.xa[k] > x) { khi = k; } else { klo = k; } } var h = this.xa[khi] - this.xa[klo]; var a = (this.xa[khi] - x) / h; var b = (x - this.xa[klo]) / h; // Cubic spline polynomial is now evaluated. return a * this.ya[klo] + b * this.ya[khi] + ((a * a * a - a) * this.y2[klo] + (b * b * b - b) * this.y2[khi]) * (h * h) / 6.0; }; // src/core/texture.js var Texture = (function() { Texture.fromElement = function(element) { var texture = new Texture(0, 0, gl.RGBA, gl.UNSIGNED_BYTE); texture.loadContentsOf(element); return texture; }; function Texture(width, height, format, type) { this.gl = gl; this.id = gl.createTexture(); this.width = width; this.height = height; this.format = format; this.type = type; gl.bindTexture(gl.TEXTURE_2D, this.id); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); if (width && height) gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, null); } Texture.prototype.loadContentsOf = function(element) { this.width = element.width || element.videoWidth; this.height = element.height || element.videoHeight; gl.bindTexture(gl.TEXTURE_2D, this.id); gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, element); }; Texture.prototype.initFromBytes = function(width, height, data) { this.width = width; this.height = height; this.format = gl.RGBA; this.type = gl.UNSIGNED_BYTE; gl.bindTexture(gl.TEXTURE_2D, this.id); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, this.type, new Uint8Array(data)); }; Texture.prototype.destroy = function() { gl.deleteTexture(this.id); this.id = null; }; Texture.prototype.use = function(unit) { gl.activeTexture(gl.TEXTURE0 + (unit || 0)); gl.bindTexture(gl.TEXTURE_2D, this.id); }; Texture.prototype.unuse = function(unit) { gl.activeTexture(gl.TEXTURE0 + (unit || 0)); gl.bindTexture(gl.TEXTURE_2D, null); }; Texture.prototype.ensureFormat = function(width, height, format, type) { // allow passing an existing texture instead of individual arguments if (arguments.length == 1) { var texture = arguments[0]; width = texture.width; height = texture.height; format = texture.format; type = texture.type; } // change the format only if required if (width != this.width || height != this.height || format != this.format || type != this.type) { this.width = width; this.height = height; this.format = format; this.type = type; gl.bindTexture(gl.TEXTURE_2D, this.id); gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, null); } }; Texture.prototype.drawTo = function(callback) { // start rendering to this texture gl.framebuffer = gl.framebuffer || gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, gl.framebuffer); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.id, 0); if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) { throw new Error('incomplete framebuffer'); } gl.viewport(0, 0, this.width, this.height); // do the drawing callback(); // stop rendering to this texture gl.bindFramebuffer(gl.FRAMEBUFFER, null); }; var canvas = null; function getCanvas(texture) { if (canvas == null) canvas = document.createElement('canvas'); canvas.width = texture.width; canvas.height = texture.height; var c = canvas.getContext('2d'); c.clearRect(0, 0, canvas.width, canvas.height); return c; } Texture.prototype.fillUsingCanvas = function(callback) { callback(getCanvas(this)); this.format = gl.RGBA; this.type = gl.UNSIGNED_BYTE; gl.bindTexture(gl.TEXTURE_2D, this.id); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, canvas); return this; }; Texture.prototype.toImage = function(image) { this.use(); Shader.getDefaultShader().drawRect(); var size = this.width * this.height * 4; var pixels = new Uint8Array(size); var c = getCanvas(this); var data = c.createImageData(this.width, this.height); gl.readPixels(0, 0, this.width, this.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); for (var i = 0; i < size; i++) { data.data[i] = pixels[i]; } c.putImageData(data, 0, 0); image.src = canvas.toDataURL(); }; Texture.prototype.swapWith = function(other) { var temp; temp = other.id; other.id = this.id; this.id = temp; temp = other.width; other.width = this.width; this.width = temp; temp = other.height; other.height = this.height; this.height = temp; temp = other.format; other.format = this.format; this.format = temp; }; return Texture; })(); // src/filters/common.js function warpShader(uniforms, warp) { return new Shader(null, uniforms + '\ uniform sampler2D texture;\ uniform vec2 texSize;\ varying vec2 texCoord;\ void main() {\ vec2 coord = texCoord * texSize;\ ' + warp + '\ gl_FragColor = texture2D(texture, coord / texSize);\ vec2 clampedCoord = clamp(coord, vec2(0.0), texSize);\ if (coord != clampedCoord) {\ /* fade to transparent if we are outside the image */\ gl_FragColor.a *= max(0.0, 1.0 - length(coord - clampedCoord));\ }\ }'); } // returns a random number between 0 and 1 var randomShaderFunc = '\ float random(vec3 scale, float seed) {\ /* use the fragment position for a different seed per-pixel */\ return fract(sin(dot(gl_FragCoord.xyz + seed, scale)) * 43758.5453 + seed);\ }\ '; // src/filters/adjust/brightnesscontrast.js /** * @filter Brightness / Contrast * @description Provides additive brightness and multiplicative contrast control. * @param brightness -1 to 1 (-1 is solid black, 0 is no change, and 1 is solid white) * @param contrast -1 to 1 (-1 is solid gray, 0 is no change, and 1 is maximum contrast) */ function brightnessContrast(brightness, contrast) { gl.brightnessContrast = gl.brightnessContrast || new Shader(null, '\ uniform sampler2D texture;\ uniform float brightness;\ uniform float contrast;\ varying vec2 texCoord;\ void main() {\ vec4 color = texture2D(texture, texCoord);\ color.rgb += brightness;\ if (contrast > 0.0) {\ color.rgb = (color.rgb - 0.5) / (1.0 - contrast) + 0.5;\ } else {\ color.rgb = (color.rgb - 0.5) * (1.0 + contrast) + 0.5;\ }\ gl_FragColor = color;\ }\ '); simpleShader.call(this, gl.brightnessContrast, { brightness: clamp(-1, brightness, 1), contrast: clamp(-1, contrast, 1) }); return this; } // src/filters/adjust/curves.js function splineInterpolate(points) { var interpolator = new SplineInterpolator(points); var array = []; for (var i = 0; i < 256; i++) { array.push(clamp(0, Math.floor(interpolator.interpolate(i / 255) * 256), 255)); } return array; } /** * @filter Curves * @description A powerful mapping tool that transforms the colors in the image * by an arbitrary function. The function is interpolated between * a set of 2D points using splines. The curves filter can take * either one or three arguments which will apply the mapping to * either luminance or RGB values, respectively. * @param red A list of points that define the function for the red channel. * Each point is a list of two values: the value before the mapping * and the value after the mapping, both in the range 0 to 1. For * example, [[0,1], [1,0]] would invert the red channel while * [[0,0], [1,1]] would leave the red channel unchanged. If green * and blue are omitted then this argument also applies to the * green and blue channels. * @param green (optional) A list of points that define the function for the green * channel (just like for red). * @param blue (optional) A list of points that define the function for the blue * channel (just like for red). */ function curves(red, green, blue) { // Create the ramp texture red = splineInterpolate(red); if (arguments.length == 1) { green = blue = red; } else { green = splineInterpolate(green); blue = splineInterpolate(blue); } var array = []; for (var i = 0; i < 256; i++) { array.splice(array.length, 0, red[i], green[i], blue[i], 255); } this._.extraTexture.initFromBytes(256, 1, array); this._.extraTexture.use(1); gl.curves = gl.curves || new Shader(null, '\ uniform sampler2D texture;\ uniform sampler2D map;\ varying vec2 texCoord;\ void main() {\ vec4 color = texture2D(texture, texCoord);\ color.r = texture2D(map, vec2(color.r)).r;\ color.g = texture2D(map, vec2(color.g)).g;\ color.b = texture2D(map, vec2(color.b)).b;\ gl_FragColor = color;\ }\ '); gl.curves.textures({ map: 1 }); simpleShader.call(this, gl.curves, {}); return this; } // src/filters/adjust/denoise.js /** * @filter Denoise * @description Smooths over grainy noise in dark images using an 9x9 box filter * weighted by color intensity, similar to a bilateral filter. * @param exponent The exponent of the color intensity difference, should be greater * than zero. A value of zero just gives an 9x9 box blur and high values * give the original image, but ideal values are usually around 10-20. */ function denoise(exponent) { // Do a 9x9 bilateral box filter gl.denoise = gl.denoise || new Shader(null, '\ uniform sampler2D texture;\ uniform float exponent;\ uniform float strength;\ uniform vec2 texSize;\ varying vec2 texCoord;\ void main() {\ vec4 center = texture2D(texture, texCoord);\ vec4 color = vec4(0.0);\ float total = 0.0;\ for (float x = -4.0; x <= 4.0; x += 1.0) {\ for (float y = -4.0; y <= 4.0; y += 1.0) {\ vec4 sample = texture2D(texture, texCoord + vec2(x, y) / texSize);\ float weight = 1.0 - abs(dot(sample.rgb - center.rgb, vec3(0.25)));\ weight = pow(weight, exponent);\ color += sample * weight;\ total += weight;\ }\ }\ gl_FragColor = color / total;\ }\ '); // Perform two iterations for stronger results for (var i = 0; i < 2; i++) { simpleShader.call(this, gl.denoise, { exponent: Math.max(0, exponent), texSize: [this.width, this.height] }); } return this; } // src/filters/adjust/huesaturation.js /** * @filter Hue / Saturation * @description Provides rotational hue and multiplicative saturation control. RGB color space * can be imagined as a cube where the axes are the red, green, and blue color * values. Hue changing works by rotating the color vector around the grayscale * line, which is the straight line from black (0, 0, 0) to white (1, 1, 1). * Saturation is implemented by scaling all color channel values either toward * or away from the average color channel value. * @param hue -1 to 1 (-1 is 180 degree rotation in the negative direction, 0 is no change, * and 1 is 180 degree rotation in the positive direction) * @param saturation -1 to 1 (-1 is solid gray, 0 is no change, and 1 is maximum contrast) */ function hueSaturation(hue, saturation) { gl.hueSaturation = gl.hueSaturation || new Shader(null, '\ uniform sampler2D texture;\ uniform float hue;\ uniform float saturation;\ varying vec2 texCoord;\ void main() {\ vec4 color = texture2D(texture, texCoord);\ \ /* hue adjustment, wolfram alpha: RotationTransform[angle, {1, 1, 1}][{x, y, z}] */\ float angle = hue * 3.14159265;\ float s = sin(angle), c = cos(angle);\ vec3 weights = (vec3(2.0 * c, -sqrt(3.0) * s - c, sqrt(3.0) * s - c) + 1.0) / 3.0;\ float len = length(color.rgb);\ color.rgb = vec3(\ dot(color.rgb, weights.xyz),\ dot(color.rgb, weights.zxy),\ dot(color.rgb, weights.yzx)\ );\ \ /* saturation adjustment */\ float average = (color.r + color.g + color.b) / 3.0;\ if (saturation > 0.0) {\ color.rgb += (average - color.rgb) * (1.0 - 1.0 / (1.001 - saturation));\ } else {\ color.rgb += (average - color.rgb) * (-saturation);\ }\ \ gl_FragColor = color;\ }\ '); simpleShader.call(this, gl.hueSaturation, { hue: clamp(-1, hue, 1), saturation: clamp(-1, saturation, 1) }); return this; } // src/filters/adjust/noise.js /** * @filter Noise * @description Adds black and white noise to the image. * @param amount 0 to 1 (0 for no effect, 1 for maximum noise) */ function noise(amount) { gl.noise = gl.noise || new Shader(null, '\ uniform sampler2D texture;\ uniform float amount;\ varying vec2 texCoord;\ float rand(vec2 co) {\ return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);\ }\ void main() {\ vec4 color = texture2D(texture, texCoord);\ \ float diff = (rand(texCoord) - 0.5) * amount;\ color.r += diff;\ color.g += diff;\ color.b += diff;\ \ gl_FragColor = color;\ }\ '); simpleShader.call(this, gl.noise, { amount: clamp(0, amount, 1) }); return this; } // src/filters/adjust/sepia.js /** * @filter Sepia * @description Gives the image a reddish-brown monochrome tint that imitates an old photograph. * @param amount 0 to 1 (0 for no effect, 1 for full sepia coloring) */ function sepia(amount) { gl.sepia = gl.sepia || new Shader(null, '\ uniform sampler2D texture;\ uniform float amount;\ varying vec2 texCoord;\ void main() {\ vec4 color = texture2D(texture, texCoord);\ float r = color.r;\ float g = color.g;\ float b = color.b;\ \ color.r = min(1.0, (r * (1.0 - (0.607 * amount))) + (g * (0.769 * amount)) + (b * (0.189 * amount)));\ color.g = min(1.0, (r * 0.349 * amount) + (g * (1.0 - (0.314 * amount))) + (b * 0.168 * amount));\ color.b = min(1.0, (r * 0.272 * amount) + (g * 0.534 * amount) + (b * (1.0 - (0.869 * amount))));\ \ gl_FragColor = color;\ }\ '); simpleShader.call(this, gl.sepia, { amount: clamp(0, amount, 1) }); return this; } // src/filters/adjust/unsharpmask.js /** * @filter Unsharp Mask * @description A form of image sharpening that amplifies high-frequencies in the image. It * is implemented by scaling pixels away from the average of their neighbors. * @param radius The blur radius that calculates the average of the neighboring pixels. * @param strength A scale factor where 0 is no effect and higher values cause a stronger effect. */ function unsharpMask(radius, strength) { gl.unsharpMask = gl.unsharpMask || new Shader(null, '\ uniform sampler2D blurredTexture;\ uniform sampler2D originalTexture;\ uniform float strength;\ uniform float threshold;\ varying vec2 texCoord;\ void main() {\ vec4 blurred = texture2D(blurredTexture, texCoord);\ vec4 original = texture2D(originalTexture, texCoord);\ gl_FragColor = mix(blurred, original, 1.0 + strength);\ }\ '); // Store a copy of the current texture in the second texture unit this._.extraTexture.ensureFormat(this._.texture); this._.texture.use(); this._.extraTexture.drawTo(function() { Shader.getDefaultShader().drawRect(); }); // Blur the current texture, then use the stored texture to detect edges this._.extraTexture.use(1); this.triangleBlur(radius); gl.unsharpMask.textures({ originalTexture: 1 }); simpleShader.call(this, gl.unsharpMask, { strength: strength }); this._.extraTexture.unuse(1); return this; } // src/filters/adjust/vibrance.js /** * @filter Vibrance * @description Modifies the saturation of desaturated colors, leaving saturated colors unmodified. * @param amount -1 to 1 (-1 is minimum vibrance, 0 is no change, and 1 is maximum vibrance) */ function vibrance(amount) { gl.vibrance = gl.vibrance || new Shader(null, '\ uniform sampler2D texture;\ uniform float amount;\ varying vec2 texCoord;\ void main() {\ vec4 color = texture2D(texture, texCoord);\ float average = (color.r + color.g + color.b) / 3.0;\ float mx = max(color.r, max(color.g, color.b));\ float amt = (mx - average) * (-amount * 3.0);\ color.rgb = mix(color.rgb, vec3(mx), amt);\ gl_FragColor = color;\ }\ '); simpleShader.call(this, gl.vibrance, { amount: clamp(-1, amount, 1) }); return this; } // src/filters/adjust/vignette.js /** * @filter Vignette * @description Adds a simulated lens edge darkening effect. * @param size 0 to 1 (0 for center of frame, 1 for edge of frame) * @param amount 0 to 1 (0 for no effect, 1 for maximum lens darkening) */ function vignette(size, amount) { gl.vignette = gl.vignette || new Shader(null, '\ uniform sampler2D texture;\ uniform float size;\ uniform float amount;\ varying vec2 texCoord;\ void main() {\ vec4 color = texture2D(texture, texCoord);\ \ float dist = distance(texCoord, vec2(0.5, 0.5));\ color.rgb *= smoothstep(0.8, size * 0.799, dist * (amount + size));\ \ gl_FragColor = color;\ }\ '); simpleShader.call(this, gl.vignette, { size: clamp(0, size, 1), amount: clamp(0, amount, 1) }); return this; } // src/filters/blur/lensblur.js /** * @filter Lens Blur * @description Imitates a camera capturing the image out of focus by using a blur that generates * the large shapes known as bokeh. The polygonal shape of real bokeh is due to the * blades of the aperture diaphragm when it isn't fully open. This blur renders * bokeh from a 6-bladed diaphragm because the computation is more efficient. It * can be separated into three rhombi, each of which is just a skewed box blur. * This filter makes use of the floating point texture WebGL extension to implement * the brightness parameter, so there will be severe visual artifacts if brightness * is non-zero and the floating point texture extension is not available. The * idea was from John White's SIGGRAPH 2011 talk but this effect has an additional * brightness parameter that fakes what would otherwise come from a HDR source. * @param radius the radius of the hexagonal disk convolved with the image * @param brightness -1 to 1 (the brightness of the bokeh, negative values will create dark bokeh) * @param angle the rotation of the bokeh in radians */ function lensBlur(radius, brightness, angle) { // All averaging is done on values raised to a power to make more obvious bokeh // (we will raise the average to the inverse power at the end to compensate). // Without this the image looks almost like a normal blurred image. This hack is // obviously not realistic, but to accurately simulate this we would need a high // dynamic range source photograph which we don't have. gl.lensBlurPrePass = gl.lensBlurPrePass || new Shader(null, '\ uniform sampler2D texture;\ uniform float power;\ varying vec2 texCoord;\ void main() {\ vec4 color = texture2D(texture, texCoord);\ color = pow(color, vec4(power));\ gl_FragColor = vec4(color);\ }\ '); var common = '\ uniform sampler2D texture0;\ uniform sampler2D texture1;\ uniform vec2 delta0;\ uniform vec2 delta1;\ uniform float power;\ varying vec2 texCoord;\ ' + randomShaderFunc + '\ vec4 sample(vec2 delta) {\ /* randomize the lookup values to hide the fixed number of samples */\ float offset = random(vec3(delta, 151.7182), 0.0);\ \ vec4 color = vec4(0.0);\ float total = 0.0;\ for (float t = 0.0; t <= 30.0; t++) {\ float percent = (t + offset) / 30.0;\ color += texture2D(texture0, texCoord + delta * percent);\ total += 1.0;\ }\ return color / total;\ }\ '; gl.lensBlur0 = gl.lensBlur0 || new Shader(null, common + '\ void main() {\ gl_FragColor = sample(delta0);\ }\ '); gl.lensBlur1 = gl.lensBlur1 || new Shader(null, common + '\ void main() {\ gl_FragColor = (sample(delta0) + sample(delta1)) * 0.5;\ }\ '); gl.lensBlur2 = gl.lensBlur2 || new Shader(null, common + '\ void main() {\ vec4 color = (sample(delta0) + 2.0 * texture2D(texture1, texCoord)) / 3.0;\ gl_FragColor = pow(color, vec4(power));\ }\ ').textures({ texture1: 1 }); // Generate var dir = []; for (var i = 0; i < 3; i++) { var a = angle + i * Math.PI * 2 / 3; dir.push([radius * Math.sin(a) / this.width, radius * Math.cos(a) / this.height]); } var power = Math.pow(10, clamp(-1, brightness, 1)); // Remap the texture values, which will help make the bokeh effect simpleShader.call(this, gl.lensBlurPrePass, { power: power }); // Blur two rhombi in parallel into extraTexture this._.extraTexture.ensureFormat(this._.texture); simpleShader.call(this, gl.lensBlur0, { delta0: dir[0] }, this._.texture, this._.extraTexture); simpleShader.call(this, gl.lensBlur1, { delta0: dir[1], delta1: dir[2] }, this._.extraTexture, this._.extraTexture); // Blur the last rhombus and combine with extraTexture simpleShader.call(this, gl.lensBlur0, { delta0: dir[1] }); this._.extraTexture.use(1); simpleShader.call(this, gl.lensBlur2, { power: 1 / power, delta0: dir[2] }); return this; } // src/filters/blur/tiltshift.js /** * @filter Tilt Shift * @description Simulates the shallow depth of field normally encountered in close-up * photography, which makes the scene seem much smaller than it actually * is. This filter assumes the scene is relatively planar, in which case * the part of the scene that is completely in focus can be described by * a line (the intersection of the focal plane and the scene). An example * of a planar scene might be looking at a road from above at a downward * angle. The image is then blurred with a blur radius that starts at zero * on the line and increases further from the line. * @param startX The x coordinate of the start of the line segment. * @param startY The y coordinate of the start of the line segment. * @param endX The x coordinate of the end of the line segment. * @param endY The y coordinate of the end of the line segment. * @param blurRadius The maximum radius of the pyramid blur. * @param gradientRadius The distance from the line at which the maximum blur radius is reached. */ function tiltShift(startX, startY, endX, endY, blurRadius, gradientRadius) { gl.tiltShift = gl.tiltShift || new Shader(null, '\ uniform sampler2D texture;\ uniform float blurRadius;\ uniform float gradientRadius;\ uniform vec2 start;\ uniform vec2 end;\ uniform vec2 delta;\ uniform vec2 texSize;\ varying vec2 texCoord;\ ' + randomShaderFunc + '\ void main() {\ vec4 color = vec4(0.0);\ float total = 0.0;\ \ /* randomize the lookup values to hide the fixed number of samples */\ float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);\ \ vec2 normal = normalize(vec2(start.y - end.y, end.x - start.x));\ float radius = smoothstep(0.0, 1.0, abs(dot(texCoord * texSize - start, normal)) / gradientRadius) * blurRadius;\ for (float t = -30.0; t <= 30.0; t++) {\ float percent = (t + offset - 0.5) / 30.0;\ float weight = 1.0 - abs(percent);\ vec4 sample = texture2D(texture, texCoord + delta / texSize * percent * radius);\ \ /* switch to pre-multiplied alpha to correctly blur transparent images */\ sample.rgb *= sample.a;\ \ color += sample * weight;\ total += weight;\ }\ \ gl_FragColor = color / total;\ \ /* switch back from pre-multiplied alpha */\ gl_FragColor.rgb /= gl_FragColor.a + 0.00001;\ }\ '); var dx = endX - startX; var dy = endY - startY; var d = Math.sqrt(dx * dx + dy * dy); simpleShader.call(this, gl.tiltShift, { blurRadius: blurRadius, gradientRadius: gradientRadius, start: [startX, startY], end: [endX, endY], delta: [dx / d, dy / d], texSize: [this.width, this.height] }); simpleShader.call(this, gl.tiltShift, { blurRadius: blurRadius, gradientRadius: gradientRadius, start: [startX, startY], end: [endX, endY], delta: [-dy / d, dx / d], texSize: [this.width, this.height] }); return this; } // src/filters/blur/triangleblur.js /** * @filter Triangle Blur * @description This is the most basic blur filter, which convolves the image with a * pyramid filter. The pyramid filter is separable and is applied as two * perpendicular triangle filters. * @param radius The radius of the pyramid convolved with the image. */ function triangleBlur(radius) { gl.triangleBlur = gl.triangleBlur || new Shader(null, '\ uniform sampler2D texture;\ uniform vec2 delta;\ varying vec2 texCoord;\ ' + randomShaderFunc + '\ void main() {\ vec4 color = vec4(0.0);\ float total = 0.0;\ \ /* randomize the lookup values to hide the fixed number of samples */\ float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);\ \ for (float t = -30.0; t <= 30.0; t++) {\ float percent = (t + offset - 0.5) / 30.0;\ float weight = 1.0 - abs(percent);\ vec4 sample = texture2D(texture, texCoord + delta * percent);\ \ /* switch to pre-multiplied alpha to correctly blur transparent images */\ sample.rgb *= sample.a;\ \ color += sample * weight;\ total += weight;\ }\ \ gl_FragColor = color / total;\ \ /* switch back from pre-multiplied alpha */\ gl_FragColor.rgb /= gl_FragColor.a + 0.00001;\ }\ '); simpleShader.call(this, gl.triangleBlur, { delta: [radius / this.width, 0] }); simpleShader.call(this, gl.triangleBlur, { delta: [0, radius / this.height] }); return this; } // src/filters/blur/zoomblur.js /** * @filter Zoom Blur * @description Blurs the image away from a certain point, which looks like radial motion blur. * @param centerX The x coordinate of the blur origin. * @param centerY The y coordinate of the blur origin. * @param strength The strength of the blur. Values in the range 0 to 1 are usually sufficient, * where 0 doesn't change the image and 1 creates a highly blurred image. */ function zoomBlur(centerX, centerY, strength) { gl.zoomBlur = gl.zoomBlur || new Shader(null, '\ uniform sampler2D texture;\ uniform vec2 center;\ uniform float strength;\ uniform vec2 texSize;\ varying vec2 texCoord;\ ' + randomShaderFunc + '\ void main() {\ vec4 color = vec4(0.0);\ float total = 0.0;\ vec2 toCenter = center - texCoord * texSize;\ \ /* randomize the lookup values to hide the fixed number of samples */\ float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);\ \ for (float t = 0.0; t <= 40.0; t++) {\ float percent = (t + offset) / 40.0;\ float weight = 4.0 * (percent - percent * percent);\ vec4 sample = texture2D(texture, texCoord + toCenter * percent * strength / texSize);\ \ /* switch to pre-multiplied alpha to correctly blur transparent images */\ sample.rgb *= sample.a;\ \ color += sample * weight;\ total += weight;\ }\ \ gl_FragColor = color / total;\ \ /* switch back from pre-multiplied alpha */\ gl_FragColor.rgb /= gl_FragColor.a + 0.00001;\ }\ '); simpleShader.call(this, gl.zoomBlur, { center: [centerX, centerY], strength: strength, texSize: [this.width, this.height] }); return this; } // src/filters/fun/colorhalftone.js /** * @filter Color Halftone * @description Simulates a CMYK halftone rendering of the image by multiplying pixel values * with a four rotated 2D sine wave patterns, one each for cyan, magenta, yellow, * and black. * @param centerX The x coordinate of the pattern origin. * @param centerY The y coordinate of the pattern origin. * @param angle The rotation of the pattern in radians. * @param size The diameter of a dot in pixels. */ function colorHalftone(centerX, centerY, angle, size) { gl.colorHalftone = gl.colorHalftone || new Shader(null, '\ uniform sampler2D texture;\ uniform vec2 center;\ uniform float angle;\ uniform float scale;\ uniform vec2 texSize;\ varying vec2 texCoord;\ \ float pattern(float angle) {\ float s = sin(angle), c = cos(angle);\ vec2 tex = texCoord * texSize - center;\ vec2 point = vec2(\ c * tex.x - s * tex.y,\ s * tex.x + c * tex.y\ ) * scale;\ return (sin(point.x) * sin(point.y)) * 4.0;\ }\ \ void main() {\ vec4 color = texture2D(texture, texCoord);\ vec3 cmy = 1.0 - color.rgb;\ float k = min(cmy.x, min(cmy.y, cmy.z));\ cmy = (cmy - k) / (1.0 - k);\ cmy = clamp(cmy * 10.0 - 3.0 + vec3(pattern(angle + 0.26179), pattern(angle + 1.30899), pattern(angle)), 0.0, 1.0);\ k = clamp(k * 10.0 - 5.0 + pattern(angle + 0.78539), 0.0, 1.0);\ gl_FragColor = vec4(1.0 - cmy - k, color.a);\ }\ '); simpleShader.call(this, gl.colorHalftone, { center: [centerX, centerY], angle: angle, scale: Math.PI / size, texSize: [this.width, this.height] }); return this; } // src/filters/fun/dotscreen.js /** * @filter Dot Screen * @description Simulates a black and white halftone rendering of the image by multiplying * pixel values with a rotated 2D sine wave pattern. * @param centerX The x coordinate of the pattern origin. * @param centerY The y coordinate of the pattern origin. * @param angle The rotation of the pattern in radians. * @param size The diameter of a dot in pixels. */ function dotScreen(centerX, centerY, angle, size) { gl.dotScreen = gl.dotScreen || new Shader(null, '\ uniform sampler2D texture;\ uniform vec2 center;\ uniform float angle;\ uniform float scale;\ uniform vec2 texSize;\ varying vec2 texCoord;\ \ float pattern() {\ float s = sin(angle), c = cos(angle);\ vec2 tex = texCoord * texSize - center;\ vec2 point = vec2(\ c * tex.x - s * tex.y,\ s * tex.x + c * tex.y\ ) * scale;\ return (sin(point.x) * sin(point.y)) * 4.0;\ }\ \ void main() {\ vec4 color = texture2D(texture, texCoord);\ float average = (color.r + color.g + color.b) / 3.0;\ gl_FragColor = vec4(vec3(average * 10.0 - 5.0 + pattern()), color.a);\ }\ '); simpleShader.call(this, gl.dotScreen, { center: [centerX, centerY], angle: angle, scale: Math.PI / size, texSize: [this.width, this.height] }); return this; } // src/filters/fun/edgework.js /** * @filter Edge Work * @description Picks out different frequencies in the image by subtracting two * copies of the image blurred with different radii. * @param radius The radius of the effect in pixels. */ function edgeWork(radius) { gl.edgeWork1 = gl.edgeWork1 || new Shader(null, '\ uniform sampler2D texture;\ uniform vec2 delta;\ varying vec2 texCoord;\ ' + randomShaderFunc + '\ void main() {\ vec2 color = vec2(0.0);\ vec2 total = vec2(0.0);\ \ /* randomize the lookup values to hide the fixed number of samples */\ float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);\ \ for (float t = -30.0; t <= 30.0; t++) {\ float percent = (t + offset - 0.5) / 30.0;\ float weight = 1.0 - abs(percent);\ vec3 sample = texture2D(texture, texCoord + delta * percent).rgb;\ float average = (sample.r + sample.g + sample.b) / 3.0;\ color.x += average * weight;\ total.x += weight;\ if (abs(t) < 15.0) {\ weight = weight * 2.0 - 1.0;\ color.y += average * weight;\ total.y += weight;\ }\ }\ gl_FragColor = vec4(color / total, 0.0, 1.0);\ }\ '); gl.edgeWork2 = gl.edgeWork2 || new Shader(null, '\ uniform sampler2D texture;\ uniform vec2 delta;\ varying vec2 texCoord;\ ' + randomShaderFunc + '\ void main() {\ vec2 color = vec2(0.0);\ vec2 total = vec2(0.0);\ \ /* randomize the lookup values to hide the fixed number of samples */\ float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);\ \ for (float t = -30.0; t <= 30.0; t++) {\ float percent = (t + offset - 0.5) / 30.0;\ float weight = 1.0 - abs(percent);\ vec2 sample = texture2D(texture, texCoord + delta * percent).xy;\ color.x += sample.x * weight;\ total.x += weight;\ if (abs(t) < 15.0) {\ weight = weight * 2.0 - 1.0;\ color.y += sample.y * weight;\ total.y += weight;\ }\ }\ float c = clamp(10000.0 * (color.y / total.y - color.x / total.x) + 0.5, 0.0, 1.0);\ gl_FragColor = vec4(c, c, c, 1.0);\ }\ '); simpleShader.call(this, gl.edgeWork1, { delta: [radius / this.width, 0] }); simpleShader.call(this, gl.edgeWork2, { delta: [0, radius / this.height] }); return this; } // src/filters/fun/hexagonalpixelate.js /** * @filter Hexagonal Pixelate * @description Renders the image using a pattern of hexagonal tiles. Tile colors * are nearest-neighbor sampled from the centers of the tiles. * @param centerX The x coordinate of the pattern center. * @param centerY The y coordinate of the pattern center. * @param scale The width of an individual tile, in pixels. */ function hexagonalPixelate(centerX, centerY, scale) { gl.hexagonalPixelate = gl.hexagonalPixelate || new Shader(null, '\ uniform sampler2D texture;\ uniform vec2 center;\ uniform float scale;\ uniform vec2 texSize;\ varying vec2 texCoord;\ void main() {\ vec2 tex = (texCoord * texSize - center) / scale;\ tex.y /= 0.866025404;\ tex.x -= tex.y * 0.5;\ \ vec2 a;\ if (tex.x + tex.y - floor(tex.x) - floor(tex.y) < 1.0) a = vec2(floor(tex.x), floor(tex.y));\ else a = vec2(ceil(tex.x), ceil(tex.y));\ vec2 b = vec2(ceil(tex.x), floor(tex.y));\ vec2 c = vec2(floor(tex.x), ceil(tex.y));\ \ vec3 TEX = vec3(tex.x, tex.y, 1.0 - tex.x - tex.y);\ vec3 A = vec3(a.x, a.y, 1.0 - a.x - a.y);\ vec3 B = vec3(b.x, b.y, 1.0 - b.x - b.y);\ vec3 C = vec3(c.x, c.y, 1.0 - c.x - c.y);\ \ float alen = length(TEX - A);\ float blen = length(TEX - B);\ float clen = length(TEX - C);\ \ vec2 choice;\ if (alen < blen) {\ if (alen < clen) choice = a;\ else choice = c;\ } else {\ if (blen < clen) choice = b;\ else choice = c;\ }\ \ choice.x += choice.y * 0.5;\ choice.y *= 0.866025404;\ choice *= scale / texSize;\ gl_FragColor = texture2D(texture, choice + center / texSize);\ }\ '); simpleShader.call(this, gl.hexagonalPixelate, { center: [centerX, centerY], scale: scale, texSize: [this.width, this.height] }); return this; } // src/filters/fun/ink.js /** * @filter Ink * @description Simulates outlining the image in ink by darkening edges stronger than a * certain threshold. The edge detection value is the difference of two * copies of the image, each blurred using a blur of a different radius. * @param strength The multiplicative scale of the ink edges. Values in the range 0 to 1 * are usually sufficient, where 0 doesn't change the image and 1 adds lots * of black edges. Negative strength values will create white ink edges * instead of black ones. */ function ink(strength) { gl.ink = gl.ink || new Shader(null, '\ uniform sampler2D texture;\ uniform float strength;\ uniform vec2 texSize;\ varying vec2 texCoord;\ void main() {\ vec2 dx = vec2(1.0 / texSize.x, 0.0);\ vec2 dy = vec2(0.0, 1.0 / texSize.y);\ vec4 color = texture2D(texture, texCoord);\ float bigTotal = 0.0;\ float smallTotal = 0.0;\ vec3 bigAverage = vec3(0.0);\ vec3 smallAverage = vec3(0.0);\ for (float x = -2.0; x <= 2.0; x += 1.0) {\ for (float y = -2.0; y <= 2.0; y += 1.0) {\ vec3 sample = texture2D(texture, texCoord + dx * x + dy * y).rgb;\ bigAverage += sample;\ bigTotal += 1.0;\ if (abs(x) + abs(y) < 2.0) {\ smallAverage += sample;\ smallTotal += 1.0;\ }\ }\ }\ vec3 edge = max(vec3(0.0), bigAverage / bigTotal - smallAverage / smallTotal);\ gl_FragColor = vec4(color.rgb - dot(edge, edge) * strength * 100000.0, color.a);\ }\ '); simpleShader.call(this, gl.ink, { strength: strength * strength * strength * strength * strength, texSize: [this.width, this.height] }); return this; } // src/filters/warp/bulgepinch.js /** * @filter Bulge / Pinch * @description Bulges or pinches the image in a circle. * @param centerX The x coordinate of the center of the circle of effect. * @param centerY The y coordinate of the center of the circle of effect. * @param radius The radius of the circle of effect. * @param strength -1 to 1 (-1 is strong pinch, 0 is no effect, 1 is strong bulge) */ function bulgePinch(centerX, centerY, radius, strength) { gl.bulgePinch = gl.bulgePinch || warpShader('\ uniform float radius;\ uniform float strength;\ uniform vec2 center;\ ', '\ coord -= center;\ float distance = length(coord);\ if (distance < radius) {\ float percent = distance / radius;\ if (strength > 0.0) {\ coord *= mix(1.0, smoothstep(0.0, radius / distance, percent), strength * 0.75);\ } else {\ coord *= mix(1.0, pow(percent, 1.0 + strength * 0.75) * radius / distance, 1.0 - percent);\ }\ }\ coord += center;\ '); simpleShader.call(this, gl.bulgePinch, { radius: radius, strength: clamp(-1, strength, 1), center: [centerX, centerY], texSize: [this.width, this.height] }); return this; } // src/filters/warp/matrixwarp.js /** * @filter Matrix Warp * @description Transforms an image by a 2x2 or 3x3 matrix. The coordinates used in * the transformation are (x, y) for a 2x2 matrix or (x, y, 1) for a * 3x3 matrix, where x and y are in units of pixels. * @param matrix A 2x2 or 3x3 matrix represented as either a list or a list of lists. * For example, the 3x3 matrix [[2,0,0],[0,3,0],[0,0,1]] can also be * represented as [2,0,0,0,3,0,0,0,1] or just [2,0,0,3]. * @param inverse A boolean value that, when true, applies the inverse transformation * instead. (optional, defaults to false) * @param useTextureSpace A boolean value that, when true, uses texture-space coordinates * instead of screen-space coordinates. Texture-space coordinates range * from -1 to 1 instead of 0 to width - 1 or height - 1, and are easier * to use for simple operations like flipping and rotating. */ function matrixWarp(matrix, inverse, useTextureSpace) { gl.matrixWarp = gl.matrixWarp || warpShader('\ uniform mat3 matrix;\ uniform bool useTextureSpace;\ ', '\ if (useTextureSpace) coord = coord / texSize * 2.0 - 1.0;\ vec3 warp = matrix * vec3(coord, 1.0);\ coord = warp.xy / warp.z;\ if (useTextureSpace) coord = (coord * 0.5 + 0.5) * texSize;\ '); // Flatten all members of matrix into one big list matrix = Array.prototype.concat.apply([], matrix); // Extract a 3x3 matrix out of the arguments if (matrix.length == 4) { matrix = [ matrix[0], matrix[1], 0, matrix[2], matrix[3], 0, 0, 0, 1 ]; } else if (matrix.length != 9) { throw 'can only warp with 2x2 or 3x3 matrix'; } simpleShader.call(this, gl.matrixWarp, { matrix: inverse ? getInverse(matrix) : matrix, texSize: [this.width, this.height], useTextureSpace: useTextureSpace | 0 }); return this; } // src/filters/warp/perspective.js /** * @filter Perspective * @description Warps one quadrangle to another with a perspective transform. This can be used to * make a 2D image look 3D or to recover a 2D image captured in a 3D environment. * @param before The x and y coordinates of four points before the transform in a flat list. This * would look like [ax, ay, bx, by, cx, cy, dx, dy] for four points (ax, ay), (bx, by), * (cx, cy), and (dx, dy). * @param after The x and y coordinates of four points after the transform in a flat list, just * like the other argument. */ function perspective(before, after) { var a = getSquareToQuad.apply(null, after); var b = getSquareToQuad.apply(null, before); var c = multiply(getInverse(a), b); return this.matrixWarp(c); } // src/filters/warp/swirl.js /** * @filter Swirl * @description Warps a circular region of the image in a swirl. * @param centerX The x coordinate of the center of the circular region. * @param centerY The y coordinate of the center of the circular region. * @param radius The radius of the circular region. * @param angle The angle in radians that the pixels in the center of * the circular region will be rotated by. */ function swirl(centerX, centerY, radius, angle) { gl.swirl = gl.swirl || warpShader('\ uniform float radius;\ uniform float angle;\ uniform vec2 center;\ ', '\ coord -= center;\ float distance = length(coord);\ if (distance < radius) {\ float percent = (radius - distance) / radius;\ float theta = percent * percent * angle;\ float s = sin(theta);\ float c = cos(theta);\ coord = vec2(\ coord.x * c - coord.y * s,\ coord.x * s + coord.y * c\ );\ }\ coord += center;\ '); simpleShader.call(this, gl.swirl, { radius: radius, center: [centerX, centerY], angle: angle, texSize: [this.width, this.height] }); return this; } return exports; })();
JavaScript
// A modified version of bitmap.js from http://rest-term.com/archives/2566/ var Class = { create : function() { var properties = arguments[0]; function self() { this.initialize.apply(this, arguments); } for(var i in properties) { self.prototype[i] = properties[i]; } if(!self.prototype.initialize) { self.prototype.initialize = function() {}; } return self; } }; var ConvolutionFilter = Class.create({ initialize : function(matrix, divisor, bias, separable) { this.r = (Math.sqrt(matrix.length) - 1) / 2; this.matrix = matrix; this.divisor = divisor; this.bias = bias; this.separable = separable; }, apply : function(src, dst) { var w = src.width, h = src.height; var srcData = src.data; var dstData = dst.data; var di, si, idx; var r, g, b; //if (this.separable) { // TODO: optimize if linearly separable ... may need changes to divisor // and bias calculations //} else { // Not linearly separable for(var y=0;y<h;++y) { for(var x=0;x<w;++x) { idx = r = g = b = 0; di = (y*w + x) << 2; for(var ky=-this.r;ky<=this.r;++ky) { for(var kx=-this.r;kx<=this.r;++kx) { si = (Math.max(0, Math.min(h - 1, y + ky)) * w + Math.max(0, Math.min(w - 1, x + kx))) << 2; r += srcData[si]*this.matrix[idx]; g += srcData[si + 1]*this.matrix[idx]; b += srcData[si + 2]*this.matrix[idx]; //a += srcData[si + 3]*this.matrix[idx]; idx++; } } dstData[di] = r/this.divisor + this.bias; dstData[di + 1] = g/this.divisor + this.bias; dstData[di + 2] = b/this.divisor + this.bias; //dstData[di + 3] = a/this.divisor + this.bias; dstData[di + 3] = 255; } } //} // for Firefox //dstData.forEach(function(n, i, arr) { arr[i] = n<0 ? 0 : n>255 ? 255 : n; }); } });
JavaScript
/* Base.js, version 1.1 Copyright 2006-2007, Dean Edwards License: http://www.opensource.org/licenses/mit-license.php */ var Base = function() { // dummy }; Base.extend = function(_instance, _static) { // subclass var extend = Base.prototype.extend; // build the prototype Base._prototyping = true; var proto = new this; extend.call(proto, _instance); delete Base._prototyping; // create the wrapper for the constructor function //var constructor = proto.constructor.valueOf(); //-dean var constructor = proto.constructor; var klass = proto.constructor = function() { if (!Base._prototyping) { if (this._constructing || this.constructor == klass) { // instantiation this._constructing = true; constructor.apply(this, arguments); delete this._constructing; } else if (arguments[0] != null) { // casting return (arguments[0].extend || extend).call(arguments[0], proto); } } }; // build the class interface klass.ancestor = this; klass.extend = this.extend; klass.forEach = this.forEach; klass.implement = this.implement; klass.prototype = proto; klass.toString = this.toString; klass.valueOf = function(type) { //return (type == "object") ? klass : constructor; //-dean return (type == "object") ? klass : constructor.valueOf(); }; extend.call(klass, _static); // class initialisation if (typeof klass.init == "function") klass.init(); return klass; }; Base.prototype = { extend: function(source, value) { if (arguments.length > 1) { // extending with a name/value pair var ancestor = this[source]; if (ancestor && (typeof value == "function") && // overriding a method? // the valueOf() comparison is to avoid circular references (!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) && /\bbase\b/.test(value)) { // get the underlying method var method = value.valueOf(); // override value = function() { var previous = this.base || Base.prototype.base; this.base = ancestor; var returnValue = method.apply(this, arguments); this.base = previous; return returnValue; }; // point to the underlying method value.valueOf = function(type) { return (type == "object") ? value : method; }; value.toString = Base.toString; } this[source] = value; } else if (source) { // extending with an object literal var extend = Base.prototype.extend; // if this object has a customised extend method then use it if (!Base._prototyping && typeof this != "function") { extend = this.extend || extend; } var proto = {toSource: null}; // do the "toString" and other methods manually var hidden = ["constructor", "toString", "valueOf"]; // if we are prototyping then include the constructor var i = Base._prototyping ? 0 : 1; while (key = hidden[i++]) { if (source[key] != proto[key]) { extend.call(this, key, source[key]); } } // copy each of the source object's properties to this object for (var key in source) { if (!proto[key]) extend.call(this, key, source[key]); } } return this; }, base: function() { // call this method from any other method to invoke that method's ancestor } }; // initialise Base = Base.extend({ constructor: function() { this.extend(arguments[0]); } }, { ancestor: Object, version: "1.1", forEach: function(object, block, context) { for (var key in object) { if (this.prototype[key] === undefined) { block.call(context, object[key], key, object); } } }, implement: function() { for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] == "function") { // if it's a function, call it arguments[i](this.prototype); } else { // add the interface using the extend method this.prototype.extend(arguments[i]); } } return this; }, toString: function() { return String(this.valueOf()); } });
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var TESTS_INTERACTIVE = 0x01; var TESTS_AUTOMATED = 0x02; var TESTS_ALL = TESTS_INTERACTIVE | TESTS_AUTOMATED; var g_tests = []; var g_testsByName = {}; function init() { discoverTests(); buildTestTable(); } function discoverTests() { g_testsByName = {}; if (navigator.userAgent.toLowerCase().indexOf('msie') >= 0) { // IE doesn't support enumerating custom members of window for (var i = 0; i < document.scripts.length; i++) { var scriptNode = document.scripts[i]; var scriptBody = ''; if (scriptNode.innerHTML) { scriptBody += scriptNode.innerHTML; } if (scriptNode.src) { try { var xhr = new ActiveXObject('Msxml2.XMLHTTP'); xhr.open('get', scriptNode.src, false); // false -- not async xhr.send(); scriptBody += xhr.responseText; } catch (e) {} } // parse script body for test_xx functions var possibleTests = scriptBody.match(/test_\w+/g); if (possibleTests) { for (var j = 0; j < possibleTests.length; j++) { if (possibleTests[j] in window && typeof window[possibleTests[j]] === 'function') g_testsByName[possibleTests[j]] = true; } } } } else { for (var f in window) { if (f.substr(0, 5) == 'test_' && typeof window[f] === 'function') g_testsByName[f] = true; } } // convert into an array g_tests = []; for (var test in g_testsByName) { g_tests.push(test); } g_tests.sort(); } function buildTestTable() { var testTable = jQuery('#test-table'); for (var i = 0; i < g_tests.length; i++) { var row = jQuery('<tr id="testrow_' + g_tests[i] + '" "class="test">'); row.append(jQuery('<td class="test-number">' + (i + 1) + '</tr>')); row.append(jQuery('<td class="test-name">' + g_tests[i] + '</td>')); row.append(jQuery('<td class="test-status">&nbsp;</td>')); var runTestButton = jQuery('<input type="button" value="Run">') .click(function(testName) { return function() { enableUI(false); runSingleTest(testName, function() { enableUI(true); }); }; }(g_tests[i])); row.append(jQuery('<td class="test-actions"></td>').append(runTestButton)); var notes = []; if (window[g_tests[i]].interactive) notes.push('Interactive'); if (window[g_tests[i]].async) notes.push('Async'); row.append(jQuery('<td class="test-notes">' + (notes.join(', ') || '&nbsp;') + '</td>')); testTable.append(row); } } function clearResults() { jQuery('tr.test').removeClass('pass').removeClass('fail'); jQuery('.test-status').html('&nbsp;'); } function isEmptyObjectLiteral(o) { if (!o) return true; for (var k in o) return false; return true; } function logResult(testName, pass, message, otherInfo) { var testRow = jQuery('#testrow_' + testName); if (!testRow || !testRow.length) return; testRow.removeClass('pass').removeClass('fail'); testRow.addClass(pass ? 'pass' : 'fail'); var testStatusCell = jQuery('.test-status', testRow); message = message ? message.toString() : (pass ? 'pass' : 'fail') testStatusCell.text(message); if (!isEmptyObjectLiteral(otherInfo)) { testStatusCell.append(jQuery('<div><a href="#">[More Info]</a></div>') .click(function() { jQuery('.other-info', testStatusCell).toggle(); return false; })); var otherInfoHtml = ['<ul class="other-info" style="display: none">']; for (var k in otherInfo) { otherInfoHtml.push('<li><span>' + (k || '&nbsp;') + '</span>'); otherInfoHtml.push((otherInfo[k] || '&nbsp;') + '</li>'); } otherInfoHtml.push('</ul>'); testStatusCell.append(jQuery(otherInfoHtml.join(''))); } } function enableUI(enable) { if (enable) jQuery('input').removeAttr('disabled'); else jQuery('input').attr('disabled', true); } function runSingleTest(testName, completeFn) { completeFn = completeFn || function(){}; var testFn = window[testName]; var successFn = function() { // log result and run next test logResult(testName, true); completeFn(); }; var errorFn = function(e) { var message = ''; var otherInfo = {}; if (e.jsUnitMessage) { message = new String(e.jsUnitMessage); } else if (e.message) { message = new String(e.message); } else if (e.comment) { message = new String(e.comment); } else if (e.description) { message = new String(e.description); } // log result and run next test for (var k in e) { var val = e[k]; if (val === null) val = '<null>'; else if (typeof(e[k]) == 'undefined') val = '<undefined>'; val = val.toString(); if (k == 'stackTrace') { var MAX_LENGTH = 500; if (val.length >= MAX_LENGTH) val = val.substr(0, MAX_LENGTH - 3) + '...'; } otherInfo[k] = val; } logResult(testName, false, message, otherInfo); completeFn(); }; var runFunc = function() { if (testFn.interactive || testFn.async) { testFn.call(null, successFn, errorFn); } else { testFn.call(null); successFn(); } }; var passExceptions = document.getElementById('passexceptions').checked; if (passExceptions) { runFunc.call(); } else { try { runFunc.call(); } catch (e) { errorFn(e); } } } function runTests(type) { if (!type) type = TESTS_ALL; enableUI(false); clearResults(); var i = -1; var runNextTest = function() { i++; if (i >= g_tests.length) { enableUI(true); return; } var testName = g_tests[i]; var testFn = window[testName]; if (testFn.interactive) { if (!(type & TESTS_INTERACTIVE)) { runNextTest(); return; } } else { if (!(type & TESTS_AUTOMATED)) { runNextTest(); return; } } runSingleTest(testName, runNextTest); } runNextTest(); }
JavaScript
// Spectrum: The No Hassle Colorpicker // https://github.com/bgrins/spectrum // Author: Brian Grinstead // License: MIT // Requires: jQuery, spectrum.css (function (window, $, undefined) { var defaultOpts = { // Events beforeShow: noop, move: noop, change: noop, show: noop, hide: noop, // Options color: false, flat: false, showInput: false, showButtons: true, showInitial: false, showPalette: false, showPaletteOnly: false, showSelectionPalette: true, localStorageKey: false, maxSelectionSize: 7, cancelText: "cancel", chooseText: "choose", preferredFormat: false, className: "", theme: "sp-light", palette: ['fff', '000'], selectionPalette: [] }, spectrums = [], IE = $.browser.msie, replaceInput = [ "<div class='sp-replacer'>", "<div class='sp-preview'></div>", "<div class='sp-dd'>&#9660;</div>", "</div>" ].join(''), markup = (function () { // IE does not support gradients with multiple stops, so we need to simulate // that for the rainbow slider with 8 divs that each have a single gradient var gradientFix = ""; if (IE) { for (var i = 1; i <= 6; i++) { gradientFix += "<div class='sp-" + i + "'></div>"; } } return [ "<div class='sp-container'>", "<div class='sp-palette-container'>", "<div class='sp-palette sp-thumb sp-cf'></div>", "</div>", "<div class='sp-picker-container'>", "<div class='sp-top sp-cf'>", "<div class='sp-fill'></div>", "<div class='sp-top-inner'>", "<div class='sp-color'>", "<div class='sp-sat'>", "<div class='sp-val'>", "<div class='sp-dragger'></div>", "</div>", "</div>", "</div>", "<div class='sp-hue'>", "<div class='sp-slider'></div>", gradientFix, "</div>", "</div>", "</div>", "<div class='sp-input-container sp-cf'>", "<input class='sp-input' type='text' spellcheck='false' />", "</div>", "<div class='sp-initial sp-thumb sp-cf'></div>", "<div class='sp-button-container sp-cf'>", "<a class='sp-cancel' href='#'></a>", "<button class='sp-choose'></button>", "</div>", "</div>", "</div>" ].join(""); })(), paletteTemplate = function (p, color, className) { var html = []; for (var i = 0; i < p.length; i++) { var tiny = tinycolor(p[i]); var c = tiny.toHsl().l < .5 ? "sp-thumb-dark" : "sp-thumb-light"; c += (tinycolor.equals(color, p[i])) ? " sp-thumb-active" : ""; html.push('<span title="' + tiny.toHexString() + '" data-color="' + tiny.toHexString() + '" style="background-color:' + tiny.toRgbString() + ';" class="' + c + '"></span>'); } return "<div class='sp-cf " + className + "'>" + html.join('') + "</div>"; }; function hideAll() { for (var i = 0; i < spectrums.length; i++) { if (spectrums[i]) { spectrums[i].hide(); } } } function instanceOptions(o, callbackContext) { var opts = $.extend({}, defaultOpts, o); opts.callbacks = { 'move': bind(opts.move, callbackContext), 'change': bind(opts.change, callbackContext), 'show': bind(opts.show, callbackContext), 'hide': bind(opts.hide, callbackContext), 'beforeShow': bind(opts.beforeShow, callbackContext) }; return opts; } function spectrum(element, o) { var opts = instanceOptions(o, element), flat = opts.flat, showPaletteOnly = opts.showPaletteOnly, showPalette = opts.showPalette || showPaletteOnly, showInitial = opts.showInitial && !flat, showInput = opts.showInput, showSelectionPalette = opts.showSelectionPalette, localStorageKey = opts.localStorageKey, theme = opts.theme, callbacks = opts.callbacks, resize = throttle(reflow, 10), visible = false, dragWidth = 0, dragHeight = 0, dragHelperHeight = 0, slideHeight = 0, slideWidth = 0, slideHelperHeight = 0, currentHue = 0, currentSaturation = 0, currentValue = 0, palette = opts.palette.slice(0), paletteArray = $.isArray(palette[0]) ? palette : [palette], selectionPalette = opts.selectionPalette.slice(0), draggingClass = "sp-dragging"; var doc = element.ownerDocument, body = doc.body, boundElement = $(element), container = $(markup, doc).addClass(theme), dragger = container.find(".sp-color"), dragHelper = container.find(".sp-dragger"), slider = container.find(".sp-hue"), slideHelper = container.find(".sp-slider"), textInput = container.find(".sp-input"), paletteContainer = container.find(".sp-palette"), initialColorContainer = container.find(".sp-initial"), cancelButton = container.find(".sp-cancel"), chooseButton = container.find(".sp-choose"), isInput = boundElement.is("input"), shouldReplace = isInput && !flat, replacer = (shouldReplace) ? $(replaceInput).addClass(theme) : $([]), offsetElement = (shouldReplace) ? replacer : boundElement, previewElement = replacer.find(".sp-preview"), initialColor = opts.color || (isInput && boundElement.val()), colorOnShow = false, preferredFormat = opts.preferredFormat, currentPreferredFormat = preferredFormat, clickoutFiresChange = !opts.showButtons; chooseButton.text(opts.chooseText); cancelButton.text(opts.cancelText); function initialize() { if (IE) { container.find("*:not(input)").attr("unselectable", "on"); } container.toggleClass("sp-flat", flat); container.toggleClass("sp-input-disabled", !showInput); container.toggleClass("sp-buttons-disabled", !opts.showButtons || flat); container.toggleClass("sp-palette-disabled", !showPalette); container.toggleClass("sp-palette-only", showPaletteOnly); container.toggleClass("sp-initial-disabled", !showInitial); container.addClass(opts.className); if (shouldReplace) { boundElement.hide().after(replacer); } if (flat) { boundElement.after(container).hide(); } else { $(body).append(container.hide()); } if (localStorageKey && window.localStorage) { try { selectionPalette = window.localStorage[localStorageKey].split(","); } catch (e) { } } offsetElement.bind("click.spectrum touchstart.spectrum", function (e) { toggle(); e.stopPropagation(); if (!$(e.target).is("input")) { e.preventDefault(); } }); // Prevent clicks from bubbling up to document. This would cause it to be hidden. container.click(stopPropagation); // Handle user typed input textInput.change(setFromTextInput); textInput.bind("paste", function () { setTimeout(setFromTextInput, 1); }); textInput.keydown(function (e) { if (e.keyCode == 13) { setFromTextInput(); } }); cancelButton.bind("click.spectrum", function (e) { e.stopPropagation(); e.preventDefault(); hide(); }); chooseButton.bind("click.spectrum", function (e) { e.stopPropagation(); e.preventDefault(); if (isValid()) { updateOriginalInput(true); hide(); } }); draggable(slider, function (dragX, dragY) { currentHue = (dragY / slideHeight); move(); }, dragStart, dragStop); draggable(dragger, function (dragX, dragY) { currentSaturation = dragX / dragWidth; currentValue = (dragHeight - dragY) / dragHeight; move(); }, dragStart, dragStop); if (!!initialColor) { set(initialColor); // In case color was black - update the preview UI and set the format // since the set function will not run (default color is black). updateUI(); currentPreferredFormat = preferredFormat || tinycolor(initialColor).format; addColorToSelectionPalette(initialColor); } else { updateUI(); } if (flat) { show(); } function palletElementClick(e) { if (e.data && e.data.ignore) { set($(this).data("color")); move(); } else { set($(this).data("color")); updateOriginalInput(true); move(); hide(); } return false; } var paletteEvent = IE ? "mousedown.spectrum" : "click.spectrum touchstart.spectrum"; paletteContainer.delegate("span", paletteEvent, palletElementClick); initialColorContainer.delegate("span::nth-child(1)", paletteEvent, { ignore: true }, palletElementClick); } function addColorToSelectionPalette(color) { if (showSelectionPalette) { selectionPalette.push(tinycolor(color).toHexString()); if (localStorageKey && window.localStorage) { window.localStorage[localStorageKey] = selectionPalette.join(","); } } } function getUniqueSelectionPalette() { var unique = []; var p = selectionPalette; var paletteLookup = {}; if (showPalette) { for (var i = 0; i < paletteArray.length; i++) { for (var j = 0; j < paletteArray[i].length; j++) { var hex = tinycolor(paletteArray[i][j]).toHexString(); paletteLookup[hex] = true; } } for (var i = 0; i < p.length; i++) { var color = tinycolor(p[i]); var hex = color.toHexString(); if (!paletteLookup.hasOwnProperty(hex)) { unique.push(p[i]); paletteLookup[hex] = true; } } } return unique.reverse().slice(0, opts.maxSelectionSize); } function drawPalette() { var currentColor = get(); var html = $.map(paletteArray, function (palette, i) { return paletteTemplate(palette, currentColor, "sp-palette-row sp-palette-row-" + i); }); if (selectionPalette) { html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, "sp-palette-row sp-palette-row-selection")); } paletteContainer.html(html.join("")); } function drawInitial() { if (showInitial) { var initial = colorOnShow; var current = get(); initialColorContainer.html(paletteTemplate([initial, current], current, "sp-palette-row-initial")); } } function dragStart() { if (dragHeight === 0 || dragWidth === 0 || slideHeight === 0) { reflow(); } container.addClass(draggingClass); } function dragStop() { container.removeClass(draggingClass); } function setFromTextInput() { var tiny = tinycolor(textInput.val()); if (tiny.ok) { set(tiny); } else { textInput.addClass("sp-validation-error"); } } function toggle() { (visible) ? hide() : show(); } function show() { if (visible) { reflow(); return; } if (callbacks.beforeShow(get()) === false) return; hideAll(); visible = true; $(doc).bind("click.spectrum", hide); $(window).bind("resize.spectrum", resize); replacer.addClass("sp-active"); container.show(); if (showPalette) { drawPalette(); } reflow(); updateUI(); colorOnShow = get(); drawInitial(); callbacks.show(colorOnShow); } function hide() { if (!visible || flat) { return; } visible = false; $(doc).unbind("click.spectrum", hide); $(window).unbind("resize.spectrum", resize); replacer.removeClass("sp-active"); container.hide(); var colorHasChanged = !tinycolor.equals(get(), colorOnShow); if (colorHasChanged) { if (clickoutFiresChange) { updateOriginalInput(true); } else { revert(); } } callbacks.hide(get()); } function revert() { set(colorOnShow, true); } function set(color, ignoreFormatChange) { if (tinycolor.equals(color, get())) { return; } var newColor = tinycolor(color); var newHsv = newColor.toHsv(); currentHue = newHsv.h; currentSaturation = newHsv.s; currentValue = newHsv.v; updateUI(); if (!ignoreFormatChange) { currentPreferredFormat = preferredFormat || newColor.format; } } function get() { return tinycolor.fromRatio({ h: currentHue, s: currentSaturation, v: currentValue }); } function isValid() { return !textInput.hasClass("sp-validation-error"); } function move() { updateUI(); callbacks.move(get()); } function updateUI() { textInput.removeClass("sp-validation-error"); updateHelperLocations(); // Update dragger background color (gradients take care of saturation and value). var flatColor = tinycolor({ h: currentHue, s: "1.0", v: "1.0" }); dragger.css("background-color", flatColor.toHexString()); var realColor = get(), realHex = realColor.toHexString(); // Update the replaced elements background color (with actual selected color) previewElement.css("background-color", realHex); // Update the text entry input as it changes happen if (showInput) { textInput.val(realColor.toString(currentPreferredFormat)); } if (showPalette) { drawPalette(); } drawInitial(); } function updateHelperLocations() { var h = currentHue; var s = currentSaturation; var v = currentValue; // Where to show the little circle in that displays your current selected color var dragX = s * dragWidth; var dragY = dragHeight - (v * dragHeight); dragX = Math.max( -dragHelperHeight, Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight) ); dragY = Math.max( -dragHelperHeight, Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight) ); dragHelper.css({ "top": dragY, "left": dragX }); // Where to show the bar that displays your current selected hue var slideY = (currentHue) * slideHeight; slideHelper.css({ "top": slideY - slideHelperHeight }); } function updateOriginalInput(fireCallback) { var color = get(); if (isInput) { boundElement.val(color.toString(currentPreferredFormat)).change(); } var hasChanged = !tinycolor.equals(color, colorOnShow); colorOnShow = color; // Update the selection palette with the current color addColorToSelectionPalette(color); if (fireCallback && hasChanged) { callbacks.change(color); } } function reflow() { dragWidth = dragger.width(); dragHeight = dragger.height(); dragHelperHeight = dragHelper.height(); slideWidth = slider.width(); slideHeight = slider.height(); slideHelperHeight = slideHelper.height(); if (!flat) { container.offset(getOffset(container, offsetElement)); } updateHelperLocations(); } function destroy() { boundElement.show(); offsetElement.unbind("click.spectrum touchstart.spectrum"); container.remove(); replacer.remove(); spectrums[spect.id] = null; } initialize(); var spect = { show: show, hide: hide, set: function (c) { set(c); updateOriginalInput(); }, get: get, destroy: destroy, container: container }; spect.id = spectrums.push(spect) - 1; return spect; } /** * checkOffset - get the offset below/above and left/right element depending on screen position * Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js */ function getOffset(picker, input) { var extraY = 0; var dpWidth = picker.outerWidth(); var dpHeight = picker.outerHeight(); var inputWidth = input.outerWidth(); var inputHeight = input.outerHeight(); var doc = picker[0].ownerDocument; var docElem = doc.documentElement; var viewWidth = docElem.clientWidth + $(doc).scrollLeft(); var viewHeight = docElem.clientHeight + $(doc).scrollTop(); var offset = input.offset(); offset.top += inputHeight; offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, ((offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight - extraY) : extraY)); return offset; } /** * noop - do nothing */ function noop() { } /** * stopPropagation - makes the code only doing this a little easier to read in line */ function stopPropagation(e) { e.stopPropagation(); } /** * Create a function bound to a given object * Thanks to underscore.js */ function bind(func, obj) { var slice = Array.prototype.slice; var args = slice.call(arguments, 2); return function () { return func.apply(obj, args.concat(slice.call(arguments))); } } /** * Lightweight drag helper. Handles containment within the element, so that * when dragging, the x is within [0,element.width] and y is within [0,element.height] */ function draggable(element, onmove, onstart, onstop) { onmove = onmove || function () { }; onstart = onstart || function () { }; onstop = onstop || function () { }; var doc = element.ownerDocument || document; var dragging = false; var offset = {}; var maxHeight = 0; var maxWidth = 0; var IE = $.browser.msie; var hasTouch = ('ontouchstart' in window); var duringDragEvents = {}; duringDragEvents["selectstart"] = prevent; duringDragEvents["dragstart"] = prevent; duringDragEvents[(hasTouch ? "touchmove" : "mousemove")] = move; duringDragEvents[(hasTouch ? "touchend" : "mouseup")] = stop; function prevent(e) { if (e.stopPropagation) { e.stopPropagation(); } if (e.preventDefault) { e.preventDefault(); } e.returnValue = false; } function move(e) { if (dragging) { // Mouseup happened outside of window if (IE && !(document.documentMode >= 9) && !e.button) { return stop(); } var touches = e.originalEvent.touches; var pageX = touches ? touches[0].pageX : e.pageX; var pageY = touches ? touches[0].pageY : e.pageY; var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth)); var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight)); if (hasTouch) { // Stop scrolling in iOS prevent(e); } onmove.apply(element, [dragX, dragY]); } } function start(e) { var rightclick = (e.which) ? (e.which == 3) : (e.button == 2); var touches = e.originalEvent.touches; if (!rightclick && !dragging) { if (onstart.apply(element, arguments) !== false) { dragging = true; maxHeight = $(element).height(); maxWidth = $(element).width(); offset = $(element).offset(); $(doc).bind(duringDragEvents); $(doc.body).addClass("sp-dragging"); if (!hasTouch) { move(e); } prevent(e); } } } function stop() { if (dragging) { $(doc).unbind(duringDragEvents); $(doc.body).removeClass("sp-dragging"); onstop.apply(element, arguments); } dragging = false; } $(element).bind(hasTouch ? "touchstart" : "mousedown", start); } function throttle(func, wait, debounce) { var timeout; return function () { var context = this, args = arguments; var throttler = function () { timeout = null; func.apply(context, args); }; if (debounce) clearTimeout(timeout); if (debounce || !timeout) timeout = setTimeout(throttler, wait); }; } /** * Define a jQuery plugin */ var dataID = "spectrum.id"; $.fn.spectrum = function (opts, extra) { if (typeof opts == "string") { if (opts == "get") { return spectrums[this.eq(0).data(dataID)].get(); } else if (opts == "container") { return spectrums[$(this).data(dataID)].container; } return this.each(function () { var spect = spectrums[$(this).data(dataID)]; if (spect) { if (opts == "show") { spect.show(); } if (opts == "hide") { spect.hide(); } if (opts == "set") { spect.set(extra); } if (opts == "destroy") { spect.destroy(); $(this).removeData(dataID); } } }); } // Initializing a new one return this.spectrum("destroy").each(function () { var spect = spectrum(this, opts); $(this).data(dataID, spect.id); }); }; $.fn.spectrum.load = true; $.fn.spectrum.loadOpts = {}; $.fn.spectrum.draggable = draggable; $.fn.spectrum.processNativeColorInputs = function() { var supportsColor = $("<input type='color' />")[0].type === "color"; if (!supportsColor) { $("input[type=color]").spectrum({ preferredFormat: "hex6" }); } }; $(function () { if ($.fn.spectrum.load) { $.fn.spectrum.processNativeColorInputs(); } }); })(this, jQuery); // TinyColor.js - <https://github.com/bgrins/TinyColor> - 2011 Brian Grinstead - v0.5 (function (window) { var trimLeft = /^[\s,#]+/, trimRight = /\s+$/, tinyCounter = 0, math = Math, mathRound = math.round, mathMin = math.min, mathMax = math.max, mathRandom = math.random, parseFloat = window.parseFloat; function tinycolor(color, opts) { // If input is already a tinycolor, return itself if (typeof color == "object" && color.hasOwnProperty("_tc_id")) { return color; } var rgb = inputToRGB(color); var r = rgb.r, g = rgb.g, b = rgb.b, a = parseFloat(rgb.a), format = rgb.format; return { ok: rgb.ok, format: format, _tc_id: tinyCounter++, alpha: a, toHsv: function () { var hsv = rgbToHsv(r, g, b); return { h: hsv.h, s: hsv.s, v: hsv.v, a: a }; }, toHsvString: function () { var hsv = rgbToHsv(r, g, b); var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100); return (a == 1) ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + a + ")"; }, toHsl: function () { var hsl = rgbToHsl(r, g, b); return { h: hsl.h, s: hsl.s, l: hsl.l, a: a }; }, toHslString: function () { var hsl = rgbToHsl(r, g, b); var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100); return (a == 1) ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + a + ")"; }, toHex: function () { return rgbToHex(r, g, b); }, toHexString: function (force6Char) { return '#' + rgbToHex(r, g, b, force6Char); }, toRgb: function () { return { r: mathRound(r), g: mathRound(g), b: mathRound(b), a: a }; }, toRgbString: function () { return (a == 1) ? "rgb(" + mathRound(r) + ", " + mathRound(g) + ", " + mathRound(b) + ")" : "rgba(" + mathRound(r) + ", " + mathRound(g) + ", " + mathRound(b) + ", " + a + ")"; }, toName: function () { return hexNames[rgbToHex(r, g, b)] || false; }, toFilter: function () { var hex = rgbToHex(r, g, b); var alphaHex = Math.round(parseFloat(a) * 255).toString(16); return "progid:DXImageTransform.Microsoft.gradient(startColorstr=#" + alphaHex + hex + ",endColorstr=#" + alphaHex + hex + ")"; }, toString: function (format) { format = format || this.format; var formattedString = false; if (format === "rgb") { formattedString = this.toRgbString(); } if (format === "hex") { formattedString = this.toHexString(); } if (format === "hex6") { formattedString = this.toHexString(true); } if (format === "name") { formattedString = this.toName(); } if (format === "hsl") { formattedString = this.toHslString(); } if (format === "hsv") { formattedString = this.toHsvString(); } return formattedString || this.toHexString(); } }; } // If input is an object, force 1 into "1.0" to handle ratios properly // String input requires "1.0" as input, so 1 will be treated as 1 tinycolor.fromRatio = function(color) { if (typeof color == "object") { for (var i in color) { if (color[i] === 1) { color[i] = "1.0"; } } } return tinycolor(color); } // Given a string or object, convert that input to RGB // Possible string inputs: // // "red" // "#f00" or "f00" // "#ff0000" or "ff0000" // "rgb 255 0 0" or "rgb (255, 0, 0)" // "rgb 1.0 0 0" or "rgb (1, 0, 0)" // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" // function inputToRGB(color) { var rgb = { r: 0, g: 0, b: 0 }; var a = 1; var ok = false; var format = false; if (typeof color == "string") { color = stringInputToObject(color); } if (typeof color == "object") { if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) { rgb = rgbToRgb(color.r, color.g, color.b); ok = true; format = "rgb"; } else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) { rgb = hsvToRgb(color.h, color.s, color.v); ok = true; format = "hsv"; } else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) { var rgb = hslToRgb(color.h, color.s, color.l); ok = true; format = "hsl"; } if (color.hasOwnProperty("a")) { a = color.a; } } rgb.r = mathMin(255, mathMax(rgb.r, 0)); rgb.g = mathMin(255, mathMax(rgb.g, 0)); rgb.b = mathMin(255, mathMax(rgb.b, 0)); // Don't let the range of [0,255] come back in [0,1]. // Potentially lose a little bit of precision here, but will fix issues where // .5 gets interpreted as half of the total, instead of half of 1. // If it was supposed to be 128, this was already taken care of in the conversion function if (rgb.r < 1) { rgb.r = mathRound(rgb.r); } if (rgb.g < 1) { rgb.g = mathRound(rgb.g); } if (rgb.b < 1) { rgb.b = mathRound(rgb.b); } return { ok: ok, format: (color && color.format) || format, r: rgb.r, g: rgb.g, b: rgb.b, a: a }; } // Conversion Functions // -------------------- // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript> // `rgbToRgb` // Handle bounds / percentage checking to conform to CSS color spec // <http://www.w3.org/TR/css3-color/> // *Assumes:* r, g, b in [0, 255] or [0, 1] // *Returns:* { r, g, b } in [0, 255] function rgbToRgb(r, g, b) { return { r: bound01(r, 255) * 255, g: bound01(g, 255) * 255, b: bound01(b, 255) * 255 }; } // `rgbToHsl` // Converts an RGB color value to HSL. // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] // *Returns:* { h, s, l } in [0,1] function rgbToHsl(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = mathMax(r, g, b), min = mathMin(r, g, b); var h, s, l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, l: l }; } // `hslToRgb` // Converts an HSL color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hslToRgb(h, s, l) { var r, g, b; h = bound01(h, 360); s = bound01(s, 100); l = bound01(l, 100); function hue2rgb(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } if (s == 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1 / 3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1 / 3); } return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHsv` // Converts an RGB color value to HSV // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] // *Returns:* { h, s, v } in [0,1] function rgbToHsv(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = mathMax(r, g, b), min = mathMin(r, g, b); var h, s, v = max; var d = max - min; s = max == 0 ? 0 : d / max; if (max == min) { h = 0; // achromatic } else { switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, v: v }; } // `hsvToRgb` // Converts an HSV color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hsvToRgb(h, s, v) { var r, g, b; h = bound01(h, 360) * 6; s = bound01(s, 100); v = bound01(v, 100); var i = math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t, v][mod], g = [t, v, v, q, p, p][mod], b = [p, p, t, v, v, q][mod]; return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHex` // Converts an RGB color to hex // Assumes r, g, and b are contained in the set [0, 255] // Returns a 3 or 6 character hex function rgbToHex(r, g, b, force6Char) { function pad(c) { return c.length == 1 ? '0' + c : '' + c; } var hex = [ pad(mathRound(r).toString(16)), pad(mathRound(g).toString(16)), pad(mathRound(b).toString(16)) ]; // Return a 3 character hex if possible if (!force6Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); } return hex.join(""); } // `equals` // Can be called with any tinycolor input tinycolor.equals = function (color1, color2) { if (!color1 || !color2) { return false; } return tinycolor(color1).toHex() == tinycolor(color2).toHex(); }; tinycolor.random = function () { return tinycolor.fromRatio({ r: mathRandom(), g: mathRandom(), b: mathRandom() }); }; // Modification Functions // ---------------------- // Thanks to less.js for some of the basics here // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js> tinycolor.desaturate = function (color, amount) { var hsl = tinycolor(color).toHsl(); hsl.s -= ((amount || 10) / 100); hsl.s = clamp01(hsl.s); return tinycolor(hsl); }; tinycolor.saturate = function (color, amount) { var hsl = tinycolor(color).toHsl(); hsl.s += ((amount || 10) / 100); hsl.s = clamp01(hsl.s); return tinycolor(hsl); }; tinycolor.greyscale = function (color) { return tinycolor.desaturate(color, 100); }; tinycolor.lighten = function (color, amount) { var hsl = tinycolor(color).toHsl(); hsl.l += ((amount || 10) / 100); hsl.l = clamp01(hsl.l); return tinycolor(hsl); }; tinycolor.darken = function (color, amount) { var hsl = tinycolor(color).toHsl(); hsl.l -= ((amount || 10) / 100); hsl.l = clamp01(hsl.l); return tinycolor(hsl); }; tinycolor.complement = function (color) { var hsl = tinycolor(color).toHsl(); hsl.h = (hsl.h + .5) % 1; return tinycolor(hsl); }; // Combination Functions // --------------------- // Thanks to jQuery xColor for some of the ideas behind these // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js> tinycolor.triad = function (color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h * 360; return [ tinycolor(color), tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) ]; }; tinycolor.tetrad = function (color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h * 360; return [ tinycolor(color), tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) ]; }; tinycolor.splitcomplement = function (color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h * 360; return [ tinycolor(color), tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l }) ]; }; tinycolor.analogous = function (color, results, slices) { results = results || 6; slices = slices || 30; var hsl = tinycolor(color).toHsl(); var part = 360 / slices var ret = [tinycolor(color)]; hsl.h *= 360; for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) { hsl.h = (hsl.h + part) % 360; ret.push(tinycolor(hsl)); } return ret; }; tinycolor.monochromatic = function (color, results) { results = results || 6; var hsv = tinycolor(color).toHsv(); var h = hsv.h, s = hsv.s, v = hsv.v; var ret = []; var modification = 1 / results; while (results--) { ret.push(tinycolor({ h: h, s: s, v: v })); v = (v + modification) % 1; } return ret; }; tinycolor.readable = function (color1, color2) { var a = tinycolor(color1).toRgb(), b = tinycolor(color2).toRgb(); return ( (b.r - a.r) * (b.r - a.r) + (b.g - a.g) * (b.g - a.g) + (b.b - a.b) * (b.b - a.b) ) > 0x28A4; }; // Big List of Colors // --------- // <http://www.w3.org/TR/css3-color/#svg-color> var names = tinycolor.names = { aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "0ff", aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc", bisque: "ffe4c4", black: "000", blanchedalmond: "ffebcd", blue: "00f", blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", burntsienna: "ea7e5d", cadetblue: "5f9ea0", chartreuse: "7fff00", chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c", cyan: "0ff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9", darkgreen: "006400", darkgrey: "a9a9a9", darkkhaki: "bdb76b", darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f", darkslategrey: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493", deepskyblue: "00bfff", dimgray: "696969", dimgrey: "696969", dodgerblue: "1e90ff", firebrick: "b22222", floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "f0f", gainsboro: "dcdcdc", ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f", grey: "808080", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082", ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00", lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgray: "d3d3d3", lightgreen: "90ee90", lightgrey: "d3d3d3", lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslategray: "789", lightslategrey: "789", lightsteelblue: "b0c4de", lightyellow: "ffffe0", lime: "0f0", limegreen: "32cd32", linen: "faf0e6", magenta: "f0f", maroon: "800000", mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370db", mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a", mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6", olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "db7093", papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6", purple: "800080", red: "f00", rosybrown: "bc8f8f", royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd", slategray: "708090", slategrey: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee", wheat: "f5deb3", white: "fff", whitesmoke: "f5f5f5", yellow: "ff0", yellowgreen: "9acd32" }; // Make it easy to access colors via `hexNames[hex]` var hexNames = tinycolor.hexNames = flip(names); // Utilities // --------- // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` function flip(o) { var flipped = {}; for (var i in o) { if (o.hasOwnProperty(i)) { flipped[o[i]] = i; } } return flipped; } // Take input from [0, n] and return it as [0, 1] function bound01(n, max) { if (isOnePointZero(n)) { n = "100%"; } var processPercent = isPercentage(n); n = mathMin(max, mathMax(0, parseFloat(n))); // Automatically convert percentage into number if (processPercent) { n = n * (max / 100); } // Handle floating point rounding errors if ((math.abs(n - max) < 0.000001)) { return 1; } else if (n >= 1) { return (n % max) / parseFloat(max); } return n; } // Force a number between 0 and 1 function clamp01(val) { return mathMin(1, mathMax(0, val)); } // Parse an integer into hex function parseHex(val) { return parseInt(val, 16); } // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0> function isOnePointZero(n) { return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; } // Check to see if string passed in is a percentage function isPercentage(n) { return typeof n === "string" && n.indexOf('%') != -1; } var matchers = (function () { // <http://www.w3.org/TR/css3-values/#integers> var CSS_INTEGER = "[-\\+]?\\d+%?"; // <http://www.w3.org/TR/css3-values/#number-value> var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; // Actual matching. // Parentheses and commas are optional, but not required. // Whitespace can take the place of commas or opening paren var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; return { rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ }; })(); // `stringInputToObject` // Permissive string parsing. Take in a number of formats, and output an object // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` function stringInputToObject(color) { color = color.replace(trimLeft, '').replace(trimRight, '').toLowerCase(); var named = false; if (names[color]) { color = names[color]; named = true; } else if (color == 'transparent') { return { r: 0, g: 0, b: 0, a: 0 }; } // Try to match string input using regular expressions. // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] // Just return an object and let the conversion functions handle that. // This way the result will be the same whether the tinycolor is initialized with string or object. var match; if ((match = matchers.rgb.exec(color))) { return { r: match[1], g: match[2], b: match[3] }; } if ((match = matchers.rgba.exec(color))) { return { r: match[1], g: match[2], b: match[3], a: match[4] }; } if ((match = matchers.hsl.exec(color))) { return { h: match[1], s: match[2], l: match[3] }; } if ((match = matchers.hsla.exec(color))) { return { h: match[1], s: match[2], l: match[3], a: match[4] }; } if ((match = matchers.hsv.exec(color))) { return { h: match[1], s: match[2], v: match[3] }; } if ((match = matchers.hex6.exec(color))) { return { r: parseHex(match[1]), g: parseHex(match[2]), b: parseHex(match[3]), format: named ? "name" : "hex" }; } if ((match = matchers.hex3.exec(color))) { return { r: parseHex(match[1] + '' + match[1]), g: parseHex(match[2] + '' + match[2]), b: parseHex(match[3] + '' + match[3]), format: named ? "name" : "hex" }; } return false; } // Everything is ready, expose to window window.tinycolor = tinycolor; })(this);
JavaScript
/** * A class to parse color values * @author Stoyan Stefanov <sstoo@gmail.com> * @link http://www.phpied.com/rgb-color-parser-in-javascript/ * @license Use it if you like it */ function RGBColor(color_string) { this.ok = false; // strip any leading # if (color_string.charAt(0) == '#') { // remove # if any color_string = color_string.substr(1,6); } color_string = color_string.replace(/ /g,''); color_string = color_string.toLowerCase(); // before getting into regexps, try simple matches // and overwrite the input var simple_colors = { aliceblue: 'f0f8ff', antiquewhite: 'faebd7', aqua: '00ffff', aquamarine: '7fffd4', azure: 'f0ffff', beige: 'f5f5dc', bisque: 'ffe4c4', black: '000000', blanchedalmond: 'ffebcd', blue: '0000ff', blueviolet: '8a2be2', brown: 'a52a2a', burlywood: 'deb887', cadetblue: '5f9ea0', chartreuse: '7fff00', chocolate: 'd2691e', coral: 'ff7f50', cornflowerblue: '6495ed', cornsilk: 'fff8dc', crimson: 'dc143c', cyan: '00ffff', darkblue: '00008b', darkcyan: '008b8b', darkgoldenrod: 'b8860b', darkgray: 'a9a9a9', darkgreen: '006400', darkkhaki: 'bdb76b', darkmagenta: '8b008b', darkolivegreen: '556b2f', darkorange: 'ff8c00', darkorchid: '9932cc', darkred: '8b0000', darksalmon: 'e9967a', darkseagreen: '8fbc8f', darkslateblue: '483d8b', darkslategray: '2f4f4f', darkturquoise: '00ced1', darkviolet: '9400d3', deeppink: 'ff1493', deepskyblue: '00bfff', dimgray: '696969', dodgerblue: '1e90ff', feldspar: 'd19275', firebrick: 'b22222', floralwhite: 'fffaf0', forestgreen: '228b22', fuchsia: 'ff00ff', gainsboro: 'dcdcdc', ghostwhite: 'f8f8ff', gold: 'ffd700', goldenrod: 'daa520', gray: '808080', green: '008000', greenyellow: 'adff2f', honeydew: 'f0fff0', hotpink: 'ff69b4', indianred : 'cd5c5c', indigo : '4b0082', ivory: 'fffff0', khaki: 'f0e68c', lavender: 'e6e6fa', lavenderblush: 'fff0f5', lawngreen: '7cfc00', lemonchiffon: 'fffacd', lightblue: 'add8e6', lightcoral: 'f08080', lightcyan: 'e0ffff', lightgoldenrodyellow: 'fafad2', lightgrey: 'd3d3d3', lightgreen: '90ee90', lightpink: 'ffb6c1', lightsalmon: 'ffa07a', lightseagreen: '20b2aa', lightskyblue: '87cefa', lightslateblue: '8470ff', lightslategray: '778899', lightsteelblue: 'b0c4de', lightyellow: 'ffffe0', lime: '00ff00', limegreen: '32cd32', linen: 'faf0e6', magenta: 'ff00ff', maroon: '800000', mediumaquamarine: '66cdaa', mediumblue: '0000cd', mediumorchid: 'ba55d3', mediumpurple: '9370d8', mediumseagreen: '3cb371', mediumslateblue: '7b68ee', mediumspringgreen: '00fa9a', mediumturquoise: '48d1cc', mediumvioletred: 'c71585', midnightblue: '191970', mintcream: 'f5fffa', mistyrose: 'ffe4e1', moccasin: 'ffe4b5', navajowhite: 'ffdead', navy: '000080', oldlace: 'fdf5e6', olive: '808000', olivedrab: '6b8e23', orange: 'ffa500', orangered: 'ff4500', orchid: 'da70d6', palegoldenrod: 'eee8aa', palegreen: '98fb98', paleturquoise: 'afeeee', palevioletred: 'd87093', papayawhip: 'ffefd5', peachpuff: 'ffdab9', peru: 'cd853f', pink: 'ffc0cb', plum: 'dda0dd', powderblue: 'b0e0e6', purple: '800080', red: 'ff0000', rosybrown: 'bc8f8f', royalblue: '4169e1', saddlebrown: '8b4513', salmon: 'fa8072', sandybrown: 'f4a460', seagreen: '2e8b57', seashell: 'fff5ee', sienna: 'a0522d', silver: 'c0c0c0', skyblue: '87ceeb', slateblue: '6a5acd', slategray: '708090', snow: 'fffafa', springgreen: '00ff7f', steelblue: '4682b4', tan: 'd2b48c', teal: '008080', thistle: 'd8bfd8', tomato: 'ff6347', turquoise: '40e0d0', violet: 'ee82ee', violetred: 'd02090', wheat: 'f5deb3', white: 'ffffff', whitesmoke: 'f5f5f5', yellow: 'ffff00', yellowgreen: '9acd32' }; for (var key in simple_colors) { if (color_string == key) { color_string = simple_colors[key]; } } // emd of simple type-in colors // array of color definition objects var color_defs = [ { re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'], process: function (bits){ return [ parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3]) ]; } }, { re: /^(\w{2})(\w{2})(\w{2})$/, example: ['#00ff00', '336699'], process: function (bits){ return [ parseInt(bits[1], 16), parseInt(bits[2], 16), parseInt(bits[3], 16) ]; } }, { re: /^(\w{1})(\w{1})(\w{1})$/, example: ['#fb0', 'f0f'], process: function (bits){ return [ parseInt(bits[1] + bits[1], 16), parseInt(bits[2] + bits[2], 16), parseInt(bits[3] + bits[3], 16) ]; } } ]; // search through the definitions to find a match for (var i = 0; i < color_defs.length; i++) { var re = color_defs[i].re; var processor = color_defs[i].process; var bits = re.exec(color_string); if (bits) { channels = processor(bits); this.r = channels[0]; this.g = channels[1]; this.b = channels[2]; this.ok = true; } } // validate/cleanup values this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r); this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g); this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b); // some getters this.toRGB = function () { return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')'; } this.toHex = function () { var r = this.r.toString(16); var g = this.g.toString(16); var b = this.b.toString(16); if (r.length == 1) r = '0' + r; if (g.length == 1) g = '0' + g; if (b.length == 1) b = '0' + b; return '#' + r + g + b; } // help this.getHelpXML = function () { var examples = new Array(); // add regexps for (var i = 0; i < color_defs.length; i++) { var example = color_defs[i].example; for (var j = 0; j < example.length; j++) { examples[examples.length] = example[j]; } } // add type-in colors for (var sc in simple_colors) { examples[examples.length] = sc; } var xml = document.createElement('ul'); xml.setAttribute('id', 'rgbcolor-examples'); for (var i = 0; i < examples.length; i++) { try { var list_item = document.createElement('li'); var list_color = new RGBColor(examples[i]); var example_div = document.createElement('div'); example_div.style.cssText = 'margin: 3px; ' + 'border: 1px solid black; ' + 'background:' + list_color.toHex() + '; ' + 'color:' + list_color.toHex() ; example_div.appendChild(document.createTextNode('test')); var list_item_value = document.createTextNode( ' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex() ); list_item.appendChild(example_div); list_item.appendChild(list_item_value); xml.appendChild(list_item); } catch(e){} } return xml; } }
JavaScript
/* * canvg.js - Javascript SVG parser and renderer on Canvas * MIT Licensed * Gabe Lerner (gabelerner@gmail.com) * http://code.google.com/p/canvg/ * * Requires: rgbcolor.js - http://www.phpied.com/rgb-color-parser-in-javascript/ */ if(!window.console) { window.console = {}; window.console.log = function(str) {}; window.console.dir = function(str) {}; } // <3 IE if(!Array.indexOf){ Array.prototype.indexOf = function(obj){ for(var i=0; i<this.length; i++){ if(this[i]==obj){ return i; } } return -1; } } (function(){ // canvg(target, s) // target: canvas element or the id of a canvas element // s: svg string or url to svg file // opts: optional hash of options // ignoreMouse: true => ignore mouse events // ignoreAnimation: true => ignore animations // ignoreDimensions: true => does not try to resize canvas // ignoreClear: true => does not clear canvas // offsetX: int => draws at a x offset // offsetY: int => draws at a y offset // scaleWidth: int => scales horizontally to width // scaleHeight: int => scales vertically to height // renderCallback: function => will call the function after the first render is completed // forceRedraw: function => will call the function on every frame, if it returns true, will redraw this.canvg = function (target, s, opts) { if (typeof target == 'string') { target = document.getElementById(target); } // reuse class per canvas var svg; if (target.svg == null) { svg = build(); target.svg = svg; } else { svg = target.svg; svg.stop(); } svg.opts = opts; var ctx = target.getContext('2d'); if (s.substr(0,1) == '<') { // load from xml string svg.loadXml(ctx, s); } else { // load from url svg.load(ctx, s); } } function build() { var svg = { }; svg.FRAMERATE = 30; // globals svg.init = function(ctx) { svg.Definitions = {}; svg.Styles = {}; svg.Animations = []; svg.Images = []; svg.ctx = ctx; svg.ViewPort = new (function () { this.viewPorts = []; this.SetCurrent = function(width, height) { this.viewPorts.push({ width: width, height: height }); } this.RemoveCurrent = function() { this.viewPorts.pop(); } this.Current = function() { return this.viewPorts[this.viewPorts.length - 1]; } this.width = function() { return this.Current().width; } this.height = function() { return this.Current().height; } this.ComputeSize = function(d) { if (d != null && typeof(d) == 'number') return d; if (d == 'x') return this.width(); if (d == 'y') return this.height(); return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2); } }); } svg.init(); // images loaded svg.ImagesLoaded = function() { for (var i=0; i<svg.Images.length; i++) { if (!svg.Images[i].loaded) return false; } return true; } // trim svg.trim = function(s) { return s.replace(/^\s+|\s+$/g, ''); } // compress spaces svg.compressSpaces = function(s) { return s.replace(/[\s\r\t\n]+/gm,' '); } // ajax svg.ajax = function(url) { var AJAX; if(window.XMLHttpRequest){AJAX=new XMLHttpRequest();} else{AJAX=new ActiveXObject('Microsoft.XMLHTTP');} if(AJAX){ AJAX.open('GET',url,false); AJAX.send(null); return AJAX.responseText; } return null; } // parse xml svg.parseXml = function(xml) { if (window.DOMParser) { var parser = new DOMParser(); return parser.parseFromString(xml, 'text/xml'); } else { xml = xml.replace(/<!DOCTYPE svg[^>]*>/, ''); var xmlDoc = new ActiveXObject('Microsoft.XMLDOM'); xmlDoc.async = 'false'; xmlDoc.loadXML(xml); return xmlDoc; } } svg.Property = function(name, value) { this.name = name; this.value = value; this.hasValue = function() { return (this.value != null && this.value != ''); } // return the numerical value of the property this.numValue = function() { if (!this.hasValue()) return 0; var n = parseFloat(this.value); if ((this.value + '').match(/%$/)) { n = n / 100.0; } return n; } this.valueOrDefault = function(def) { if (this.hasValue()) return this.value; return def; } this.numValueOrDefault = function(def) { if (this.hasValue()) return this.numValue(); return def; } /* EXTENSIONS */ var that = this; // color extensions this.Color = { // augment the current color value with the opacity addOpacity: function(opacity) { var newValue = that.value; if (opacity != null && opacity != '') { var color = new RGBColor(that.value); if (color.ok) { newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacity + ')'; } } return new svg.Property(that.name, newValue); } } // definition extensions this.Definition = { // get the definition from the definitions table getDefinition: function() { var name = that.value.replace(/^(url\()?#([^\)]+)\)?$/, '$2'); return svg.Definitions[name]; }, isUrl: function() { return that.value.indexOf('url(') == 0 }, getFillStyle: function(e) { var def = this.getDefinition(); // gradient if (def != null && def.createGradient) { return def.createGradient(svg.ctx, e); } // pattern if (def != null && def.createPattern) { return def.createPattern(svg.ctx, e); } return null; } } // length extensions this.Length = { DPI: function(viewPort) { return 96.0; // TODO: compute? }, EM: function(viewPort) { var em = 12; var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); if (fontSize.hasValue()) em = fontSize.Length.toPixels(viewPort); return em; }, // get the length as pixels toPixels: function(viewPort) { if (!that.hasValue()) return 0; var s = that.value+''; if (s.match(/em$/)) return that.numValue() * this.EM(viewPort); if (s.match(/ex$/)) return that.numValue() * this.EM(viewPort) / 2.0; if (s.match(/px$/)) return that.numValue(); if (s.match(/pt$/)) return that.numValue() * 1.25; if (s.match(/pc$/)) return that.numValue() * 15; if (s.match(/cm$/)) return that.numValue() * this.DPI(viewPort) / 2.54; if (s.match(/mm$/)) return that.numValue() * this.DPI(viewPort) / 25.4; if (s.match(/in$/)) return that.numValue() * this.DPI(viewPort); if (s.match(/%$/)) return that.numValue() * svg.ViewPort.ComputeSize(viewPort); return that.numValue(); } } // time extensions this.Time = { // get the time as milliseconds toMilliseconds: function() { if (!that.hasValue()) return 0; var s = that.value+''; if (s.match(/s$/)) return that.numValue() * 1000; if (s.match(/ms$/)) return that.numValue(); return that.numValue(); } } // angle extensions this.Angle = { // get the angle as radians toRadians: function() { if (!that.hasValue()) return 0; var s = that.value+''; if (s.match(/deg$/)) return that.numValue() * (Math.PI / 180.0); if (s.match(/grad$/)) return that.numValue() * (Math.PI / 200.0); if (s.match(/rad$/)) return that.numValue(); return that.numValue() * (Math.PI / 180.0); } } } // fonts svg.Font = new (function() { this.Styles = ['normal','italic','oblique','inherit']; this.Variants = ['normal','small-caps','inherit']; this.Weights = ['normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900','inherit']; this.CreateFont = function(fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) { var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font); return { fontFamily: fontFamily || f.fontFamily, fontSize: fontSize || f.fontSize, fontStyle: fontStyle || f.fontStyle, fontWeight: fontWeight || f.fontWeight, fontVariant: fontVariant || f.fontVariant, toString: function () { return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' ') } } } var that = this; this.Parse = function(s) { var f = {}; var d = svg.trim(svg.compressSpaces(s || '')).split(' '); var set = { fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false } var ff = ''; for (var i=0; i<d.length; i++) { if (!set.fontStyle && that.Styles.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontStyle = d[i]; set.fontStyle = true; } else if (!set.fontVariant && that.Variants.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontVariant = d[i]; set.fontStyle = set.fontVariant = true; } else if (!set.fontWeight && that.Weights.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontWeight = d[i]; set.fontStyle = set.fontVariant = set.fontWeight = true; } else if (!set.fontSize) { if (d[i] != 'inherit') f.fontSize = d[i].split('/')[0]; set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; } else { if (d[i] != 'inherit') ff += d[i]; } } if (ff != '') f.fontFamily = ff; return f; } }); // points and paths svg.ToNumberArray = function(s) { var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' '); for (var i=0; i<a.length; i++) { a[i] = parseFloat(a[i]); } return a; } svg.Point = function(x, y) { this.x = x; this.y = y; this.angleTo = function(p) { return Math.atan2(p.y - this.y, p.x - this.x); } this.applyTransform = function(v) { var xp = this.x * v[0] + this.y * v[2] + v[4]; var yp = this.x * v[1] + this.y * v[3] + v[5]; this.x = xp; this.y = yp; } } svg.CreatePoint = function(s) { var a = svg.ToNumberArray(s); return new svg.Point(a[0], a[1]); } svg.CreatePath = function(s) { var a = svg.ToNumberArray(s); var path = []; for (var i=0; i<a.length; i+=2) { path.push(new svg.Point(a[i], a[i+1])); } return path; } // bounding box svg.BoundingBox = function(x1, y1, x2, y2) { // pass in initial points if you want this.x1 = Number.NaN; this.y1 = Number.NaN; this.x2 = Number.NaN; this.y2 = Number.NaN; this.x = function() { return this.x1; } this.y = function() { return this.y1; } this.width = function() { return this.x2 - this.x1; } this.height = function() { return this.y2 - this.y1; } this.addPoint = function(x, y) { if (x != null) { if (isNaN(this.x1) || isNaN(this.x2)) { this.x1 = x; this.x2 = x; } if (x < this.x1) this.x1 = x; if (x > this.x2) this.x2 = x; } if (y != null) { if (isNaN(this.y1) || isNaN(this.y2)) { this.y1 = y; this.y2 = y; } if (y < this.y1) this.y1 = y; if (y > this.y2) this.y2 = y; } } this.addX = function(x) { this.addPoint(x, null); } this.addY = function(y) { this.addPoint(null, y); } this.addBoundingBox = function(bb) { this.addPoint(bb.x1, bb.y1); this.addPoint(bb.x2, bb.y2); } this.addQuadraticCurve = function(p0x, p0y, p1x, p1y, p2x, p2y) { var cp1x = p0x + 2/3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0) var cp1y = p0y + 2/3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0) var cp2x = cp1x + 1/3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0) var cp2y = cp1y + 1/3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0) this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y); } this.addBezierCurve = function(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) { // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html var p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y]; this.addPoint(p0[0], p0[1]); this.addPoint(p3[0], p3[1]); for (i=0; i<=1; i++) { var f = function(t) { return Math.pow(1-t, 3) * p0[i] + 3 * Math.pow(1-t, 2) * t * p1[i] + 3 * (1-t) * Math.pow(t, 2) * p2[i] + Math.pow(t, 3) * p3[i]; } var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; var c = 3 * p1[i] - 3 * p0[i]; if (a == 0) { if (b == 0) continue; var t = -c / b; if (0 < t && t < 1) { if (i == 0) this.addX(f(t)); if (i == 1) this.addY(f(t)); } continue; } var b2ac = Math.pow(b, 2) - 4 * c * a; if (b2ac < 0) continue; var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); if (0 < t1 && t1 < 1) { if (i == 0) this.addX(f(t1)); if (i == 1) this.addY(f(t1)); } var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); if (0 < t2 && t2 < 1) { if (i == 0) this.addX(f(t2)); if (i == 1) this.addY(f(t2)); } } } this.isPointInBox = function(x, y) { return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2); } this.addPoint(x1, y1); this.addPoint(x2, y2); } // transforms svg.Transform = function(v) { var that = this; this.Type = {} // translate this.Type.translate = function(s) { this.p = svg.CreatePoint(s); this.apply = function(ctx) { ctx.translate(this.p.x || 0.0, this.p.y || 0.0); } this.applyToPoint = function(p) { p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); } } // rotate this.Type.rotate = function(s) { var a = svg.ToNumberArray(s); this.angle = new svg.Property('angle', a[0]); this.cx = a[1] || 0; this.cy = a[2] || 0; this.apply = function(ctx) { ctx.translate(this.cx, this.cy); ctx.rotate(this.angle.Angle.toRadians()); ctx.translate(-this.cx, -this.cy); } this.applyToPoint = function(p) { var a = this.angle.Angle.toRadians(); p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]); p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]); } } this.Type.scale = function(s) { this.p = svg.CreatePoint(s); this.apply = function(ctx) { ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0); } this.applyToPoint = function(p) { p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]); } } this.Type.matrix = function(s) { this.m = svg.ToNumberArray(s); this.apply = function(ctx) { ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]); } this.applyToPoint = function(p) { p.applyTransform(this.m); } } this.Type.SkewBase = function(s) { this.base = that.Type.matrix; this.base(s); this.angle = new svg.Property('angle', s); } this.Type.SkewBase.prototype = new this.Type.matrix; this.Type.skewX = function(s) { this.base = that.Type.SkewBase; this.base(s); this.m = [1, 0, Math.tan(this.angle.Angle.toRadians()), 1, 0, 0]; } this.Type.skewX.prototype = new this.Type.SkewBase; this.Type.skewY = function(s) { this.base = that.Type.SkewBase; this.base(s); this.m = [1, Math.tan(this.angle.Angle.toRadians()), 0, 1, 0, 0]; } this.Type.skewY.prototype = new this.Type.SkewBase; this.transforms = []; this.apply = function(ctx) { for (var i=0; i<this.transforms.length; i++) { this.transforms[i].apply(ctx); } } this.applyToPoint = function(p) { for (var i=0; i<this.transforms.length; i++) { this.transforms[i].applyToPoint(p); } } var data = v.split(/\s(?=[a-z])/); for (var i=0; i<data.length; i++) { var type = data[i].split('(')[0]; var s = data[i].split('(')[1].replace(')',''); var transform = eval('new this.Type.' + type + '(s)'); this.transforms.push(transform); } } // aspect ratio svg.AspectRatio = function(ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) { // aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute aspectRatio = svg.compressSpaces(aspectRatio); aspectRatio = aspectRatio.replace(/^defer\s/,''); // ignore defer var align = aspectRatio.split(' ')[0] || 'xMidYMid'; var meetOrSlice = aspectRatio.split(' ')[1] || 'meet'; // calculate scale var scaleX = width / desiredWidth; var scaleY = height / desiredHeight; var scaleMin = Math.min(scaleX, scaleY); var scaleMax = Math.max(scaleX, scaleY); if (meetOrSlice == 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; } if (meetOrSlice == 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; } refX = new svg.Property('refX', refX); refY = new svg.Property('refY', refY); if (refX.hasValue() && refY.hasValue()) { ctx.translate(-scaleMin * refX.Length.toPixels('x'), -scaleMin * refY.Length.toPixels('y')); } else { // align if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0); if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0); if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0); if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight); } // scale if (align == 'none') ctx.scale(scaleX, scaleY); else if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin); else if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax); // translate ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY); } // elements svg.Element = {} svg.Element.ElementBase = function(node) { this.attributes = {}; this.styles = {}; this.children = []; // get or create attribute this.attribute = function(name, createIfNotExists) { var a = this.attributes[name]; if (a != null) return a; a = new svg.Property(name, ''); if (createIfNotExists == true) this.attributes[name] = a; return a; } // get or create style this.style = function(name, createIfNotExists) { var s = this.styles[name]; if (s != null) return s; var a = this.attribute(name); if (a != null && a.hasValue()) { return a; } s = new svg.Property(name, ''); if (createIfNotExists == true) this.styles[name] = s; return s; } // base render this.render = function(ctx) { // don't render display=none if (this.attribute('display').value == 'none') return; ctx.save(); this.setContext(ctx); this.renderChildren(ctx); this.clearContext(ctx); ctx.restore(); } // base set context this.setContext = function(ctx) { // OVERRIDE ME! } // base clear context this.clearContext = function(ctx) { // OVERRIDE ME! } // base render children this.renderChildren = function(ctx) { for (var i=0; i<this.children.length; i++) { this.children[i].render(ctx); } } this.addChild = function(childNode, create) { var child = childNode; if (create) child = svg.CreateElement(childNode); child.parent = this; this.children.push(child); } if (node != null && node.nodeType == 1) { //ELEMENT_NODE // add children for (var i=0; i<node.childNodes.length; i++) { var childNode = node.childNodes[i]; if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE } // add attributes for (var i=0; i<node.attributes.length; i++) { var attribute = node.attributes[i]; this.attributes[attribute.nodeName] = new svg.Property(attribute.nodeName, attribute.nodeValue); } // add tag styles var styles = svg.Styles[this.type]; if (styles != null) { for (var name in styles) { this.styles[name] = styles[name]; } } // add class styles if (this.attribute('class').hasValue()) { var classes = svg.compressSpaces(this.attribute('class').value).split(' '); for (var j=0; j<classes.length; j++) { styles = svg.Styles['.'+classes[j]]; if (styles != null) { for (var name in styles) { this.styles[name] = styles[name]; } } } } // add inline styles if (this.attribute('style').hasValue()) { var styles = this.attribute('style').value.split(';'); for (var i=0; i<styles.length; i++) { if (svg.trim(styles[i]) != '') { var style = styles[i].split(':'); var name = svg.trim(style[0]); var value = svg.trim(style[1]); this.styles[name] = new svg.Property(name, value); } } } // add id if (this.attribute('id').hasValue()) { if (svg.Definitions[this.attribute('id').value] == null) { svg.Definitions[this.attribute('id').value] = this; } } } } svg.Element.RenderedElementBase = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.setContext = function(ctx) { // fill if (this.style('fill').Definition.isUrl()) { var fs = this.style('fill').Definition.getFillStyle(this); if (fs != null) ctx.fillStyle = fs; } else if (this.style('fill').hasValue()) { var fillStyle = this.style('fill'); if (this.style('fill-opacity').hasValue()) fillStyle = fillStyle.Color.addOpacity(this.style('fill-opacity').value); ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value); } // stroke if (this.style('stroke').Definition.isUrl()) { var fs = this.style('stroke').Definition.getFillStyle(this); if (fs != null) ctx.strokeStyle = fs; } else if (this.style('stroke').hasValue()) { var strokeStyle = this.style('stroke'); if (this.style('stroke-opacity').hasValue()) strokeStyle = strokeStyle.Color.addOpacity(this.style('stroke-opacity').value); ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value); } if (this.style('stroke-width').hasValue()) ctx.lineWidth = this.style('stroke-width').Length.toPixels(); if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value; if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value; if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value; // font if (typeof(ctx.font) != 'undefined') { ctx.font = svg.Font.CreateFont( this.style('font-style').value, this.style('font-variant').value, this.style('font-weight').value, this.style('font-size').hasValue() ? this.style('font-size').Length.toPixels() + 'px' : '', this.style('font-family').value).toString(); } // transform if (this.attribute('transform').hasValue()) { var transform = new svg.Transform(this.attribute('transform').value); transform.apply(ctx); } // clip if (this.attribute('clip-path').hasValue()) { var clip = this.attribute('clip-path').Definition.getDefinition(); if (clip != null) clip.apply(ctx); } // opacity if (this.style('opacity').hasValue()) { ctx.globalAlpha = this.style('opacity').numValue(); } } } svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase; svg.Element.PathElementBase = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.path = function(ctx) { if (ctx != null) ctx.beginPath(); return new svg.BoundingBox(); } this.renderChildren = function(ctx) { this.path(ctx); svg.Mouse.checkPath(this, ctx); if (ctx.fillStyle != '') ctx.fill(); if (ctx.strokeStyle != '') ctx.stroke(); var markers = this.getMarkers(); if (markers != null) { if (this.attribute('marker-start').Definition.isUrl()) { var marker = this.attribute('marker-start').Definition.getDefinition(); marker.render(ctx, markers[0][0], markers[0][1]); } if (this.attribute('marker-mid').Definition.isUrl()) { var marker = this.attribute('marker-mid').Definition.getDefinition(); for (var i=1;i<markers.length-1;i++) { marker.render(ctx, markers[i][0], markers[i][1]); } } if (this.attribute('marker-end').Definition.isUrl()) { var marker = this.attribute('marker-end').Definition.getDefinition(); marker.render(ctx, markers[markers.length-1][0], markers[markers.length-1][1]); } } } this.getBoundingBox = function() { return this.path(); } this.getMarkers = function() { return null; } } svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase; // svg element svg.Element.svg = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.baseClearContext = this.clearContext; this.clearContext = function(ctx) { this.baseClearContext(ctx); svg.ViewPort.RemoveCurrent(); } this.baseSetContext = this.setContext; this.setContext = function(ctx) { this.baseSetContext(ctx); // create new view port if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) { ctx.translate(this.attribute('x').Length.toPixels('x'), this.attribute('y').Length.toPixels('y')); } var width = svg.ViewPort.width(); var height = svg.ViewPort.height(); if (this.attribute('width').hasValue() && this.attribute('height').hasValue()) { width = this.attribute('width').Length.toPixels('x'); height = this.attribute('height').Length.toPixels('y'); var x = 0; var y = 0; if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) { x = -this.attribute('refX').Length.toPixels('x'); y = -this.attribute('refY').Length.toPixels('y'); } ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(width, y); ctx.lineTo(width, height); ctx.lineTo(x, height); ctx.closePath(); ctx.clip(); } svg.ViewPort.SetCurrent(width, height); // viewbox if (this.attribute('viewBox').hasValue()) { var viewBox = svg.ToNumberArray(this.attribute('viewBox').value); var minX = viewBox[0]; var minY = viewBox[1]; width = viewBox[2]; height = viewBox[3]; svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, svg.ViewPort.width(), width, svg.ViewPort.height(), height, minX, minY, this.attribute('refX').value, this.attribute('refY').value); svg.ViewPort.RemoveCurrent(); svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]); } // initial values ctx.strokeStyle = 'rgba(0,0,0,0)'; ctx.lineCap = 'butt'; ctx.lineJoin = 'miter'; ctx.miterLimit = 4; } } svg.Element.svg.prototype = new svg.Element.RenderedElementBase; // rect element svg.Element.rect = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.path = function(ctx) { var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); var width = this.attribute('width').Length.toPixels('x'); var height = this.attribute('height').Length.toPixels('y'); var rx = this.attribute('rx').Length.toPixels('x'); var ry = this.attribute('ry').Length.toPixels('y'); if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx; if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry; if (ctx != null) { ctx.beginPath(); ctx.moveTo(x + rx, y); ctx.lineTo(x + width - rx, y); ctx.quadraticCurveTo(x + width, y, x + width, y + ry) ctx.lineTo(x + width, y + height - ry); ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height) ctx.lineTo(x + rx, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - ry) ctx.lineTo(x, y + ry); ctx.quadraticCurveTo(x, y, x + rx, y) ctx.closePath(); } return new svg.BoundingBox(x, y, x + width, y + height); } } svg.Element.rect.prototype = new svg.Element.PathElementBase; // circle element svg.Element.circle = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.path = function(ctx) { var cx = this.attribute('cx').Length.toPixels('x'); var cy = this.attribute('cy').Length.toPixels('y'); var r = this.attribute('r').Length.toPixels(); if (ctx != null) { ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2, true); ctx.closePath(); } return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r); } } svg.Element.circle.prototype = new svg.Element.PathElementBase; // ellipse element svg.Element.ellipse = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.path = function(ctx) { var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3); var rx = this.attribute('rx').Length.toPixels('x'); var ry = this.attribute('ry').Length.toPixels('y'); var cx = this.attribute('cx').Length.toPixels('x'); var cy = this.attribute('cy').Length.toPixels('y'); if (ctx != null) { ctx.beginPath(); ctx.moveTo(cx, cy - ry); ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy); ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry); ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy); ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry); ctx.closePath(); } return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry); } } svg.Element.ellipse.prototype = new svg.Element.PathElementBase; // line element svg.Element.line = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.getPoints = function() { return [ new svg.Point(this.attribute('x1').Length.toPixels('x'), this.attribute('y1').Length.toPixels('y')), new svg.Point(this.attribute('x2').Length.toPixels('x'), this.attribute('y2').Length.toPixels('y'))]; } this.path = function(ctx) { var points = this.getPoints(); if (ctx != null) { ctx.beginPath(); ctx.moveTo(points[0].x, points[0].y); ctx.lineTo(points[1].x, points[1].y); } return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y); } this.getMarkers = function() { var points = this.getPoints(); var a = points[0].angleTo(points[1]); return [[points[0], a], [points[1], a]]; } } svg.Element.line.prototype = new svg.Element.PathElementBase; // polyline element svg.Element.polyline = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.points = svg.CreatePath(this.attribute('points').value); this.path = function(ctx) { var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y); if (ctx != null) { ctx.beginPath(); ctx.moveTo(this.points[0].x, this.points[0].y); } for (var i=1; i<this.points.length; i++) { bb.addPoint(this.points[i].x, this.points[i].y); if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y); } return bb; } this.getMarkers = function() { var markers = []; for (var i=0; i<this.points.length - 1; i++) { markers.push([this.points[i], this.points[i].angleTo(this.points[i+1])]); } markers.push([this.points[this.points.length-1], markers[markers.length-1][1]]); return markers; } } svg.Element.polyline.prototype = new svg.Element.PathElementBase; // polygon element svg.Element.polygon = function(node) { this.base = svg.Element.polyline; this.base(node); this.basePath = this.path; this.path = function(ctx) { var bb = this.basePath(ctx); if (ctx != null) { ctx.lineTo(this.points[0].x, this.points[0].y); ctx.closePath(); } return bb; } } svg.Element.polygon.prototype = new svg.Element.polyline; // path element svg.Element.path = function(node) { this.base = svg.Element.PathElementBase; this.base(node); var d = this.attribute('d').value; // TODO: floating points, convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF d = d.replace(/,/gm,' '); // get rid of all commas d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm,'$1 $2'); // separate commands from points d = d.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from points d = d.replace(/([0-9])([+\-])/gm,'$1 $2'); // separate digits when no comma d = d.replace(/(\.[0-9]*)(\.)/gm,'$1 $2'); // separate digits when no comma d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,'$1 $3 $4 '); // shorthand elliptical arc path syntax d = svg.compressSpaces(d); // compress multiple spaces d = svg.trim(d); this.PathParser = new (function(d) { this.tokens = d.split(' '); this.reset = function() { this.i = -1; this.command = ''; this.previousCommand = ''; this.start = new svg.Point(0, 0); this.control = new svg.Point(0, 0); this.current = new svg.Point(0, 0); this.points = []; this.angles = []; } this.isEnd = function() { return this.i >= this.tokens.length - 1; } this.isCommandOrEnd = function() { if (this.isEnd()) return true; return this.tokens[this.i + 1].match(/[A-Za-z]/) != null; } this.isRelativeCommand = function() { return this.command == this.command.toLowerCase(); } this.getToken = function() { this.i = this.i + 1; return this.tokens[this.i]; } this.getScalar = function() { return parseFloat(this.getToken()); } this.nextCommand = function() { this.previousCommand = this.command; this.command = this.getToken(); } this.getPoint = function() { var p = new svg.Point(this.getScalar(), this.getScalar()); return this.makeAbsolute(p); } this.getAsControlPoint = function() { var p = this.getPoint(); this.control = p; return p; } this.getAsCurrentPoint = function() { var p = this.getPoint(); this.current = p; return p; } this.getReflectedControlPoint = function() { if (this.previousCommand.toLowerCase() != 'c' && this.previousCommand.toLowerCase() != 's') { return this.current; } // reflect point var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y); return p; } this.makeAbsolute = function(p) { if (this.isRelativeCommand()) { p.x = this.current.x + p.x; p.y = this.current.y + p.y; } return p; } this.addMarker = function(p, from) { this.addMarkerAngle(p, from == null ? null : from.angleTo(p)); } this.addMarkerAngle = function(p, a) { this.points.push(p); this.angles.push(a); } this.getMarkerPoints = function() { return this.points; } this.getMarkerAngles = function() { for (var i=0; i<this.angles.length; i++) { if (this.angles[i] == null) { for (var j=i+1; j<this.angles.length; j++) { if (this.angles[j] != null) { this.angles[i] = this.angles[j]; break; } } } } return this.angles; } })(d); this.path = function(ctx) { var pp = this.PathParser; pp.reset(); var bb = new svg.BoundingBox(); if (ctx != null) ctx.beginPath(); while (!pp.isEnd()) { pp.nextCommand(); switch (pp.command.toUpperCase()) { case 'M': var p = pp.getAsCurrentPoint(); pp.addMarker(p); bb.addPoint(p.x, p.y); if (ctx != null) ctx.moveTo(p.x, p.y); pp.start = pp.current; while (!pp.isCommandOrEnd()) { var p = pp.getAsCurrentPoint(); pp.addMarker(p); bb.addPoint(p.x, p.y); if (ctx != null) ctx.lineTo(p.x, p.y); } break; case 'L': while (!pp.isCommandOrEnd()) { var c = pp.current; var p = pp.getAsCurrentPoint(); pp.addMarker(p, c); bb.addPoint(p.x, p.y); if (ctx != null) ctx.lineTo(p.x, p.y); } break; case 'H': while (!pp.isCommandOrEnd()) { var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y); pp.addMarker(newP, pp.current); pp.current = newP; bb.addPoint(pp.current.x, pp.current.y); if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y); } break; case 'V': while (!pp.isCommandOrEnd()) { var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar()); pp.addMarker(newP, pp.current); pp.current = newP; bb.addPoint(pp.current.x, pp.current.y); if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y); } break; case 'C': while (!pp.isCommandOrEnd()) { var curr = pp.current; var p1 = pp.getPoint(); var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl); bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'S': while (!pp.isCommandOrEnd()) { var curr = pp.current; var p1 = pp.getReflectedControlPoint(); var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl); bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'Q': while (!pp.isCommandOrEnd()) { var curr = pp.current; var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl); bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'T': while (!pp.isCommandOrEnd()) { var curr = pp.current; var cntrl = pp.getReflectedControlPoint(); pp.control = cntrl; var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl); bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'A': while (!pp.isCommandOrEnd()) { var curr = pp.current; var rx = pp.getScalar(); var ry = pp.getScalar(); var xAxisRotation = pp.getScalar() * (Math.PI / 180.0); var largeArcFlag = pp.getScalar(); var sweepFlag = pp.getScalar(); var cp = pp.getAsCurrentPoint(); // Conversion from endpoint to center parameterization // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes // x1', y1' var currp = new svg.Point( Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0, -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0 ); // adjust radii var l = Math.pow(currp.x,2)/Math.pow(rx,2)+Math.pow(currp.y,2)/Math.pow(ry,2); if (l > 1) { rx *= Math.sqrt(l); ry *= Math.sqrt(l); } // cx', cy' var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt( ((Math.pow(rx,2)*Math.pow(ry,2))-(Math.pow(rx,2)*Math.pow(currp.y,2))-(Math.pow(ry,2)*Math.pow(currp.x,2))) / (Math.pow(rx,2)*Math.pow(currp.y,2)+Math.pow(ry,2)*Math.pow(currp.x,2)) ); if (isNaN(s)) s = 0; var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx); // cx, cy var centp = new svg.Point( (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y, (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y ); // vector magnitude var m = function(v) { return Math.sqrt(Math.pow(v[0],2) + Math.pow(v[1],2)); } // ratio between two vectors var r = function(u, v) { return (u[0]*v[0]+u[1]*v[1]) / (m(u)*m(v)) } // angle between two vectors var a = function(u, v) { return (u[0]*v[1] < u[1]*v[0] ? -1 : 1) * Math.acos(r(u,v)); } // initial angle var a1 = a([1,0], [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]); // angle delta var u = [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]; var v = [(-currp.x-cpp.x)/rx,(-currp.y-cpp.y)/ry]; var ad = a(u, v); if (r(u,v) <= -1) ad = Math.PI; if (r(u,v) >= 1) ad = 0; if (sweepFlag == 0 && ad > 0) ad = ad - 2 * Math.PI; if (sweepFlag == 1 && ad < 0) ad = ad + 2 * Math.PI; // for markers var halfWay = new svg.Point( centp.x - rx * Math.cos((a1 + ad) / 2), centp.y - ry * Math.sin((a1 + ad) / 2) ); pp.addMarkerAngle(halfWay, (a1 + ad) / 2 + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2); pp.addMarkerAngle(cp, ad + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2); bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better if (ctx != null) { var r = rx > ry ? rx : ry; var sx = rx > ry ? 1 : rx / ry; var sy = rx > ry ? ry / rx : 1; ctx.translate(centp.x, centp.y); ctx.rotate(xAxisRotation); ctx.scale(sx, sy); ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag); ctx.scale(1/sx, 1/sy); ctx.rotate(-xAxisRotation); ctx.translate(-centp.x, -centp.y); } } break; case 'Z': if (ctx != null) ctx.closePath(); pp.current = pp.start; } } return bb; } this.getMarkers = function() { var points = this.PathParser.getMarkerPoints(); var angles = this.PathParser.getMarkerAngles(); var markers = []; for (var i=0; i<points.length; i++) { markers.push([points[i], angles[i]]); } return markers; } } svg.Element.path.prototype = new svg.Element.PathElementBase; // pattern element svg.Element.pattern = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.createPattern = function(ctx, element) { // render me using a temporary svg element var tempSvg = new svg.Element.svg(); tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value); tempSvg.attributes['x'] = new svg.Property('x', this.attribute('x').value); tempSvg.attributes['y'] = new svg.Property('y', this.attribute('y').value); tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value); tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value); tempSvg.children = this.children; var c = document.createElement('canvas'); c.width = this.attribute('width').Length.toPixels(); c.height = this.attribute('height').Length.toPixels(); tempSvg.render(c.getContext('2d')); return ctx.createPattern(c, 'repeat'); } } svg.Element.pattern.prototype = new svg.Element.ElementBase; // marker element svg.Element.marker = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.baseRender = this.render; this.render = function(ctx, point, angle) { ctx.translate(point.x, point.y); if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle); if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth); ctx.save(); // render me using a temporary svg element var tempSvg = new svg.Element.svg(); tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value); tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value); tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value); tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value); tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value); tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black')); tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none')); tempSvg.children = this.children; tempSvg.render(ctx); ctx.restore(); if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1/ctx.lineWidth, 1/ctx.lineWidth); if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle); ctx.translate(-point.x, -point.y); } } svg.Element.marker.prototype = new svg.Element.ElementBase; // definitions element svg.Element.defs = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.render = function(ctx) { // NOOP } } svg.Element.defs.prototype = new svg.Element.ElementBase; // base for gradients svg.Element.GradientBase = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.gradientUnits = this.attribute('gradientUnits').valueOrDefault('objectBoundingBox'); this.stops = []; for (var i=0; i<this.children.length; i++) { var child = this.children[i]; this.stops.push(child); } this.getGradient = function() { // OVERRIDE ME! } this.createGradient = function(ctx, element) { var stopsContainer = this; if (this.attribute('xlink:href').hasValue()) { stopsContainer = this.attribute('xlink:href').Definition.getDefinition(); } var g = this.getGradient(ctx, element); for (var i=0; i<stopsContainer.stops.length; i++) { g.addColorStop(stopsContainer.stops[i].offset, stopsContainer.stops[i].color); } return g; } } svg.Element.GradientBase.prototype = new svg.Element.ElementBase; // linear gradient element svg.Element.linearGradient = function(node) { this.base = svg.Element.GradientBase; this.base(node); this.getGradient = function(ctx, element) { var bb = element.getBoundingBox(); var x1 = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('x1').numValue() : this.attribute('x1').Length.toPixels('x')); var y1 = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('y1').numValue() : this.attribute('y1').Length.toPixels('y')); var x2 = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('x2').numValue() : this.attribute('x2').Length.toPixels('x')); var y2 = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('y2').numValue() : this.attribute('y2').Length.toPixels('y')); var p1 = new svg.Point(x1, y1); var p2 = new svg.Point(x2, y2); if (this.attribute('gradientTransform').hasValue()) { var transform = new svg.Transform(this.attribute('gradientTransform').value); transform.applyToPoint(p1); transform.applyToPoint(p2); } return ctx.createLinearGradient(p1.x, p1.y, p2.x, p2.y); } } svg.Element.linearGradient.prototype = new svg.Element.GradientBase; // radial gradient element svg.Element.radialGradient = function(node) { this.base = svg.Element.GradientBase; this.base(node); this.getGradient = function(ctx, element) { var bb = element.getBoundingBox(); var cx = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('cx').numValue() : this.attribute('cx').Length.toPixels('x')); var cy = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('cy').numValue() : this.attribute('cy').Length.toPixels('y')); var fx = cx; var fy = cy; if (this.attribute('fx').hasValue()) { fx = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('fx').numValue() : this.attribute('fx').Length.toPixels('x')); } if (this.attribute('fy').hasValue()) { fy = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('fy').numValue() : this.attribute('fy').Length.toPixels('y')); } var r = (this.gradientUnits == 'objectBoundingBox' ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue() : this.attribute('r').Length.toPixels()); var c = new svg.Point(cx, cy); var f = new svg.Point(fx, fy); if (this.attribute('gradientTransform').hasValue()) { var transform = new svg.Transform(this.attribute('gradientTransform').value); transform.applyToPoint(c); transform.applyToPoint(f); } return ctx.createRadialGradient(f.x, f.y, 0, c.x, c.y, r); } } svg.Element.radialGradient.prototype = new svg.Element.GradientBase; // gradient stop element svg.Element.stop = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.offset = this.attribute('offset').numValue(); var stopColor = this.style('stop-color'); if (this.style('stop-opacity').hasValue()) stopColor = stopColor.Color.addOpacity(this.style('stop-opacity').value); this.color = stopColor.value; } svg.Element.stop.prototype = new svg.Element.ElementBase; // animation base element svg.Element.AnimateBase = function(node) { this.base = svg.Element.ElementBase; this.base(node); svg.Animations.push(this); this.duration = 0.0; this.begin = this.attribute('begin').Time.toMilliseconds(); this.maxDuration = this.begin + this.attribute('dur').Time.toMilliseconds(); this.getProperty = function() { var attributeType = this.attribute('attributeType').value; var attributeName = this.attribute('attributeName').value; if (attributeType == 'CSS') { return this.parent.style(attributeName, true); } return this.parent.attribute(attributeName, true); }; this.initialValue = null; this.removed = false; this.calcValue = function() { // OVERRIDE ME! return ''; } this.update = function(delta) { // set initial value if (this.initialValue == null) { this.initialValue = this.getProperty().value; } // if we're past the end time if (this.duration > this.maxDuration) { // loop for indefinitely repeating animations if (this.attribute('repeatCount').value == 'indefinite') { this.duration = 0.0 } else if (this.attribute('fill').valueOrDefault('remove') == 'remove' && !this.removed) { this.removed = true; this.getProperty().value = this.initialValue; return true; } else { return false; // no updates made } } this.duration = this.duration + delta; // if we're past the begin time var updated = false; if (this.begin < this.duration) { var newValue = this.calcValue(); // tween if (this.attribute('type').hasValue()) { // for transform, etc. var type = this.attribute('type').value; newValue = type + '(' + newValue + ')'; } this.getProperty().value = newValue; updated = true; } return updated; } // fraction of duration we've covered this.progress = function() { return ((this.duration - this.begin) / (this.maxDuration - this.begin)); } } svg.Element.AnimateBase.prototype = new svg.Element.ElementBase; // animate element svg.Element.animate = function(node) { this.base = svg.Element.AnimateBase; this.base(node); this.calcValue = function() { var from = this.attribute('from').numValue(); var to = this.attribute('to').numValue(); // tween value linearly return from + (to - from) * this.progress(); }; } svg.Element.animate.prototype = new svg.Element.AnimateBase; // animate color element svg.Element.animateColor = function(node) { this.base = svg.Element.AnimateBase; this.base(node); this.calcValue = function() { var from = new RGBColor(this.attribute('from').value); var to = new RGBColor(this.attribute('to').value); if (from.ok && to.ok) { // tween color linearly var r = from.r + (to.r - from.r) * this.progress(); var g = from.g + (to.g - from.g) * this.progress(); var b = from.b + (to.b - from.b) * this.progress(); return 'rgb('+parseInt(r,10)+','+parseInt(g,10)+','+parseInt(b,10)+')'; } return this.attribute('from').value; }; } svg.Element.animateColor.prototype = new svg.Element.AnimateBase; // animate transform element svg.Element.animateTransform = function(node) { this.base = svg.Element.animate; this.base(node); } svg.Element.animateTransform.prototype = new svg.Element.animate; // text element svg.Element.text = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); if (node != null) { // add children this.children = []; for (var i=0; i<node.childNodes.length; i++) { var childNode = node.childNodes[i]; if (childNode.nodeType == 1) { // capture tspan and tref nodes this.addChild(childNode, true); } else if (childNode.nodeType == 3) { // capture text this.addChild(new svg.Element.tspan(childNode), false); } } } this.baseSetContext = this.setContext; this.setContext = function(ctx) { this.baseSetContext(ctx); if (this.attribute('text-anchor').hasValue()) { var textAnchor = this.attribute('text-anchor').value; ctx.textAlign = textAnchor == 'middle' ? 'center' : textAnchor; } if (this.attribute('alignment-baseline').hasValue()) ctx.textBaseline = this.attribute('alignment-baseline').value; } this.renderChildren = function(ctx) { var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); for (var i=0; i<this.children.length; i++) { var child = this.children[i]; if (child.attribute('x').hasValue()) { child.x = child.attribute('x').Length.toPixels('x'); } else { if (child.attribute('dx').hasValue()) x += child.attribute('dx').Length.toPixels('x'); child.x = x; x += child.measureText(ctx); } if (child.attribute('y').hasValue()) { child.y = child.attribute('y').Length.toPixels('y'); } else { if (child.attribute('dy').hasValue()) y += child.attribute('dy').Length.toPixels('y'); child.y = y; } child.render(ctx); } } } svg.Element.text.prototype = new svg.Element.RenderedElementBase; // text base svg.Element.TextElementBase = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.renderChildren = function(ctx) { ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y); } this.getText = function() { // OVERRIDE ME } this.measureText = function(ctx) { var textToMeasure = svg.compressSpaces(this.getText()); if (!ctx.measureText) return textToMeasure.length * 10; return ctx.measureText(textToMeasure).width; } } svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase; // tspan svg.Element.tspan = function(node) { this.base = svg.Element.TextElementBase; this.base(node); // TEXT ELEMENT this.text = node.nodeType == 3 ? node.nodeValue : node.childNodes[0].nodeValue; this.getText = function() { return this.text; } } svg.Element.tspan.prototype = new svg.Element.TextElementBase; // tref svg.Element.tref = function(node) { this.base = svg.Element.TextElementBase; this.base(node); this.getText = function() { var element = this.attribute('xlink:href').Definition.getDefinition(); if (element != null) return element.children[0].getText(); } } svg.Element.tref.prototype = new svg.Element.TextElementBase; // a element svg.Element.a = function(node) { this.base = svg.Element.TextElementBase; this.base(node); this.hasText = true; for (var i=0; i<node.childNodes.length; i++) { if (node.childNodes[i].nodeType != 3) this.hasText = false; } // this might contain text this.text = this.hasText ? node.childNodes[0].nodeValue : ''; this.getText = function() { return this.text; } this.baseRenderChildren = this.renderChildren; this.renderChildren = function(ctx) { if (this.hasText) { // render as text element this.baseRenderChildren(ctx); var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.Length.toPixels('y'), this.x + this.measureText(ctx), this.y)); } else { // render as temporary group var g = new svg.Element.g(); g.children = this.children; g.parent = this; g.render(ctx); } } this.onclick = function() { window.open(this.attribute('xlink:href').value); } this.onmousemove = function() { svg.ctx.canvas.style.cursor = 'pointer'; } } svg.Element.a.prototype = new svg.Element.TextElementBase; // image element svg.Element.image = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); svg.Images.push(this); this.img = document.createElement('img'); this.loaded = false; var that = this; this.img.onload = function() { that.loaded = true; } this.img.src = this.attribute('xlink:href').value; this.renderChildren = function(ctx) { var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); var width = this.attribute('width').Length.toPixels('x'); var height = this.attribute('height').Length.toPixels('y'); if (width == 0 || height == 0) return; ctx.save(); ctx.translate(x, y); svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, width, this.img.width, height, this.img.height, 0, 0); ctx.drawImage(this.img, 0, 0); ctx.restore(); } } svg.Element.image.prototype = new svg.Element.RenderedElementBase; // group element svg.Element.g = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.getBoundingBox = function() { var bb = new svg.BoundingBox(); for (var i=0; i<this.children.length; i++) { bb.addBoundingBox(this.children[i].getBoundingBox()); } return bb; }; } svg.Element.g.prototype = new svg.Element.RenderedElementBase; // symbol element svg.Element.symbol = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); } svg.Element.symbol.prototype = new svg.Element.RenderedElementBase; // style element svg.Element.style = function(node) { this.base = svg.Element.ElementBase; this.base(node); var css = node.childNodes[0].nodeValue; css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(\/\/.*)/gm, ''); // remove comments css = svg.compressSpaces(css); // replace whitespace var cssDefs = css.split('}'); for (var i=0; i<cssDefs.length; i++) { if (svg.trim(cssDefs[i]) != '') { var cssDef = cssDefs[i].split('{'); var cssClasses = cssDef[0].split(','); var cssProps = cssDef[1].split(';'); for (var j=0; j<cssClasses.length; j++) { var cssClass = svg.trim(cssClasses[j]); if (cssClass != '') { var props = {}; for (var k=0; k<cssProps.length; k++) { var prop = cssProps[k].split(':'); var name = prop[0]; var value = prop[1]; if (name != null && value != null) { props[svg.trim(prop[0])] = new svg.Property(svg.trim(prop[0]), svg.trim(prop[1])); } } svg.Styles[cssClass] = props; } } } } } svg.Element.style.prototype = new svg.Element.ElementBase; // use element svg.Element.use = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.baseSetContext = this.setContext; this.setContext = function(ctx) { this.baseSetContext(ctx); if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').Length.toPixels('x'), 0); if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').Length.toPixels('y')); } this.getDefinition = function() { return this.attribute('xlink:href').Definition.getDefinition(); } this.path = function(ctx) { var element = this.getDefinition(); if (element != null) element.path(ctx); } this.renderChildren = function(ctx) { var element = this.getDefinition(); if (element != null) element.render(ctx); } } svg.Element.use.prototype = new svg.Element.RenderedElementBase; // clip element svg.Element.clipPath = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.apply = function(ctx) { for (var i=0; i<this.children.length; i++) { if (this.children[i].path) { this.children[i].path(ctx); ctx.clip(); } } } } svg.Element.clipPath.prototype = new svg.Element.ElementBase; // title element, do nothing svg.Element.title = function(node) { } svg.Element.title.prototype = new svg.Element.ElementBase; // desc element, do nothing svg.Element.desc = function(node) { } svg.Element.desc.prototype = new svg.Element.ElementBase; svg.Element.MISSING = function(node) { console.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.'); } svg.Element.MISSING.prototype = new svg.Element.ElementBase; // element factory svg.CreateElement = function(node) { var className = 'svg.Element.' + node.nodeName.replace(/^[^:]+:/,''); if (!eval(className)) className = 'svg.Element.MISSING'; var e = eval('new ' + className + '(node)'); e.type = node.nodeName; return e; } // load from url svg.load = function(ctx, url) { svg.loadXml(ctx, svg.ajax(url)); } // load from xml svg.loadXml = function(ctx, xml) { svg.init(ctx); var mapXY = function(p) { var e = ctx.canvas; while (e) { p.x -= e.offsetLeft; p.y -= e.offsetTop; e = e.offsetParent; } if (window.scrollX) p.x += window.scrollX; if (window.scrollY) p.y += window.scrollY; return p; } // bind mouse if (svg.opts == null || svg.opts['ignoreMouse'] != true) { ctx.canvas.onclick = function(e) { var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY)); svg.Mouse.onclick(p.x, p.y); }; ctx.canvas.onmousemove = function(e) { var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY)); svg.Mouse.onmousemove(p.x, p.y); }; } var dom = svg.parseXml(xml); var e = svg.CreateElement(dom.documentElement); // render loop var isFirstRender = true; var draw = function() { if (svg.opts == null || svg.opts['ignoreDimensions'] != true) { // set canvas size if (e.style('width').hasValue()) { ctx.canvas.width = e.style('width').Length.toPixels(ctx.canvas.parentNode.clientWidth); } if (e.style('height').hasValue()) { ctx.canvas.height = e.style('height').Length.toPixels(ctx.canvas.parentNode.clientHeight); } } svg.ViewPort.SetCurrent(ctx.canvas.clientWidth, ctx.canvas.clientHeight); if (svg.opts != null && svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX']; if (svg.opts != null && svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY']; if (svg.opts != null && svg.opts['scaleWidth'] != null && svg.opts['scaleHeight'] != null) { e.attribute('width', true).value = svg.opts['scaleWidth']; e.attribute('height', true).value = svg.opts['scaleHeight']; // REMOVED FOR android-ui-utils // e.attribute('viewBox', true).value = '0 0 ' + ctx.canvas.clientWidth + ' ' + ctx.canvas.clientHeight; e.attribute('preserveAspectRatio', true).value = 'none'; } // clear and render if (svg.opts == null || svg.opts['ignoreClear'] != true) { ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight); } e.render(ctx); if (isFirstRender) { isFirstRender = false; if (svg.opts != null && typeof(svg.opts['renderCallback']) == 'function') svg.opts['renderCallback'](); } } var waitingForImages = true; if (svg.ImagesLoaded()) { waitingForImages = false; draw(); } svg.intervalID = setInterval(function() { var needUpdate = false; if (waitingForImages && svg.ImagesLoaded()) { waitingForImages = false; needUpdate = true; } // need update from mouse events? if (svg.opts == null || svg.opts['ignoreMouse'] != true) { needUpdate = needUpdate | svg.Mouse.hasEvents(); } // need update from animations? if (svg.opts == null || svg.opts['ignoreAnimation'] != true) { for (var i=0; i<svg.Animations.length; i++) { needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE); } } // need update from redraw? if (svg.opts != null && typeof(svg.opts['forceRedraw']) == 'function') { if (svg.opts['forceRedraw']() == true) needUpdate = true; } // render if needed if (needUpdate) { draw(); svg.Mouse.runEvents(); // run and clear our events } }, 1000 / svg.FRAMERATE); } svg.stop = function() { if (svg.intervalID) { clearInterval(svg.intervalID); } } svg.Mouse = new (function() { this.events = []; this.hasEvents = function() { return this.events.length != 0; } this.onclick = function(x, y) { this.events.push({ type: 'onclick', x: x, y: y, run: function(e) { if (e.onclick) e.onclick(); } }); } this.onmousemove = function(x, y) { this.events.push({ type: 'onmousemove', x: x, y: y, run: function(e) { if (e.onmousemove) e.onmousemove(); } }); } this.eventElements = []; this.checkPath = function(element, ctx) { for (var i=0; i<this.events.length; i++) { var e = this.events[i]; if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element; } } this.checkBoundingBox = function(element, bb) { for (var i=0; i<this.events.length; i++) { var e = this.events[i]; if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element; } } this.runEvents = function() { svg.ctx.canvas.style.cursor = ''; for (var i=0; i<this.events.length; i++) { var e = this.events[i]; var element = this.eventElements[i]; while (element) { e.run(element); element = element.parent; } } // done running, clear this.events = []; this.eventElements = []; } }); return svg; } })(); if (CanvasRenderingContext2D) { CanvasRenderingContext2D.prototype.drawSvg = function(s, dx, dy, dw, dh) { canvg(this.canvas, s, { ignoreMouse: true, ignoreAnimation: true, ignoreDimensions: true, ignoreClear: true, offsetX: dx, offsetY: dy, scaleWidth: dw, scaleHeight: dh }); } }
JavaScript
/** JSZip - A Javascript class for generating Zip files <http://jszip.stuartk.co.uk> (c) 2009 Stuart Knightley <stuart [at] stuartk.co.uk> Licenced under the GPLv3 and the MIT licences Usage: zip = new JSZip(); zip.add("hello.txt", "Hello, World!").add("tempfile", "nothing"); zip.folder("images").add("smile.gif", base64Data, {base64: true}); zip.add("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")}); zip.remove("tempfile"); base64zip = zip.generate(); **/ function JSZip(compression) { // default : no compression this.compression = (compression || "STORE").toUpperCase(); this.files = []; // Where we are in the hierarchy this.root = ""; // Default properties for a new file this.d = { base64: false, binary: false, dir: false, date: null }; if (!JSZip.compressions[this.compression]) { throw compression + " is not a valid compression method !"; } } /** * Add a file to the zip file * @param name The name of the file * @param data The file data, either raw or base64 encoded * @param o File options * @return this JSZip object */ JSZip.prototype.add = function(name, data, o) { o = o || {}; name = this.root+name; if (o.base64 === true && o.binary == null) o.binary = true; for (var opt in this.d) { o[opt] = o[opt] || this.d[opt]; } // date // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html o.date = o.date || new Date(); var dosTime, dosDate; dosTime = o.date.getHours(); dosTime = dosTime << 6; dosTime = dosTime | o.date.getMinutes(); dosTime = dosTime << 5; dosTime = dosTime | o.date.getSeconds() / 2; dosDate = o.date.getFullYear() - 1980; dosDate = dosDate << 4; dosDate = dosDate | (o.date.getMonth() + 1); dosDate = dosDate << 5; dosDate = dosDate | o.date.getDate(); if (o.base64 === true) data = JSZipBase64.decode(data); // decode UTF-8 strings if we are dealing with text data if(o.binary === false) data = this.utf8encode(data); var compression = JSZip.compressions[this.compression]; var compressedData = compression.compress(data); var header = ""; // version needed to extract header += "\x0A\x00"; // general purpose bit flag header += "\x00\x00"; // compression method header += compression.magic; // last mod file time header += this.decToHex(dosTime, 2); // last mod file date header += this.decToHex(dosDate, 2); // crc-32 header += this.decToHex(this.crc32(data), 4); // compressed size header += this.decToHex(compressedData.length, 4); // uncompressed size header += this.decToHex(data.length, 4); // file name length header += this.decToHex(name.length, 2); // extra field length header += "\x00\x00"; // file name this.files[name] = {header: header, data: compressedData, dir: o.dir}; return this; }; /** * Add a directory to the zip file * @param name The name of the directory to add * @return JSZip object with the new directory as the root */ JSZip.prototype.folder = function(name) { // Check the name ends with a / if (name.substr(-1) != "/") name += "/"; // Does this folder already exist? if (typeof this.files[name] === "undefined") this.add(name, '', {dir:true}); // Allow chaining by returning a new object with this folder as the root var ret = this.clone(); ret.root = this.root+name; return ret; }; /** * Compare a string or regular expression against all of the filenames and * return an informational object for each that matches. * @param string/regex The regular expression to test against * @return An array of objects representing the matched files. In the form * {name: "filename", data: "file data", dir: true/false} */ JSZip.prototype.find = function(needle) { var result = [], re; if (typeof needle === "string") { re = new RegExp("^"+needle+"$"); } else { re = needle; } for (var filename in this.files) { if (re.test(filename)) { var file = this.files[filename]; result.push({name: filename, data: file.data, dir: !!file.dir}); } } return result; }; /** * Delete a file, or a directory and all sub-files, from the zip * @param name the name of the file to delete * @return this JSZip object */ JSZip.prototype.remove = function(name) { var file = this.files[name]; if (!file) { // Look for any folders if (name.substr(-1) != "/") name += "/"; file = this.files[name]; } if (file) { if (name.match("/") === null) { // file delete this.files[name]; } else { // folder var kids = this.find(new RegExp("^"+name)); for (var i = 0; i < kids.length; i++) { if (kids[i].name == name) { // Delete this folder delete this.files[name]; } else { // Remove a child of this folder this.remove(kids[i].name); } } } } return this; }; /** * Generate the complete zip file * @return A base64 encoded string of the zip file */ JSZip.prototype.generate = function(asBytes) { asBytes = asBytes || false; // The central directory, and files data var directory = [], files = [], fileOffset = 0; for (var name in this.files) { if( !this.files.hasOwnProperty(name) ) { continue; } var fileRecord = "", dirRecord = ""; fileRecord = "\x50\x4b\x03\x04" + this.files[name].header + name + this.files[name].data; dirRecord = "\x50\x4b\x01\x02" + // version made by (00: DOS) "\x14\x00" + // file header (common to file and central directory) this.files[name].header + // file comment length "\x00\x00" + // disk number start "\x00\x00" + // internal file attributes TODO "\x00\x00" + // external file attributes (this.files[name].dir===true?"\x10\x00\x00\x00":"\x00\x00\x00\x00")+ // relative offset of local header this.decToHex(fileOffset, 4) + // file name name; fileOffset += fileRecord.length; files.push(fileRecord); directory.push(dirRecord); } var fileData = files.join(""); var dirData = directory.join(""); var dirEnd = ""; // end of central dir signature dirEnd = "\x50\x4b\x05\x06" + // number of this disk "\x00\x00" + // number of the disk with the start of the central directory "\x00\x00" + // total number of entries in the central directory on this disk this.decToHex(files.length, 2) + // total number of entries in the central directory this.decToHex(files.length, 2) + // size of the central directory 4 bytes this.decToHex(dirData.length, 4) + // offset of start of central directory with respect to the starting disk number this.decToHex(fileData.length, 4) + // .ZIP file comment length "\x00\x00"; var zip = fileData + dirData + dirEnd; return (asBytes) ? zip : JSZipBase64.encode(zip); }; /* * Compression methods * This object is filled in as follow : * name : { * magic // the 2 bytes indentifying the compression method * compress // function, take the uncompressed content and return it compressed. * } * * STORE is the default compression method, so it's included in this file. * Other methods should go to separated files : the user wants modularity. */ JSZip.compressions = { "STORE" : { magic : "\x00\x00", compress : function (content) { return content; // no compression } } }; // Utility functions JSZip.prototype.decToHex = function(dec, bytes) { var hex = ""; for(var i=0;i<bytes;i++) { hex += String.fromCharCode(dec&0xff); dec=dec>>>8; } return hex; }; /** * * Javascript crc32 * http://www.webtoolkit.info/ * **/ JSZip.prototype.crc32 = function(str, crc) { if (str === "") return "\x00\x00\x00\x00"; var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D"; if (typeof(crc) == "undefined") { crc = 0; } var x = 0; var y = 0; crc = crc ^ (-1); for( var i = 0, iTop = str.length; i < iTop; i++ ) { y = ( crc ^ str.charCodeAt( i ) ) & 0xFF; x = "0x" + table.substr( y * 9, 8 ); crc = ( crc >>> 8 ) ^ x; } return crc ^ (-1); }; // Inspired by http://my.opera.com/GreyWyvern/blog/show.dml/1725165 JSZip.prototype.clone = function() { var newObj = new JSZip(); for (var i in this) { if (typeof this[i] !== "function") { newObj[i] = this[i]; } } return newObj; }; JSZip.prototype.utf8encode = function(input) { input = encodeURIComponent(input); input = input.replace(/%.{2,2}/g, function(m) { var hex = m.substring(1); return String.fromCharCode(parseInt(hex,16)); }); return input; }; /** * * Base64 encode / decode * http://www.webtoolkit.info/ * * Hacked so that it doesn't utf8 en/decode everything **/ var JSZipBase64 = function() { // private property var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; return { // public method for encoding encode : function(input, utf8) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4); } return output; }, // public method for decoding decode : function(input, utf8) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = _keyStr.indexOf(input.charAt(i++)); enc2 = _keyStr.indexOf(input.charAt(i++)); enc3 = _keyStr.indexOf(input.charAt(i++)); enc4 = _keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } return output; } }; }();
JavaScript
/* * Port of a script by Masanao Izumo. * * Only changes : wrap all the variables in a function and add the * main function to JSZip (DEFLATE compression method). * Everything else was written by M. Izumo. * * Original code can be found here: http://www.onicos.com/staff/iz/amuse/javascript/expert/inflate.txt */ if(!JSZip) { throw "JSZip not defined"; } /* * Original: * http://www.onicos.com/staff/iz/amuse/javascript/expert/deflate.txt */ (function(){ /* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp> * Version: 1.0.1 * LastModified: Dec 25 1999 */ /* Interface: * data = zip_deflate(src); */ /* constant parameters */ var zip_WSIZE = 32768; // Sliding Window size var zip_STORED_BLOCK = 0; var zip_STATIC_TREES = 1; var zip_DYN_TREES = 2; /* for deflate */ var zip_DEFAULT_LEVEL = 6; var zip_FULL_SEARCH = true; var zip_INBUFSIZ = 32768; // Input buffer size var zip_INBUF_EXTRA = 64; // Extra buffer var zip_OUTBUFSIZ = 1024 * 8; var zip_window_size = 2 * zip_WSIZE; var zip_MIN_MATCH = 3; var zip_MAX_MATCH = 258; var zip_BITS = 16; // for SMALL_MEM var zip_LIT_BUFSIZE = 0x2000; var zip_HASH_BITS = 13; // for MEDIUM_MEM // var zip_LIT_BUFSIZE = 0x4000; // var zip_HASH_BITS = 14; // for BIG_MEM // var zip_LIT_BUFSIZE = 0x8000; // var zip_HASH_BITS = 15; if(zip_LIT_BUFSIZE > zip_INBUFSIZ) alert("error: zip_INBUFSIZ is too small"); if((zip_WSIZE<<1) > (1<<zip_BITS)) alert("error: zip_WSIZE is too large"); if(zip_HASH_BITS > zip_BITS-1) alert("error: zip_HASH_BITS is too large"); if(zip_HASH_BITS < 8 || zip_MAX_MATCH != 258) alert("error: Code too clever"); var zip_DIST_BUFSIZE = zip_LIT_BUFSIZE; var zip_HASH_SIZE = 1 << zip_HASH_BITS; var zip_HASH_MASK = zip_HASH_SIZE - 1; var zip_WMASK = zip_WSIZE - 1; var zip_NIL = 0; // Tail of hash chains var zip_TOO_FAR = 4096; var zip_MIN_LOOKAHEAD = zip_MAX_MATCH + zip_MIN_MATCH + 1; var zip_MAX_DIST = zip_WSIZE - zip_MIN_LOOKAHEAD; var zip_SMALLEST = 1; var zip_MAX_BITS = 15; var zip_MAX_BL_BITS = 7; var zip_LENGTH_CODES = 29; var zip_LITERALS =256; var zip_END_BLOCK = 256; var zip_L_CODES = zip_LITERALS + 1 + zip_LENGTH_CODES; var zip_D_CODES = 30; var zip_BL_CODES = 19; var zip_REP_3_6 = 16; var zip_REPZ_3_10 = 17; var zip_REPZ_11_138 = 18; var zip_HEAP_SIZE = 2 * zip_L_CODES + 1; var zip_H_SHIFT = parseInt((zip_HASH_BITS + zip_MIN_MATCH - 1) / zip_MIN_MATCH); /* variables */ var zip_free_queue; var zip_qhead, zip_qtail; var zip_initflag; var zip_outbuf = null; var zip_outcnt, zip_outoff; var zip_complete; var zip_window; var zip_d_buf; var zip_l_buf; var zip_prev; var zip_bi_buf; var zip_bi_valid; var zip_block_start; var zip_ins_h; var zip_hash_head; var zip_prev_match; var zip_match_available; var zip_match_length; var zip_prev_length; var zip_strstart; var zip_match_start; var zip_eofile; var zip_lookahead; var zip_max_chain_length; var zip_max_lazy_match; var zip_compr_level; var zip_good_match; var zip_nice_match; var zip_dyn_ltree; var zip_dyn_dtree; var zip_static_ltree; var zip_static_dtree; var zip_bl_tree; var zip_l_desc; var zip_d_desc; var zip_bl_desc; var zip_bl_count; var zip_heap; var zip_heap_len; var zip_heap_max; var zip_depth; var zip_length_code; var zip_dist_code; var zip_base_length; var zip_base_dist; var zip_flag_buf; var zip_last_lit; var zip_last_dist; var zip_last_flags; var zip_flags; var zip_flag_bit; var zip_opt_len; var zip_static_len; var zip_deflate_data; var zip_deflate_pos; /* objects (deflate) */ var zip_DeflateCT = function() { this.fc = 0; // frequency count or bit string this.dl = 0; // father node in Huffman tree or length of bit string } var zip_DeflateTreeDesc = function() { this.dyn_tree = null; // the dynamic tree this.static_tree = null; // corresponding static tree or NULL this.extra_bits = null; // extra bits for each code or NULL this.extra_base = 0; // base index for extra_bits this.elems = 0; // max number of elements in the tree this.max_length = 0; // max bit length for the codes this.max_code = 0; // largest code with non zero frequency } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ var zip_DeflateConfiguration = function(a, b, c, d) { this.good_length = a; // reduce lazy search above this match length this.max_lazy = b; // do not perform lazy search above this match length this.nice_length = c; // quit search above this match length this.max_chain = d; } var zip_DeflateBuffer = function() { this.next = null; this.len = 0; this.ptr = new Array(zip_OUTBUFSIZ); this.off = 0; } /* constant tables */ var zip_extra_lbits = new Array( 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0); var zip_extra_dbits = new Array( 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13); var zip_extra_blbits = new Array( 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7); var zip_bl_order = new Array( 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15); var zip_configuration_table = new Array( new zip_DeflateConfiguration(0, 0, 0, 0), new zip_DeflateConfiguration(4, 4, 8, 4), new zip_DeflateConfiguration(4, 5, 16, 8), new zip_DeflateConfiguration(4, 6, 32, 32), new zip_DeflateConfiguration(4, 4, 16, 16), new zip_DeflateConfiguration(8, 16, 32, 32), new zip_DeflateConfiguration(8, 16, 128, 128), new zip_DeflateConfiguration(8, 32, 128, 256), new zip_DeflateConfiguration(32, 128, 258, 1024), new zip_DeflateConfiguration(32, 258, 258, 4096)); /* routines (deflate) */ var zip_deflate_start = function(level) { var i; if(!level) level = zip_DEFAULT_LEVEL; else if(level < 1) level = 1; else if(level > 9) level = 9; zip_compr_level = level; zip_initflag = false; zip_eofile = false; if(zip_outbuf != null) return; zip_free_queue = zip_qhead = zip_qtail = null; zip_outbuf = new Array(zip_OUTBUFSIZ); zip_window = new Array(zip_window_size); zip_d_buf = new Array(zip_DIST_BUFSIZE); zip_l_buf = new Array(zip_INBUFSIZ + zip_INBUF_EXTRA); zip_prev = new Array(1 << zip_BITS); zip_dyn_ltree = new Array(zip_HEAP_SIZE); for(i = 0; i < zip_HEAP_SIZE; i++) zip_dyn_ltree[i] = new zip_DeflateCT(); zip_dyn_dtree = new Array(2*zip_D_CODES+1); for(i = 0; i < 2*zip_D_CODES+1; i++) zip_dyn_dtree[i] = new zip_DeflateCT(); zip_static_ltree = new Array(zip_L_CODES+2); for(i = 0; i < zip_L_CODES+2; i++) zip_static_ltree[i] = new zip_DeflateCT(); zip_static_dtree = new Array(zip_D_CODES); for(i = 0; i < zip_D_CODES; i++) zip_static_dtree[i] = new zip_DeflateCT(); zip_bl_tree = new Array(2*zip_BL_CODES+1); for(i = 0; i < 2*zip_BL_CODES+1; i++) zip_bl_tree[i] = new zip_DeflateCT(); zip_l_desc = new zip_DeflateTreeDesc(); zip_d_desc = new zip_DeflateTreeDesc(); zip_bl_desc = new zip_DeflateTreeDesc(); zip_bl_count = new Array(zip_MAX_BITS+1); zip_heap = new Array(2*zip_L_CODES+1); zip_depth = new Array(2*zip_L_CODES+1); zip_length_code = new Array(zip_MAX_MATCH-zip_MIN_MATCH+1); zip_dist_code = new Array(512); zip_base_length = new Array(zip_LENGTH_CODES); zip_base_dist = new Array(zip_D_CODES); zip_flag_buf = new Array(parseInt(zip_LIT_BUFSIZE / 8)); } var zip_deflate_end = function() { zip_free_queue = zip_qhead = zip_qtail = null; zip_outbuf = null; zip_window = null; zip_d_buf = null; zip_l_buf = null; zip_prev = null; zip_dyn_ltree = null; zip_dyn_dtree = null; zip_static_ltree = null; zip_static_dtree = null; zip_bl_tree = null; zip_l_desc = null; zip_d_desc = null; zip_bl_desc = null; zip_bl_count = null; zip_heap = null; zip_depth = null; zip_length_code = null; zip_dist_code = null; zip_base_length = null; zip_base_dist = null; zip_flag_buf = null; } var zip_reuse_queue = function(p) { p.next = zip_free_queue; zip_free_queue = p; } var zip_new_queue = function() { var p; if(zip_free_queue != null) { p = zip_free_queue; zip_free_queue = zip_free_queue.next; } else p = new zip_DeflateBuffer(); p.next = null; p.len = p.off = 0; return p; } var zip_head1 = function(i) { return zip_prev[zip_WSIZE + i]; } var zip_head2 = function(i, val) { return zip_prev[zip_WSIZE + i] = val; } /* put_byte is used for the compressed output, put_ubyte for the * uncompressed output. However unlzw() uses window for its * suffix table instead of its output buffer, so it does not use put_ubyte * (to be cleaned up). */ var zip_put_byte = function(c) { zip_outbuf[zip_outoff + zip_outcnt++] = c; if(zip_outoff + zip_outcnt == zip_OUTBUFSIZ) zip_qoutbuf(); } /* Output a 16 bit value, lsb first */ var zip_put_short = function(w) { w &= 0xffff; if(zip_outoff + zip_outcnt < zip_OUTBUFSIZ - 2) { zip_outbuf[zip_outoff + zip_outcnt++] = (w & 0xff); zip_outbuf[zip_outoff + zip_outcnt++] = (w >>> 8); } else { zip_put_byte(w & 0xff); zip_put_byte(w >>> 8); } } /* ========================================================================== * Insert string s in the dictionary and set match_head to the previous head * of the hash chain (the most recent string with same hash key). Return * the previous length of the hash chain. * IN assertion: all calls to to INSERT_STRING are made with consecutive * input characters and the first MIN_MATCH bytes of s are valid * (except for the last MIN_MATCH-1 bytes of the input file). */ var zip_INSERT_STRING = function() { zip_ins_h = ((zip_ins_h << zip_H_SHIFT) ^ (zip_window[zip_strstart + zip_MIN_MATCH - 1] & 0xff)) & zip_HASH_MASK; zip_hash_head = zip_head1(zip_ins_h); zip_prev[zip_strstart & zip_WMASK] = zip_hash_head; zip_head2(zip_ins_h, zip_strstart); } /* Send a code of the given tree. c and tree must not have side effects */ var zip_SEND_CODE = function(c, tree) { zip_send_bits(tree[c].fc, tree[c].dl); } /* Mapping from a distance to a distance code. dist is the distance - 1 and * must not have side effects. dist_code[256] and dist_code[257] are never * used. */ var zip_D_CODE = function(dist) { return (dist < 256 ? zip_dist_code[dist] : zip_dist_code[256 + (dist>>7)]) & 0xff; } /* ========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ var zip_SMALLER = function(tree, n, m) { return tree[n].fc < tree[m].fc || (tree[n].fc == tree[m].fc && zip_depth[n] <= zip_depth[m]); } /* ========================================================================== * read string data */ var zip_read_buff = function(buff, offset, n) { var i; for(i = 0; i < n && zip_deflate_pos < zip_deflate_data.length; i++) buff[offset + i] = zip_deflate_data.charCodeAt(zip_deflate_pos++) & 0xff; return i; } /* ========================================================================== * Initialize the "longest match" routines for a new file */ var zip_lm_init = function() { var j; /* Initialize the hash table. */ for(j = 0; j < zip_HASH_SIZE; j++) // zip_head2(j, zip_NIL); zip_prev[zip_WSIZE + j] = 0; /* prev will be initialized on the fly */ /* Set the default configuration parameters: */ zip_max_lazy_match = zip_configuration_table[zip_compr_level].max_lazy; zip_good_match = zip_configuration_table[zip_compr_level].good_length; if(!zip_FULL_SEARCH) zip_nice_match = zip_configuration_table[zip_compr_level].nice_length; zip_max_chain_length = zip_configuration_table[zip_compr_level].max_chain; zip_strstart = 0; zip_block_start = 0; zip_lookahead = zip_read_buff(zip_window, 0, 2 * zip_WSIZE); if(zip_lookahead <= 0) { zip_eofile = true; zip_lookahead = 0; return; } zip_eofile = false; /* Make sure that we always have enough lookahead. This is important * if input comes from a device such as a tty. */ while(zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile) zip_fill_window(); /* If lookahead < MIN_MATCH, ins_h is garbage, but this is * not important since only literal bytes will be emitted. */ zip_ins_h = 0; for(j = 0; j < zip_MIN_MATCH - 1; j++) { // UPDATE_HASH(ins_h, window[j]); zip_ins_h = ((zip_ins_h << zip_H_SHIFT) ^ (zip_window[j] & 0xff)) & zip_HASH_MASK; } } /* ========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 */ var zip_longest_match = function(cur_match) { var chain_length = zip_max_chain_length; // max hash chain length var scanp = zip_strstart; // current string var matchp; // matched string var len; // length of current match var best_len = zip_prev_length; // best match length so far /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var limit = (zip_strstart > zip_MAX_DIST ? zip_strstart - zip_MAX_DIST : zip_NIL); var strendp = zip_strstart + zip_MAX_MATCH; var scan_end1 = zip_window[scanp + best_len - 1]; var scan_end = zip_window[scanp + best_len]; /* Do not waste too much time if we already have a good match: */ if(zip_prev_length >= zip_good_match) chain_length >>= 2; // Assert(encoder->strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead"); do { // Assert(cur_match < encoder->strstart, "no future"); matchp = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2: */ if(zip_window[matchp + best_len] != scan_end || zip_window[matchp + best_len - 1] != scan_end1 || zip_window[matchp] != zip_window[scanp] || zip_window[++matchp] != zip_window[scanp + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scanp += 2; matchp++; /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { } while(zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && scanp < strendp); len = zip_MAX_MATCH - (strendp - scanp); scanp = strendp - zip_MAX_MATCH; if(len > best_len) { zip_match_start = cur_match; best_len = len; if(zip_FULL_SEARCH) { if(len >= zip_MAX_MATCH) break; } else { if(len >= zip_nice_match) break; } scan_end1 = zip_window[scanp + best_len-1]; scan_end = zip_window[scanp + best_len]; } } while((cur_match = zip_prev[cur_match & zip_WMASK]) > limit && --chain_length != 0); return best_len; } /* ========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead, and sets eofile if end of input file. * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0 * OUT assertions: at least one byte has been read, or eofile is set; * file reads are performed for at least two bytes (required for the * translate_eol option). */ var zip_fill_window = function() { var n, m; // Amount of free space at the end of the window. var more = zip_window_size - zip_lookahead - zip_strstart; /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if(more == -1) { /* Very unlikely, but possible on 16 bit machine if strstart == 0 * and lookahead == 1 (input done one byte at time) */ more--; } else if(zip_strstart >= zip_WSIZE + zip_MAX_DIST) { /* By the IN assertion, the window is not empty so we can't confuse * more == 0 with more == 64K on a 16 bit machine. */ // Assert(window_size == (ulg)2*WSIZE, "no sliding with BIG_MEM"); // System.arraycopy(window, WSIZE, window, 0, WSIZE); for(n = 0; n < zip_WSIZE; n++) zip_window[n] = zip_window[n + zip_WSIZE]; zip_match_start -= zip_WSIZE; zip_strstart -= zip_WSIZE; /* we now have strstart >= MAX_DIST: */ zip_block_start -= zip_WSIZE; for(n = 0; n < zip_HASH_SIZE; n++) { m = zip_head1(n); zip_head2(n, m >= zip_WSIZE ? m - zip_WSIZE : zip_NIL); } for(n = 0; n < zip_WSIZE; n++) { /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ m = zip_prev[n]; zip_prev[n] = (m >= zip_WSIZE ? m - zip_WSIZE : zip_NIL); } more += zip_WSIZE; } // At this point, more >= 2 if(!zip_eofile) { n = zip_read_buff(zip_window, zip_strstart + zip_lookahead, more); if(n <= 0) zip_eofile = true; else zip_lookahead += n; } } /* ========================================================================== * Processes a new input file and return its compressed length. This * function does not perform lazy evaluationof matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ var zip_deflate_fast = function() { while(zip_lookahead != 0 && zip_qhead == null) { var flush; // set if current block must be flushed /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ zip_INSERT_STRING(); /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if(zip_hash_head != zip_NIL && zip_strstart - zip_hash_head <= zip_MAX_DIST) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ zip_match_length = zip_longest_match(zip_hash_head); /* longest_match() sets match_start */ if(zip_match_length > zip_lookahead) zip_match_length = zip_lookahead; } if(zip_match_length >= zip_MIN_MATCH) { // check_match(strstart, match_start, match_length); flush = zip_ct_tally(zip_strstart - zip_match_start, zip_match_length - zip_MIN_MATCH); zip_lookahead -= zip_match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if(zip_match_length <= zip_max_lazy_match) { zip_match_length--; // string at strstart already in hash table do { zip_strstart++; zip_INSERT_STRING(); /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH * these bytes are garbage, but it does not matter since * the next lookahead bytes will be emitted as literals. */ } while(--zip_match_length != 0); zip_strstart++; } else { zip_strstart += zip_match_length; zip_match_length = 0; zip_ins_h = zip_window[zip_strstart] & 0xff; // UPDATE_HASH(ins_h, window[strstart + 1]); zip_ins_h = ((zip_ins_h<<zip_H_SHIFT) ^ (zip_window[zip_strstart + 1] & 0xff)) & zip_HASH_MASK; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif } } else { /* No match, output a literal byte */ flush = zip_ct_tally(0, zip_window[zip_strstart] & 0xff); zip_lookahead--; zip_strstart++; } if(flush) { zip_flush_block(0); zip_block_start = zip_strstart; } /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ while(zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile) zip_fill_window(); } } var zip_deflate_better = function() { /* Process the input block. */ while(zip_lookahead != 0 && zip_qhead == null) { /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ zip_INSERT_STRING(); /* Find the longest match, discarding those <= prev_length. */ zip_prev_length = zip_match_length; zip_prev_match = zip_match_start; zip_match_length = zip_MIN_MATCH - 1; if(zip_hash_head != zip_NIL && zip_prev_length < zip_max_lazy_match && zip_strstart - zip_hash_head <= zip_MAX_DIST) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ zip_match_length = zip_longest_match(zip_hash_head); /* longest_match() sets match_start */ if(zip_match_length > zip_lookahead) zip_match_length = zip_lookahead; /* Ignore a length 3 match if it is too distant: */ if(zip_match_length == zip_MIN_MATCH && zip_strstart - zip_match_start > zip_TOO_FAR) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ zip_match_length--; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if(zip_prev_length >= zip_MIN_MATCH && zip_match_length <= zip_prev_length) { var flush; // set if current block must be flushed // check_match(strstart - 1, prev_match, prev_length); flush = zip_ct_tally(zip_strstart - 1 - zip_prev_match, zip_prev_length - zip_MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. */ zip_lookahead -= zip_prev_length - 1; zip_prev_length -= 2; do { zip_strstart++; zip_INSERT_STRING(); /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH * these bytes are garbage, but it does not matter since the * next lookahead bytes will always be emitted as literals. */ } while(--zip_prev_length != 0); zip_match_available = 0; zip_match_length = zip_MIN_MATCH - 1; zip_strstart++; if(flush) { zip_flush_block(0); zip_block_start = zip_strstart; } } else if(zip_match_available != 0) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ if(zip_ct_tally(0, zip_window[zip_strstart - 1] & 0xff)) { zip_flush_block(0); zip_block_start = zip_strstart; } zip_strstart++; zip_lookahead--; } else { /* There is no previous match to compare with, wait for * the next step to decide. */ zip_match_available = 1; zip_strstart++; zip_lookahead--; } /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ while(zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile) zip_fill_window(); } } var zip_init_deflate = function() { if(zip_eofile) return; zip_bi_buf = 0; zip_bi_valid = 0; zip_ct_init(); zip_lm_init(); zip_qhead = null; zip_outcnt = 0; zip_outoff = 0; if(zip_compr_level <= 3) { zip_prev_length = zip_MIN_MATCH - 1; zip_match_length = 0; } else { zip_match_length = zip_MIN_MATCH - 1; zip_match_available = 0; } zip_complete = false; } /* ========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ var zip_deflate_internal = function(buff, off, buff_size) { var n; if(!zip_initflag) { zip_init_deflate(); zip_initflag = true; if(zip_lookahead == 0) { // empty zip_complete = true; return 0; } } if((n = zip_qcopy(buff, off, buff_size)) == buff_size) return buff_size; if(zip_complete) return n; if(zip_compr_level <= 3) // optimized for speed zip_deflate_fast(); else zip_deflate_better(); if(zip_lookahead == 0) { if(zip_match_available != 0) zip_ct_tally(0, zip_window[zip_strstart - 1] & 0xff); zip_flush_block(1); zip_complete = true; } return n + zip_qcopy(buff, n + off, buff_size - n); } var zip_qcopy = function(buff, off, buff_size) { var n, i, j; n = 0; while(zip_qhead != null && n < buff_size) { i = buff_size - n; if(i > zip_qhead.len) i = zip_qhead.len; // System.arraycopy(qhead.ptr, qhead.off, buff, off + n, i); for(j = 0; j < i; j++) buff[off + n + j] = zip_qhead.ptr[zip_qhead.off + j]; zip_qhead.off += i; zip_qhead.len -= i; n += i; if(zip_qhead.len == 0) { var p; p = zip_qhead; zip_qhead = zip_qhead.next; zip_reuse_queue(p); } } if(n == buff_size) return n; if(zip_outoff < zip_outcnt) { i = buff_size - n; if(i > zip_outcnt - zip_outoff) i = zip_outcnt - zip_outoff; // System.arraycopy(outbuf, outoff, buff, off + n, i); for(j = 0; j < i; j++) buff[off + n + j] = zip_outbuf[zip_outoff + j]; zip_outoff += i; n += i; if(zip_outcnt == zip_outoff) zip_outcnt = zip_outoff = 0; } return n; } /* ========================================================================== * Allocate the match buffer, initialize the various tables and save the * location of the internal file attribute (ascii/binary) and method * (DEFLATE/STORE). */ var zip_ct_init = function() { var n; // iterates over tree elements var bits; // bit counter var length; // length value var code; // code value var dist; // distance index if(zip_static_dtree[0].dl != 0) return; // ct_init already called zip_l_desc.dyn_tree = zip_dyn_ltree; zip_l_desc.static_tree = zip_static_ltree; zip_l_desc.extra_bits = zip_extra_lbits; zip_l_desc.extra_base = zip_LITERALS + 1; zip_l_desc.elems = zip_L_CODES; zip_l_desc.max_length = zip_MAX_BITS; zip_l_desc.max_code = 0; zip_d_desc.dyn_tree = zip_dyn_dtree; zip_d_desc.static_tree = zip_static_dtree; zip_d_desc.extra_bits = zip_extra_dbits; zip_d_desc.extra_base = 0; zip_d_desc.elems = zip_D_CODES; zip_d_desc.max_length = zip_MAX_BITS; zip_d_desc.max_code = 0; zip_bl_desc.dyn_tree = zip_bl_tree; zip_bl_desc.static_tree = null; zip_bl_desc.extra_bits = zip_extra_blbits; zip_bl_desc.extra_base = 0; zip_bl_desc.elems = zip_BL_CODES; zip_bl_desc.max_length = zip_MAX_BL_BITS; zip_bl_desc.max_code = 0; // Initialize the mapping length (0..255) -> length code (0..28) length = 0; for(code = 0; code < zip_LENGTH_CODES-1; code++) { zip_base_length[code] = length; for(n = 0; n < (1<<zip_extra_lbits[code]); n++) zip_length_code[length++] = code; } // Assert (length == 256, "ct_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ zip_length_code[length-1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for(code = 0 ; code < 16; code++) { zip_base_dist[code] = dist; for(n = 0; n < (1<<zip_extra_dbits[code]); n++) { zip_dist_code[dist++] = code; } } // Assert (dist == 256, "ct_init: dist != 256"); dist >>= 7; // from now on, all distances are divided by 128 for( ; code < zip_D_CODES; code++) { zip_base_dist[code] = dist << 7; for(n = 0; n < (1<<(zip_extra_dbits[code]-7)); n++) zip_dist_code[256 + dist++] = code; } // Assert (dist == 256, "ct_init: 256+dist != 512"); // Construct the codes of the static literal tree for(bits = 0; bits <= zip_MAX_BITS; bits++) zip_bl_count[bits] = 0; n = 0; while(n <= 143) { zip_static_ltree[n++].dl = 8; zip_bl_count[8]++; } while(n <= 255) { zip_static_ltree[n++].dl = 9; zip_bl_count[9]++; } while(n <= 279) { zip_static_ltree[n++].dl = 7; zip_bl_count[7]++; } while(n <= 287) { zip_static_ltree[n++].dl = 8; zip_bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ zip_gen_codes(zip_static_ltree, zip_L_CODES + 1); /* The static distance tree is trivial: */ for(n = 0; n < zip_D_CODES; n++) { zip_static_dtree[n].dl = 5; zip_static_dtree[n].fc = zip_bi_reverse(n, 5); } // Initialize the first block of the first file: zip_init_block(); } /* ========================================================================== * Initialize a new block. */ var zip_init_block = function() { var n; // iterates over tree elements // Initialize the trees. for(n = 0; n < zip_L_CODES; n++) zip_dyn_ltree[n].fc = 0; for(n = 0; n < zip_D_CODES; n++) zip_dyn_dtree[n].fc = 0; for(n = 0; n < zip_BL_CODES; n++) zip_bl_tree[n].fc = 0; zip_dyn_ltree[zip_END_BLOCK].fc = 1; zip_opt_len = zip_static_len = 0; zip_last_lit = zip_last_dist = zip_last_flags = 0; zip_flags = 0; zip_flag_bit = 1; } /* ========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ var zip_pqdownheap = function( tree, // the tree to restore k) { // node to move down var v = zip_heap[k]; var j = k << 1; // left son of k while(j <= zip_heap_len) { // Set j to the smallest of the two sons: if(j < zip_heap_len && zip_SMALLER(tree, zip_heap[j + 1], zip_heap[j])) j++; // Exit if v is smaller than both sons if(zip_SMALLER(tree, v, zip_heap[j])) break; // Exchange v with the smallest son zip_heap[k] = zip_heap[j]; k = j; // And continue down the tree, setting j to the left son of k j <<= 1; } zip_heap[k] = v; } /* ========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ var zip_gen_bitlen = function(desc) { // the tree descriptor var tree = desc.dyn_tree; var extra = desc.extra_bits; var base = desc.extra_base; var max_code = desc.max_code; var max_length = desc.max_length; var stree = desc.static_tree; var h; // heap index var n, m; // iterate over the tree elements var bits; // bit length var xbits; // extra bits var f; // frequency var overflow = 0; // number of elements with bit length too large for(bits = 0; bits <= zip_MAX_BITS; bits++) zip_bl_count[bits] = 0; /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[zip_heap[zip_heap_max]].dl = 0; // root of the heap for(h = zip_heap_max + 1; h < zip_HEAP_SIZE; h++) { n = zip_heap[h]; bits = tree[tree[n].dl].dl + 1; if(bits > max_length) { bits = max_length; overflow++; } tree[n].dl = bits; // We overwrite tree[n].dl which is no longer needed if(n > max_code) continue; // not a leaf node zip_bl_count[bits]++; xbits = 0; if(n >= base) xbits = extra[n - base]; f = tree[n].fc; zip_opt_len += f * (bits + xbits); if(stree != null) zip_static_len += f * (stree[n].dl + xbits); } if(overflow == 0) return; // This happens for example on obj2 and pic of the Calgary corpus // Find the first bit length which could increase: do { bits = max_length - 1; while(zip_bl_count[bits] == 0) bits--; zip_bl_count[bits]--; // move one leaf down the tree zip_bl_count[bits + 1] += 2; // move one overflow item as its brother zip_bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while(overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for(bits = max_length; bits != 0; bits--) { n = zip_bl_count[bits]; while(n != 0) { m = zip_heap[--h]; if(m > max_code) continue; if(tree[m].dl != bits) { zip_opt_len += (bits - tree[m].dl) * tree[m].fc; tree[m].fc = bits; } n--; } } } /* ========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ var zip_gen_codes = function(tree, // the tree to decorate max_code) { // largest code with non zero frequency var next_code = new Array(zip_MAX_BITS+1); // next code value for each bit length var code = 0; // running code value var bits; // bit index var n; // code index /* The distribution counts are first used to generate the code values * without bit reversal. */ for(bits = 1; bits <= zip_MAX_BITS; bits++) { code = ((code + zip_bl_count[bits-1]) << 1); next_code[bits] = code; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ // Assert (code + encoder->bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); // Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for(n = 0; n <= max_code; n++) { var len = tree[n].dl; if(len == 0) continue; // Now reverse the bits tree[n].fc = zip_bi_reverse(next_code[len]++, len); // Tracec(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].fc, next_code[len]-1)); } } /* ========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ var zip_build_tree = function(desc) { // the tree descriptor var tree = desc.dyn_tree; var stree = desc.static_tree; var elems = desc.elems; var n, m; // iterate over heap elements var max_code = -1; // largest code with non zero frequency var node = elems; // next internal node of the tree /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ zip_heap_len = 0; zip_heap_max = zip_HEAP_SIZE; for(n = 0; n < elems; n++) { if(tree[n].fc != 0) { zip_heap[++zip_heap_len] = max_code = n; zip_depth[n] = 0; } else tree[n].dl = 0; } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while(zip_heap_len < 2) { var xnew = zip_heap[++zip_heap_len] = (max_code < 2 ? ++max_code : 0); tree[xnew].fc = 1; zip_depth[xnew] = 0; zip_opt_len--; if(stree != null) zip_static_len -= stree[xnew].dl; // new is 0 or 1 so it does not have extra bits } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for(n = zip_heap_len >> 1; n >= 1; n--) zip_pqdownheap(tree, n); /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ do { n = zip_heap[zip_SMALLEST]; zip_heap[zip_SMALLEST] = zip_heap[zip_heap_len--]; zip_pqdownheap(tree, zip_SMALLEST); m = zip_heap[zip_SMALLEST]; // m = node of next least frequency // keep the nodes sorted by frequency zip_heap[--zip_heap_max] = n; zip_heap[--zip_heap_max] = m; // Create a new node father of n and m tree[node].fc = tree[n].fc + tree[m].fc; // depth[node] = (char)(MAX(depth[n], depth[m]) + 1); if(zip_depth[n] > zip_depth[m] + 1) zip_depth[node] = zip_depth[n]; else zip_depth[node] = zip_depth[m] + 1; tree[n].dl = tree[m].dl = node; // and insert the new node in the heap zip_heap[zip_SMALLEST] = node++; zip_pqdownheap(tree, zip_SMALLEST); } while(zip_heap_len >= 2); zip_heap[--zip_heap_max] = zip_heap[zip_SMALLEST]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ zip_gen_bitlen(desc); // The field len is now set, we can generate the bit codes zip_gen_codes(tree, max_code); } /* ========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. Updates opt_len to take into account the repeat * counts. (The contribution of the bit length codes will be added later * during the construction of bl_tree.) */ var zip_scan_tree = function(tree,// the tree to be scanned max_code) { // and its largest code of non zero frequency var n; // iterates over all tree elements var prevlen = -1; // last emitted length var curlen; // length of current code var nextlen = tree[0].dl; // length of next code var count = 0; // repeat count of the current code var max_count = 7; // max repeat count var min_count = 4; // min repeat count if(nextlen == 0) { max_count = 138; min_count = 3; } tree[max_code + 1].dl = 0xffff; // guard for(n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n + 1].dl; if(++count < max_count && curlen == nextlen) continue; else if(count < min_count) zip_bl_tree[curlen].fc += count; else if(curlen != 0) { if(curlen != prevlen) zip_bl_tree[curlen].fc++; zip_bl_tree[zip_REP_3_6].fc++; } else if(count <= 10) zip_bl_tree[zip_REPZ_3_10].fc++; else zip_bl_tree[zip_REPZ_11_138].fc++; count = 0; prevlen = curlen; if(nextlen == 0) { max_count = 138; min_count = 3; } else if(curlen == nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* ========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ var zip_send_tree = function(tree, // the tree to be scanned max_code) { // and its largest code of non zero frequency var n; // iterates over all tree elements var prevlen = -1; // last emitted length var curlen; // length of current code var nextlen = tree[0].dl; // length of next code var count = 0; // repeat count of the current code var max_count = 7; // max repeat count var min_count = 4; // min repeat count /* tree[max_code+1].dl = -1; */ /* guard already set */ if(nextlen == 0) { max_count = 138; min_count = 3; } for(n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].dl; if(++count < max_count && curlen == nextlen) { continue; } else if(count < min_count) { do { zip_SEND_CODE(curlen, zip_bl_tree); } while(--count != 0); } else if(curlen != 0) { if(curlen != prevlen) { zip_SEND_CODE(curlen, zip_bl_tree); count--; } // Assert(count >= 3 && count <= 6, " 3_6?"); zip_SEND_CODE(zip_REP_3_6, zip_bl_tree); zip_send_bits(count - 3, 2); } else if(count <= 10) { zip_SEND_CODE(zip_REPZ_3_10, zip_bl_tree); zip_send_bits(count-3, 3); } else { zip_SEND_CODE(zip_REPZ_11_138, zip_bl_tree); zip_send_bits(count-11, 7); } count = 0; prevlen = curlen; if(nextlen == 0) { max_count = 138; min_count = 3; } else if(curlen == nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* ========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ var zip_build_bl_tree = function() { var max_blindex; // index of last bit length code of non zero freq // Determine the bit length frequencies for literal and distance trees zip_scan_tree(zip_dyn_ltree, zip_l_desc.max_code); zip_scan_tree(zip_dyn_dtree, zip_d_desc.max_code); // Build the bit length tree: zip_build_tree(zip_bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for(max_blindex = zip_BL_CODES-1; max_blindex >= 3; max_blindex--) { if(zip_bl_tree[zip_bl_order[max_blindex]].dl != 0) break; } /* Update opt_len to include the bit length tree and counts */ zip_opt_len += 3*(max_blindex+1) + 5+5+4; // Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // encoder->opt_len, encoder->static_len)); return max_blindex; } /* ========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ var zip_send_all_trees = function(lcodes, dcodes, blcodes) { // number of codes for each tree var rank; // index in bl_order // Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); // Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); // Tracev((stderr, "\nbl counts: ")); zip_send_bits(lcodes-257, 5); // not +255 as stated in appnote.txt zip_send_bits(dcodes-1, 5); zip_send_bits(blcodes-4, 4); // not -3 as stated in appnote.txt for(rank = 0; rank < blcodes; rank++) { // Tracev((stderr, "\nbl code %2d ", bl_order[rank])); zip_send_bits(zip_bl_tree[zip_bl_order[rank]].dl, 3); } // send the literal tree zip_send_tree(zip_dyn_ltree,lcodes-1); // send the distance tree zip_send_tree(zip_dyn_dtree,dcodes-1); } /* ========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ var zip_flush_block = function(eof) { // true if this is the last block for a file var opt_lenb, static_lenb; // opt_len and static_len in bytes var max_blindex; // index of last bit length code of non zero freq var stored_len; // length of input block stored_len = zip_strstart - zip_block_start; zip_flag_buf[zip_last_flags] = zip_flags; // Save the flags for the last 8 items // Construct the literal and distance trees zip_build_tree(zip_l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", // encoder->opt_len, encoder->static_len)); zip_build_tree(zip_d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", // encoder->opt_len, encoder->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = zip_build_bl_tree(); // Determine the best encoding. Compute first the block length in bytes opt_lenb = (zip_opt_len +3+7)>>3; static_lenb = (zip_static_len+3+7)>>3; // Trace((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ", // opt_lenb, encoder->opt_len, // static_lenb, encoder->static_len, stored_len, // encoder->last_lit, encoder->last_dist)); if(static_lenb <= opt_lenb) opt_lenb = static_lenb; if(stored_len + 4 <= opt_lenb // 4: two words for the lengths && zip_block_start >= 0) { var i; /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ zip_send_bits((zip_STORED_BLOCK<<1)+eof, 3); /* send block type */ zip_bi_windup(); /* align on byte boundary */ zip_put_short(stored_len); zip_put_short(~stored_len); // copy block /* p = &window[block_start]; for(i = 0; i < stored_len; i++) put_byte(p[i]); */ for(i = 0; i < stored_len; i++) zip_put_byte(zip_window[zip_block_start + i]); } else if(static_lenb == opt_lenb) { zip_send_bits((zip_STATIC_TREES<<1)+eof, 3); zip_compress_block(zip_static_ltree, zip_static_dtree); } else { zip_send_bits((zip_DYN_TREES<<1)+eof, 3); zip_send_all_trees(zip_l_desc.max_code+1, zip_d_desc.max_code+1, max_blindex+1); zip_compress_block(zip_dyn_ltree, zip_dyn_dtree); } zip_init_block(); if(eof != 0) zip_bi_windup(); } /* ========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ var zip_ct_tally = function( dist, // distance of matched string lc) { // match length-MIN_MATCH or unmatched char (if dist==0) zip_l_buf[zip_last_lit++] = lc; if(dist == 0) { // lc is the unmatched char zip_dyn_ltree[lc].fc++; } else { // Here, lc is the match length - MIN_MATCH dist--; // dist = match distance - 1 // Assert((ush)dist < (ush)MAX_DIST && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)D_CODE(dist) < (ush)D_CODES, "ct_tally: bad match"); zip_dyn_ltree[zip_length_code[lc]+zip_LITERALS+1].fc++; zip_dyn_dtree[zip_D_CODE(dist)].fc++; zip_d_buf[zip_last_dist++] = dist; zip_flags |= zip_flag_bit; } zip_flag_bit <<= 1; // Output the flags if they fill a byte if((zip_last_lit & 7) == 0) { zip_flag_buf[zip_last_flags++] = zip_flags; zip_flags = 0; zip_flag_bit = 1; } // Try to guess if it is profitable to stop the current block here if(zip_compr_level > 2 && (zip_last_lit & 0xfff) == 0) { // Compute an upper bound for the compressed length var out_length = zip_last_lit * 8; var in_length = zip_strstart - zip_block_start; var dcode; for(dcode = 0; dcode < zip_D_CODES; dcode++) { out_length += zip_dyn_dtree[dcode].fc * (5 + zip_extra_dbits[dcode]); } out_length >>= 3; // Trace((stderr,"\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ", // encoder->last_lit, encoder->last_dist, in_length, out_length, // 100L - out_length*100L/in_length)); if(zip_last_dist < parseInt(zip_last_lit/2) && out_length < parseInt(in_length/2)) return true; } return (zip_last_lit == zip_LIT_BUFSIZE-1 || zip_last_dist == zip_DIST_BUFSIZE); /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } /* ========================================================================== * Send the block data compressed using the given Huffman trees */ var zip_compress_block = function( ltree, // literal tree dtree) { // distance tree var dist; // distance of matched string var lc; // match length or unmatched char (if dist == 0) var lx = 0; // running index in l_buf var dx = 0; // running index in d_buf var fx = 0; // running index in flag_buf var flag = 0; // current flags var code; // the code to send var extra; // number of extra bits to send if(zip_last_lit != 0) do { if((lx & 7) == 0) flag = zip_flag_buf[fx++]; lc = zip_l_buf[lx++] & 0xff; if((flag & 1) == 0) { zip_SEND_CODE(lc, ltree); /* send a literal byte */ // Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { // Here, lc is the match length - MIN_MATCH code = zip_length_code[lc]; zip_SEND_CODE(code+zip_LITERALS+1, ltree); // send the length code extra = zip_extra_lbits[code]; if(extra != 0) { lc -= zip_base_length[code]; zip_send_bits(lc, extra); // send the extra length bits } dist = zip_d_buf[dx++]; // Here, dist is the match distance - 1 code = zip_D_CODE(dist); // Assert (code < D_CODES, "bad d_code"); zip_SEND_CODE(code, dtree); // send the distance code extra = zip_extra_dbits[code]; if(extra != 0) { dist -= zip_base_dist[code]; zip_send_bits(dist, extra); // send the extra distance bits } } // literal or match pair ? flag >>= 1; } while(lx < zip_last_lit); zip_SEND_CODE(zip_END_BLOCK, ltree); } /* ========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ var zip_Buf_size = 16; // bit size of bi_buf var zip_send_bits = function( value, // value to send length) { // number of bits /* If not enough room in bi_buf, use (valid) bits from bi_buf and * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) * unused bits in value. */ if(zip_bi_valid > zip_Buf_size - length) { zip_bi_buf |= (value << zip_bi_valid); zip_put_short(zip_bi_buf); zip_bi_buf = (value >> (zip_Buf_size - zip_bi_valid)); zip_bi_valid += length - zip_Buf_size; } else { zip_bi_buf |= value << zip_bi_valid; zip_bi_valid += length; } } /* ========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ var zip_bi_reverse = function( code, // the value to invert len) { // its bit length var res = 0; do { res |= code & 1; code >>= 1; res <<= 1; } while(--len > 0); return res >> 1; } /* ========================================================================== * Write out any remaining bits in an incomplete byte. */ var zip_bi_windup = function() { if(zip_bi_valid > 8) { zip_put_short(zip_bi_buf); } else if(zip_bi_valid > 0) { zip_put_byte(zip_bi_buf); } zip_bi_buf = 0; zip_bi_valid = 0; } var zip_qoutbuf = function() { if(zip_outcnt != 0) { var q, i; q = zip_new_queue(); if(zip_qhead == null) zip_qhead = zip_qtail = q; else zip_qtail = zip_qtail.next = q; q.len = zip_outcnt - zip_outoff; // System.arraycopy(zip_outbuf, zip_outoff, q.ptr, 0, q.len); for(i = 0; i < q.len; i++) q.ptr[i] = zip_outbuf[zip_outoff + i]; zip_outcnt = zip_outoff = 0; } } var zip_deflate = function(str, level) { var i, j; zip_deflate_data = str; zip_deflate_pos = 0; if(typeof level == "undefined") level = zip_DEFAULT_LEVEL; zip_deflate_start(level); var buff = new Array(1024); var aout = []; while((i = zip_deflate_internal(buff, 0, buff.length)) > 0) { var cbuf = new Array(i); for(j = 0; j < i; j++){ cbuf[j] = String.fromCharCode(buff[j]); } aout[aout.length] = cbuf.join(""); } zip_deflate_data = null; // G.C. return aout.join(""); } // // end of the script of Masanao Izumo. // // we add the compression method for JSZip JSZip.compressions["DEFLATE"] = { magic : "\x08\x00", compress : function (content) { return zip_deflate(content); } } })();
JavaScript
/* * QUnit - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2009 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. */ (function(window) { var QUnit = { // Initialize the configuration options init: function init() { config = { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, blocking: false, autorun: false, assertions: [], filters: [], queue: [] }; var tests = id("qunit-tests"), banner = id("qunit-banner"), result = id("qunit-testresult"); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } }, // call on start of module test to prepend name to all tests module: function module(name, testEnvironment) { synchronize(function() { if ( config.currentModule ) { QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); } config.currentModule = name; config.moduleTestEnvironment = testEnvironment; config.moduleStats = { all: 0, bad: 0 }; QUnit.moduleStart( name ); }); }, asyncTest: function asyncTest(testName, expected, callback) { if ( arguments.length === 2 ) { callback = expected; expected = 0; } QUnit.test(testName, expected, callback, true); }, test: function test(testName, expected, callback, async) { var name = testName, testEnvironment = {}; if ( arguments.length === 2 ) { callback = expected; expected = null; } if ( config.currentModule ) { name = config.currentModule + " module: " + name; } if ( !validTest(name) ) { return; } synchronize(function() { QUnit.testStart( testName ); testEnvironment = extend({ setup: function() {}, teardown: function() {} }, config.moduleTestEnvironment); config.assertions = []; config.expected = null; if ( arguments.length >= 3 ) { config.expected = callback; callback = arguments[2]; } try { if ( !config.pollution ) { saveGlobal(); } testEnvironment.setup.call(testEnvironment); } catch(e) { QUnit.ok( false, "Setup failed on " + name + ": " + e.message ); } if ( async ) { QUnit.stop(); } try { callback.call(testEnvironment); } catch(e) { fail("Test " + name + " died, exception and test follows", e, callback); QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { start(); } } }); synchronize(function() { try { checkPollution(); testEnvironment.teardown.call(testEnvironment); } catch(e) { QUnit.ok( false, "Teardown failed on " + name + ": " + e.message ); } try { reset(); } catch(e) { fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset); } if ( config.expected && config.expected != config.assertions.length ) { QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += config.assertions.length; config.moduleStats.all += config.assertions.length; if ( tests ) { var ol = document.createElement("ol"); ol.style.display = "none"; for ( var i = 0; i < config.assertions.length; i++ ) { var assertion = config.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || "(no message)"; ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } var b = document.createElement("strong"); b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>"; addEvent(b, "click", function() { var next = b.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = (e || window.event).target; if ( target.nodeName.toLowerCase() === "strong" ) { var text = "", node = target.firstChild; while ( node.nodeType === 3 ) { text += node.nodeValue; node = node.nextSibling; } text = text.replace(/(^\s*|\s*$)/g, ""); if ( window.location ) { window.location.href = window.location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent(text); } } }); var li = document.createElement("li"); li.className = bad ? "fail" : "pass"; li.appendChild( b ); li.appendChild( ol ); tests.appendChild( li ); if ( bad ) { var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "block"; id("qunit-filter-pass").disabled = null; id("qunit-filter-missing").disabled = null; } } } else { for ( var i = 0; i < config.assertions.length; i++ ) { if ( !config.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } QUnit.testDone( testName, bad, config.assertions.length ); if ( !window.setTimeout && !config.queue.length ) { done(); } }); if ( window.setTimeout && !config.doneTimer ) { config.doneTimer = window.setTimeout(function(){ if ( !config.queue.length ) { done(); } else { synchronize( done ); } }, 13); } }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function expect(asserts) { config.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function ok(a, msg) { QUnit.log(a, msg); config.assertions.push({ result: !!a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equals( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equals: function equals(actual, expected, message) { push(expected == actual, actual, expected, message); }, same: function(a, b, message) { push(QUnit.equiv(a, b), a, b, message); }, start: function start() { // A slight delay, to avoid any current callbacks if ( window.setTimeout ) { window.setTimeout(function() { if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(); }, 13); } else { config.blocking = false; process(); } }, stop: function stop(timeout) { config.blocking = true; if ( timeout && window.setTimeout ) { config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); start(); }, timeout); } }, /** * Resets the test setup. Useful for tests that modify the DOM. */ reset: function reset() { if ( window.jQuery ) { jQuery("#main").html( config.fixture ); jQuery.event.global = {}; jQuery.ajaxSettings = extend({}, config.ajaxSettings); } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function triggerEvent( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Logging callbacks done: function done(failures, total) {}, log: function log(result, message) {}, testStart: function testStart(name) {}, testDone: function testDone(name, failures, total) {}, moduleStart: function moduleStart(name) {}, moduleDone: function moduleDone(name, failures, total) {} }; // Maintain internal state var config = { // The queue of tests to run queue: [], // block until document ready blocking: true }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, GETParams = location.search.slice(1).split('&'); for ( var i = 0; i < GETParams.length; i++ ) { GETParams[i] = decodeURIComponent( GETParams[i] ); if ( GETParams[i] === "noglobals" ) { GETParams.splice( i, 1 ); i--; config.noglobals = true; } } // restrict modules/tests by get parameters config.filters = GETParams; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:'); })(); // Expose the API as global variables, unless an 'exports' // object exists, in that case we assume we're in CommonJS if ( typeof exports === "undefined" || typeof require === "undefined" ) { extend(window, QUnit); window.QUnit = QUnit; } else { extend(exports, QUnit); exports.QUnit = QUnit; } if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true; } addEvent(window, "load", function() { // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "none"; var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; filter.disabled = true; addEvent( filter, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("pass") > -1 ) { li[i].style.display = filter.checked ? "none" : "block"; } } }); toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); var missing = document.createElement("input"); missing.type = "checkbox"; missing.id = "qunit-filter-missing"; missing.disabled = true; addEvent( missing, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) { li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block"; } } }); toolbar.appendChild( missing ); label = document.createElement("label"); label.setAttribute("for", "filter-missing"); label.innerHTML = "Hide missing tests (untested code is broken code)"; toolbar.appendChild( label ); } var main = id('main'); if ( main ) { config.fixture = main.innerHTML; } if ( window.jQuery ) { config.ajaxSettings = window.jQuery.ajaxSettings; } start(); }); function done() { if ( config.doneTimer && window.clearTimeout ) { window.clearTimeout( config.doneTimer ); config.doneTimer = null; } if ( config.queue.length ) { config.doneTimer = window.setTimeout(function(){ if ( !config.queue.length ) { done(); } else { synchronize( done ); } }, 13); return; } config.autorun = true; // Log the last module results if ( config.currentModule ) { QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); } var banner = id("qunit-banner"), tests = id("qunit-tests"), html = ['Tests completed in ', +new Date - config.started, ' milliseconds.<br/>', '<span class="bad">', config.stats.all - config.stats.bad, '</span> tests of <span class="all">', config.stats.all, '</span> passed, ', config.stats.bad,' failed.'].join(''); if ( banner ) { banner.className += " " + (config.stats.bad ? "fail" : "pass"); } if ( tests ) { var result = id("qunit-testresult"); if ( !result ) { result = document.createElement("p"); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests.nextSibling ); } result.innerHTML = html; } QUnit.done( config.stats.bad, config.stats.all ); } function validTest( name ) { var i = config.filters.length, run = false; if ( !i ) { return true; } while ( i-- ) { var filter = config.filters[i], not = filter.charAt(0) == '!'; if ( not ) { filter = filter.slice(1); } if ( name.indexOf(filter) !== -1 ) { return !not; } if ( not ) { run = true; } } return run; } function push(result, actual, expected, message) { message = message || (result ? "okay" : "failed"); QUnit.ok( result, result ? message + ": " + expected : message + ", expected: " + QUnit.jsDump.parse(expected) + " result: " + QUnit.jsDump.parse(actual) ); } function synchronize( callback ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process(); } } function process() { while ( config.queue.length && !config.blocking ) { config.queue.shift()(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { config.pollution.push( key ); } } } function checkPollution( name ) { var old = config.pollution; saveGlobal(); var newGlobals = diff( old, config.pollution ); if ( newGlobals.length > 0 ) { ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); config.expected++; } var deletedGlobals = diff( config.pollution, old ); if ( deletedGlobals.length > 0 ) { ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); config.expected++; } } // returns a new Array with the elements that are in a but not in b function diff( a, b ) { var result = a.slice(); for ( var i = 0; i < result.length; i++ ) { for ( var j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice(i, 1); i--; break; } } } return result; } function fail(message, exception, callback) { if ( typeof console !== "undefined" && console.error && console.warn ) { console.error(message); console.error(exception); console.warn(callback.toString()); } else if ( window.opera && opera.postError ) { opera.postError(message, exception, callback.toString); } } function extend(a, b) { for ( var prop in b ) { a[prop] = b[prop]; } return a; } function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); } } function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name ); } // Test for equality any JavaScript type. // Discussions and reference: http://philrathe.com/articles/equiv // Test suites: http://philrathe.com/tests/equiv // Author: Philippe Rathé <prathe@gmail.com> QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions // Determine what is o. function hoozit(o) { if (o.constructor === String) { return "string"; } else if (o.constructor === Boolean) { return "boolean"; } else if (o.constructor === Number) { if (isNaN(o)) { return "nan"; } else { return "number"; } } else if (typeof o === "undefined") { return "undefined"; // consider: typeof null === object } else if (o === null) { return "null"; // consider: typeof [] === object } else if (o instanceof Array) { return "array"; // consider: typeof new Date() === object } else if (o instanceof Date) { return "date"; // consider: /./ instanceof Object; // /./ instanceof RegExp; // typeof /./ === "function"; // => false in IE and Opera, // true in FF and Safari } else if (o instanceof RegExp) { return "regexp"; } else if (typeof o === "object") { return "object"; } else if (o instanceof Function) { return "function"; } else { return undefined; } } // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = hoozit(o); if (prop) { if (hoozit(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "nan": function (b) { return isNaN(b); }, "date": function (b, a) { return hoozit(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp": function (b, a) { return hoozit(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function": function () { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array": function (b, a) { var i; var len; // b could be an object literal here if ( ! (hoozit(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } for (i = 0; i < len; i++) { if ( ! innerEquiv(a[i], b[i])) { return false; } } return true; }, "object": function (b, a) { var i; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of strings // comparing constructors is more strict than using instanceof if ( a.constructor !== b.constructor) { return false; } // stack constructor before traversing properties callers.push(a.constructor); for (i in a) { // be strict: don't ensures hasOwnProperty and go deep aProperties.push(i); // collect a's properties if ( ! innerEquiv(a[i], b[i])) { eq = false; } } callers.pop(); // unstack, we are done for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties.sort()); } }; }(); innerEquiv = function () { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function (a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [b, a]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1)); }; return innerEquiv; }(); /** * jsDump * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php) * Date: 5/15/2008 * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ QUnit.jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; }; function literal( o ) { return o + ''; }; function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) arr = arr.join( ',' + s + inner ); if ( !arr ) return pre + post; return [ pre, inner + arr, base + post ].join(s); }; function array( arr ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] ); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; return type == 'function' ? parser.call( this, obj ) : type == 'string' ? parser : this.parsers.error; }, typeOf:function( obj ) { var type = typeof obj, f = 'function';//we'll use it 3 times, save it return type != 'object' && type != f ? type : !obj ? 'null' : obj.exec ? 'regexp' :// some browsers (FF) consider regexps functions obj.getHours ? 'date' : obj.scrollBy ? 'window' : obj.nodeName == '#document' ? 'document' : obj.nodeName ? 'node' : obj.item ? 'nodelist' : // Safari reports nodelists as functions obj.callee ? 'arguments' : obj.call || obj.constructor != Array && //an array would also fall on this hack (obj+'').indexOf(f) != -1 ? f : //IE reports functions like alert, as objects 'length' in obj ? 'array' : type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; }, indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) return ''; var chr = this.indentChar; if ( this.HTML ) chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;'); return Array( this._depth_ + (extra||0) ).join(chr); }, up:function( a ) { this._depth_ += a || 1; }, down:function( a ) { this._depth_ -= a || 1; }, setParser:function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', undefined:'undefined', 'function':function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) ret += ' ' + name; ret += '('; ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, this.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map ) { var ret = [ ]; this.up(); for ( var key in map ) ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) ); this.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = this.HTML ? '&lt;' : '<', close = this.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in this.DOMAttrs ) { var val = node[this.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + this.parse( val, 'attribute' ); } return ret + close + open + '/' + tag + close; }, functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) return ''; var args = Array(l); while ( l-- ) args[l] = String.fromCharCode(97+l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:true,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump; })(); })(this);
JavaScript
$(document).ready(function(){ $('.showApplication').each(function() { $(this).bind('click', showApp ); }); }); var showApp = function (){ var alt = $(this).prop('alt'); var callback = function(responseText) { $('#currentApplication').html(responseText); }; $.get('showApplication', { student_id : alt}, callback, 'html'); };
JavaScript
// VT100.js -- JavaScript based terminal emulator // Copyright (C) 2008-2010 Markus Gutschke <markus@shellinabox.com> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // In addition to these license terms, the author grants the following // additional rights: // // If you modify this program, or any covered work, by linking or // combining it with the OpenSSL project's OpenSSL library (or a // modified version of that library), containing parts covered by the // terms of the OpenSSL or SSLeay licenses, the author // grants you additional permission to convey the resulting work. // Corresponding Source for a non-source form of such a combination // shall include the source code for the parts of OpenSSL used as well // as that of the covered work. // // You may at your option choose to remove this additional permission from // the work, or from any part of it. // // It is possible to build this program in a way that it loads OpenSSL // libraries at run-time. If doing so, the following notices are required // by the OpenSSL and SSLeay licenses: // // This product includes software developed by the OpenSSL Project // for use in the OpenSSL Toolkit. (http://www.openssl.org/) // // This product includes cryptographic software written by Eric Young // (eay@cryptsoft.com) // // // The most up-to-date version of this program is always available from // http://shellinabox.com // // // Notes: // // The author believes that for the purposes of this license, you meet the // requirements for publishing the source code, if your web server publishes // the source in unmodified form (i.e. with licensing information, comments, // formatting, and identifier names intact). If there are technical reasons // that require you to make changes to the source code when serving the // JavaScript (e.g to remove pre-processor directives from the source), these // changes should be done in a reversible fashion. // // The author does not consider websites that reference this script in // unmodified form, and web servers that serve this script in unmodified form // to be derived works. As such, they are believed to be outside of the // scope of this license and not subject to the rights or restrictions of the // GNU General Public License. // // If in doubt, consult a legal professional familiar with the laws that // apply in your country. // #define ESnormal 0 // #define ESesc 1 // #define ESsquare 2 // #define ESgetpars 3 // #define ESgotpars 4 // #define ESdeviceattr 5 // #define ESfunckey 6 // #define EShash 7 // #define ESsetG0 8 // #define ESsetG1 9 // #define ESsetG2 10 // #define ESsetG3 11 // #define ESbang 12 // #define ESpercent 13 // #define ESignore 14 // #define ESnonstd 15 // #define ESpalette 16 // #define EStitle 17 // #define ESss2 18 // #define ESss3 19 // #define ATTR_DEFAULT 0x00F0 // #define ATTR_REVERSE 0x0100 // #define ATTR_UNDERLINE 0x0200 // #define ATTR_DIM 0x0400 // #define ATTR_BRIGHT 0x0800 // #define ATTR_BLINK 0x1000 // #define MOUSE_DOWN 0 // #define MOUSE_UP 1 // #define MOUSE_CLICK 2 function VT100(container) { if (typeof linkifyURLs == 'undefined' || linkifyURLs <= 0) { this.urlRE = null; } else { this.urlRE = new RegExp( // Known URL protocol are "http", "https", and "ftp". '(?:http|https|ftp)://' + // Optionally allow username and passwords. '(?:[^:@/ \u00A0]*(?::[^@/ \u00A0]*)?@)?' + // Hostname. '(?:[1-9][0-9]{0,2}(?:[.][1-9][0-9]{0,2}){3}|' + '[0-9a-fA-F]{0,4}(?::{1,2}[0-9a-fA-F]{1,4})+|' + '(?!-)[^[!"#$%&\'()*+,/:;<=>?@\\^_`{|}~\u0000- \u007F-\u00A0]+)' + // Port '(?::[1-9][0-9]*)?' + // Path. '(?:/(?:(?![/ \u00A0]|[,.)}"\u0027!]+[ \u00A0]|[,.)}"\u0027!]+$).)*)*|' + (linkifyURLs <= 1 ? '' : // Also support URLs without a protocol (assume "http"). // Optional username and password. '(?:[^:@/ \u00A0]*(?::[^@/ \u00A0]*)?@)?' + // Hostnames must end with a well-known top-level domain or must be // numeric. '(?:[1-9][0-9]{0,2}(?:[.][1-9][0-9]{0,2}){3}|' + 'localhost|' + '(?:(?!-)' + '[^.[!"#$%&\'()*+,/:;<=>?@\\^_`{|}~\u0000- \u007F-\u00A0]+[.]){2,}' + '(?:(?:com|net|org|edu|gov|aero|asia|biz|cat|coop|info|int|jobs|mil|mobi|'+ 'museum|name|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|' + 'au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|' + 'ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|' + 'dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|' + 'gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|' + 'ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|' + 'lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|' + 'mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|' + 'pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|' + 'sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|' + 'tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|' + 'yu|za|zm|zw|arpa)(?![a-zA-Z0-9])|[Xx][Nn]--[-a-zA-Z0-9]+))' + // Port '(?::[1-9][0-9]{0,4})?' + // Path. '(?:/(?:(?![/ \u00A0]|[,.)}"\u0027!]+[ \u00A0]|[,.)}"\u0027!]+$).)*)*|') + // In addition, support e-mail address. Optionally, recognize "mailto:" '(?:mailto:)' + (linkifyURLs <= 1 ? '' : '?') + // Username: '[-_.+a-zA-Z0-9]+@' + // Hostname. '(?!-)[-a-zA-Z0-9]+(?:[.](?!-)[-a-zA-Z0-9]+)?[.]' + '(?:(?:com|net|org|edu|gov|aero|asia|biz|cat|coop|info|int|jobs|mil|mobi|'+ 'museum|name|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|' + 'au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|' + 'ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|' + 'dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|' + 'gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|' + 'ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|' + 'lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|' + 'mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|' + 'pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|' + 'sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|' + 'tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|' + 'yu|za|zm|zw|arpa)(?![a-zA-Z0-9])|[Xx][Nn]--[-a-zA-Z0-9]+)' + // Optional arguments '(?:[?](?:(?![ \u00A0]|[,.)}"\u0027!]+[ \u00A0]|[,.)}"\u0027!]+$).)*)?'); } this.getUserSettings(); this.initializeElements(container); this.maxScrollbackLines = 500; this.npar = 0; this.par = [ ]; this.isQuestionMark = false; this.savedX = [ ]; this.savedY = [ ]; this.savedAttr = [ ]; this.savedUseGMap = 0; this.savedGMap = [ this.Latin1Map, this.VT100GraphicsMap, this.CodePage437Map, this.DirectToFontMap ]; this.savedValid = [ ]; this.respondString = ''; this.titleString = ''; this.internalClipboard = undefined; this.reset(true); } VT100.prototype.reset = function(clearHistory) { this.isEsc = 0 /* ESnormal */; this.needWrap = false; this.autoWrapMode = true; this.dispCtrl = false; this.toggleMeta = false; this.insertMode = false; this.applKeyMode = false; this.cursorKeyMode = false; this.crLfMode = false; this.offsetMode = false; this.mouseReporting = false; this.printing = false; if (typeof this.printWin != 'undefined' && this.printWin && !this.printWin.closed) { this.printWin.close(); } this.printWin = null; this.utfEnabled = this.utfPreferred; this.utfCount = 0; this.utfChar = 0; this.color = 'ansi0 bgAnsi15'; this.style = ''; this.attr = 0x00F0 /* ATTR_DEFAULT */; this.useGMap = 0; this.GMap = [ this.Latin1Map, this.VT100GraphicsMap, this.CodePage437Map, this.DirectToFontMap]; this.translate = this.GMap[this.useGMap]; this.top = 0; this.bottom = this.terminalHeight; this.lastCharacter = ' '; this.userTabStop = [ ]; if (clearHistory) { for (var i = 0; i < 2; i++) { while (this.console[i].firstChild) { this.console[i].removeChild(this.console[i].firstChild); } } } this.enableAlternateScreen(false); var wasCompressed = false; var transform = this.getTransformName(); if (transform) { for (var i = 0; i < 2; ++i) { wasCompressed |= this.console[i].style[transform] != ''; this.console[i].style[transform] = ''; } this.cursor.style[transform] = ''; this.space.style[transform] = ''; if (transform == 'filter') { this.console[this.currentScreen].style.width = ''; } } this.scale = 1.0; if (wasCompressed) { this.resizer(); } this.gotoXY(0, 0); this.showCursor(); this.isInverted = false; this.refreshInvertedState(); this.clearRegion(0, 0, this.terminalWidth, this.terminalHeight, this.color, this.style); }; VT100.prototype.addListener = function(elem, event, listener) { try { if (elem.addEventListener) { elem.addEventListener(event, listener, false); } else { elem.attachEvent('on' + event, listener); } } catch (e) { } }; VT100.prototype.getUserSettings = function() { // Compute hash signature to identify the entries in the userCSS menu. // If the menu is unchanged from last time, default values can be // looked up in a cookie associated with this page. this.signature = 3; this.utfPreferred = true; this.visualBell = typeof suppressAllAudio != 'undefined' && suppressAllAudio; this.autoprint = true; this.softKeyboard = false; this.blinkingCursor = true; if (this.visualBell) { this.signature = Math.floor(16807*this.signature + 1) % ((1 << 31) - 1); } if (typeof userCSSList != 'undefined') { for (var i = 0; i < userCSSList.length; ++i) { var label = userCSSList[i][0]; for (var j = 0; j < label.length; ++j) { this.signature = Math.floor(16807*this.signature+ label.charCodeAt(j)) % ((1 << 31) - 1); } if (userCSSList[i][1]) { this.signature = Math.floor(16807*this.signature + 1) % ((1 << 31) - 1); } } } var key = 'shellInABox=' + this.signature + ':'; var settings = document.cookie.indexOf(key); if (settings >= 0) { settings = document.cookie.substr(settings + key.length). replace(/([0-1]*).*/, "$1"); if (settings.length == 5 + (typeof userCSSList == 'undefined' ? 0 : userCSSList.length)) { this.utfPreferred = settings.charAt(0) != '0'; this.visualBell = settings.charAt(1) != '0'; this.autoprint = settings.charAt(2) != '0'; this.softKeyboard = settings.charAt(3) != '0'; this.blinkingCursor = settings.charAt(4) != '0'; if (typeof userCSSList != 'undefined') { for (var i = 0; i < userCSSList.length; ++i) { userCSSList[i][2] = settings.charAt(i + 5) != '0'; } } } } this.utfEnabled = this.utfPreferred; }; VT100.prototype.storeUserSettings = function() { var settings = 'shellInABox=' + this.signature + ':' + (this.utfEnabled ? '1' : '0') + (this.visualBell ? '1' : '0') + (this.autoprint ? '1' : '0') + (this.softKeyboard ? '1' : '0') + (this.blinkingCursor ? '1' : '0'); if (typeof userCSSList != 'undefined') { for (var i = 0; i < userCSSList.length; ++i) { settings += userCSSList[i][2] ? '1' : '0'; } } var d = new Date(); d.setDate(d.getDate() + 3653); document.cookie = settings + ';expires=' + d.toGMTString(); }; VT100.prototype.initializeUserCSSStyles = function() { this.usercssActions = []; if (typeof userCSSList != 'undefined') { var menu = ''; var group = ''; var wasSingleSel = 1; var beginOfGroup = 0; for (var i = 0; i <= userCSSList.length; ++i) { if (i < userCSSList.length) { var label = userCSSList[i][0]; var newGroup = userCSSList[i][1]; var enabled = userCSSList[i][2]; // Add user style sheet to document var style = document.createElement('link'); var id = document.createAttribute('id'); id.nodeValue = 'usercss-' + i; style.setAttributeNode(id); var rel = document.createAttribute('rel'); rel.nodeValue = 'stylesheet'; style.setAttributeNode(rel); var href = document.createAttribute('href'); href.nodeValue = 'usercss-' + i + '.css'; style.setAttributeNode(href); var type = document.createAttribute('type'); type.nodeValue = 'text/css'; style.setAttributeNode(type); document.getElementsByTagName('head')[0].appendChild(style); style.disabled = !enabled; } // Add entry to menu if (newGroup || i == userCSSList.length) { if (beginOfGroup != 0 && (i - beginOfGroup > 1 || !wasSingleSel)) { // The last group had multiple entries that are mutually exclusive; // or the previous to last group did. In either case, we need to // append a "<hr />" before we can add the last group to the menu. menu += '<hr />'; } wasSingleSel = i - beginOfGroup < 1; menu += group; group = ''; for (var j = beginOfGroup; j < i; ++j) { this.usercssActions[this.usercssActions.length] = function(vt100, current, begin, count) { // Deselect all other entries in the group, then either select // (for multiple entries in group) or toggle (for on/off entry) // the current entry. return function() { var entry = vt100.getChildById(vt100.menu, 'beginusercss'); var i = -1; var j = -1; for (var c = count; c > 0; ++j) { if (entry.tagName == 'LI') { if (++i >= begin) { --c; var label = vt100.usercss.childNodes[j]; // Restore label to just the text content if (typeof label.textContent == 'undefined') { var s = label.innerText; label.innerHTML = ''; label.appendChild(document.createTextNode(s)); } else { label.textContent= label.textContent; } // User style sheets are numbered sequentially var sheet = document.getElementById( 'usercss-' + i); if (i == current) { if (count == 1) { sheet.disabled = !sheet.disabled; } else { sheet.disabled = false; } if (!sheet.disabled) { label.innerHTML= '<img src="enabled.gif" />' + label.innerHTML; } } else { sheet.disabled = true; } userCSSList[i][2] = !sheet.disabled; } } entry = entry.nextSibling; } // If the font size changed, adjust cursor and line dimensions this.cursor.style.cssText= ''; this.cursorWidth = this.cursor.clientWidth; this.cursorHeight = this.lineheight.clientHeight; for (i = 0; i < this.console.length; ++i) { for (var line = this.console[i].firstChild; line; line = line.nextSibling) { line.style.height = this.cursorHeight + 'px'; } } vt100.resizer(); }; }(this, j, beginOfGroup, i - beginOfGroup); } if (i == userCSSList.length) { break; } beginOfGroup = i; } // Collect all entries in a group, before attaching them to the menu. // This is necessary as we don't know whether this is a group of // mutually exclusive options (which should be separated by "<hr />" on // both ends), or whether this is a on/off toggle, which can be grouped // together with other on/off options. group += '<li>' + (enabled ? '<img src="enabled.gif" />' : '') + label + '</li>'; } this.usercss.innerHTML = menu; } }; VT100.prototype.resetLastSelectedKey = function(e) { var key = this.lastSelectedKey; if (!key) { return false; } var position = this.mousePosition(e); // We don't get all the necessary events to reliably reselect a key // if we moved away from it and then back onto it. We approximate the // behavior by remembering the key until either we release the mouse // button (we might never get this event if the mouse has since left // the window), or until we move away too far. var box = this.keyboard.firstChild; if (position[0] < box.offsetLeft + key.offsetWidth || position[1] < box.offsetTop + key.offsetHeight || position[0] >= box.offsetLeft + box.offsetWidth - key.offsetWidth || position[1] >= box.offsetTop + box.offsetHeight - key.offsetHeight || position[0] < box.offsetLeft + key.offsetLeft - key.offsetWidth || position[1] < box.offsetTop + key.offsetTop - key.offsetHeight || position[0] >= box.offsetLeft + key.offsetLeft + 2*key.offsetWidth || position[1] >= box.offsetTop + key.offsetTop + 2*key.offsetHeight) { if (this.lastSelectedKey.className) log.console('reset: deselecting'); this.lastSelectedKey.className = ''; this.lastSelectedKey = undefined; } return false; }; VT100.prototype.showShiftState = function(state) { var style = document.getElementById('shift_state'); if (state) { this.setTextContentRaw(style, '#vt100 #keyboard .shifted {' + 'display: inline }' + '#vt100 #keyboard .unshifted {' + 'display: none }'); } else { this.setTextContentRaw(style, ''); } var elems = this.keyboard.getElementsByTagName('I'); for (var i = 0; i < elems.length; ++i) { if (elems[i].id == '16') { elems[i].className = state ? 'selected' : ''; } } }; VT100.prototype.showCtrlState = function(state) { var ctrl = this.getChildById(this.keyboard, '17' /* Ctrl */); if (ctrl) { ctrl.className = state ? 'selected' : ''; } }; VT100.prototype.showAltState = function(state) { var alt = this.getChildById(this.keyboard, '18' /* Alt */); if (alt) { alt.className = state ? 'selected' : ''; } }; VT100.prototype.clickedKeyboard = function(e, elem, ch, key, shift, ctrl, alt){ var fake = [ ]; fake.charCode = ch; fake.keyCode = key; fake.ctrlKey = ctrl; fake.shiftKey = shift; fake.altKey = alt; fake.metaKey = alt; return this.handleKey(fake); }; VT100.prototype.addKeyBinding = function(elem, ch, key, CH, KEY) { if (elem == undefined) { return; } if (ch == '\u00A0') { // &nbsp; should be treated as a regular space character. ch = ' '; } if (ch != undefined && CH == undefined) { // For letter keys, we automatically compute the uppercase character code // from the lowercase one. CH = ch.toUpperCase(); } if (KEY == undefined && key != undefined) { // Most keys have identically key codes for both lowercase and uppercase // keypresses. Normally, only function keys would have distinct key codes, // whereas regular keys have character codes. KEY = key; } else if (KEY == undefined && CH != undefined) { // For regular keys, copy the character code to the key code. KEY = CH.charCodeAt(0); } if (key == undefined && ch != undefined) { // For regular keys, copy the character code to the key code. key = ch.charCodeAt(0); } // Convert characters to numeric character codes. If the character code // is undefined (i.e. this is a function key), set it to zero. ch = ch ? ch.charCodeAt(0) : 0; CH = CH ? CH.charCodeAt(0) : 0; // Mouse down events high light the key. We also set lastSelectedKey. This // is needed to that mouseout/mouseover can keep track of the key that // is currently being clicked. this.addListener(elem, 'mousedown', function(vt100, elem, key) { return function(e) { if ((e.which || e.button) == 1) { if (vt100.lastSelectedKey) { vt100.lastSelectedKey.className= ''; } // Highlight the key while the mouse button is held down. if (key == 16 /* Shift */) { if (!elem.className != vt100.isShift) { vt100.showShiftState(!vt100.isShift); } } else if (key == 17 /* Ctrl */) { if (!elem.className != vt100.isCtrl) { vt100.showCtrlState(!vt100.isCtrl); } } else if (key == 18 /* Alt */) { if (!elem.className != vt100.isAlt) { vt100.showAltState(!vt100.isAlt); } } else { elem.className = 'selected'; } vt100.lastSelectedKey = elem; } return false; }; }(this, elem, key)); var clicked = // Modifier keys update the state of the keyboard, but do not generate // any key clicks that get forwarded to the application. key >= 16 /* Shift */ && key <= 18 /* Alt */ ? function(vt100, elem) { return function(e) { if (elem == vt100.lastSelectedKey) { if (key == 16 /* Shift */) { // The user clicked the Shift key vt100.isShift = !vt100.isShift; vt100.showShiftState(vt100.isShift); } else if (key == 17 /* Ctrl */) { vt100.isCtrl = !vt100.isCtrl; vt100.showCtrlState(vt100.isCtrl); } else if (key == 18 /* Alt */) { vt100.isAlt = !vt100.isAlt; vt100.showAltState(vt100.isAlt); } vt100.lastSelectedKey = undefined; } if (vt100.lastSelectedKey) { vt100.lastSelectedKey.className = ''; vt100.lastSelectedKey = undefined; } return false; }; }(this, elem) : // Regular keys generate key clicks, when the mouse button is released or // when a mouse click event is received. function(vt100, elem, ch, key, CH, KEY) { return function(e) { if (vt100.lastSelectedKey) { if (elem == vt100.lastSelectedKey) { // The user clicked a key. if (vt100.isShift) { vt100.clickedKeyboard(e, elem, CH, KEY, true, vt100.isCtrl, vt100.isAlt); } else { vt100.clickedKeyboard(e, elem, ch, key, false, vt100.isCtrl, vt100.isAlt); } vt100.isShift = false; vt100.showShiftState(false); vt100.isCtrl = false; vt100.showCtrlState(false); vt100.isAlt = false; vt100.showAltState(false); } vt100.lastSelectedKey.className = ''; vt100.lastSelectedKey = undefined; } elem.className = ''; return false; }; }(this, elem, ch, key, CH, KEY); this.addListener(elem, 'mouseup', clicked); this.addListener(elem, 'click', clicked); // When moving the mouse away from a key, check if any keys need to be // deselected. this.addListener(elem, 'mouseout', function(vt100, elem, key) { return function(e) { if (key == 16 /* Shift */) { if (!elem.className == vt100.isShift) { vt100.showShiftState(vt100.isShift); } } else if (key == 17 /* Ctrl */) { if (!elem.className == vt100.isCtrl) { vt100.showCtrlState(vt100.isCtrl); } } else if (key == 18 /* Alt */) { if (!elem.className == vt100.isAlt) { vt100.showAltState(vt100.isAlt); } } else if (elem.className) { elem.className = ''; vt100.lastSelectedKey = elem; } else if (vt100.lastSelectedKey) { vt100.resetLastSelectedKey(e); } return false; }; }(this, elem, key)); // When moving the mouse over a key, select it if the user is still holding // the mouse button down (i.e. elem == lastSelectedKey) this.addListener(elem, 'mouseover', function(vt100, elem, key) { return function(e) { if (elem == vt100.lastSelectedKey) { if (key == 16 /* Shift */) { if (!elem.className != vt100.isShift) { vt100.showShiftState(!vt100.isShift); } } else if (key == 17 /* Ctrl */) { if (!elem.className != vt100.isCtrl) { vt100.showCtrlState(!vt100.isCtrl); } } else if (key == 18 /* Alt */) { if (!elem.className != vt100.isAlt) { vt100.showAltState(!vt100.isAlt); } } else if (!elem.className) { elem.className = 'selected'; } } else { vt100.resetLastSelectedKey(e); } return false; }; }(this, elem, key)); }; VT100.prototype.initializeKeyBindings = function(elem) { if (elem) { if (elem.nodeName == "I" || elem.nodeName == "B") { if (elem.id) { // Function keys. The Javascript keycode is part of the "id" var i = parseInt(elem.id); if (i) { // If the id does not parse as a number, it is not a keycode. this.addKeyBinding(elem, undefined, i); } } else { var child = elem.firstChild; if (child) { if (child.nodeName == "#text") { // If the key only has a text node as a child, then it is a letter. // Automatically compute the lower and upper case version of the // key. var text = this.getTextContent(child) || this.getTextContent(elem); this.addKeyBinding(elem, text.toLowerCase()); } else if (child.nextSibling) { // If the key has two children, they are the lower and upper case // character code, respectively. this.addKeyBinding(elem, this.getTextContent(child), undefined, this.getTextContent(child.nextSibling)); } } } } } // Recursively parse all other child nodes. for (elem = elem.firstChild; elem; elem = elem.nextSibling) { this.initializeKeyBindings(elem); } }; VT100.prototype.initializeKeyboardButton = function() { // Configure mouse event handlers for button that displays/hides keyboard this.addListener(this.keyboardImage, 'click', function(vt100) { return function(e) { if (vt100.keyboard.style.display != '') { if (vt100.reconnectBtn.style.visibility != '') { vt100.initializeKeyboard(); vt100.showSoftKeyboard(); } } else { vt100.hideSoftKeyboard(); vt100.input.focus(); } return false; }; }(this)); // Enable button that displays keyboard if (this.softKeyboard) { this.keyboardImage.style.visibility = 'visible'; } }; VT100.prototype.initializeKeyboard = function() { // Only need to initialize the keyboard the very first time. When doing so, // copy the keyboard layout from the iframe. if (this.keyboard.firstChild) { return; } this.keyboard.innerHTML = this.layout.contentDocument.body.innerHTML; var box = this.keyboard.firstChild; this.hideSoftKeyboard(); // Configure mouse event handlers for on-screen keyboard this.addListener(this.keyboard, 'click', function(vt100) { return function(e) { vt100.hideSoftKeyboard(); vt100.input.focus(); return false; }; }(this)); this.addListener(this.keyboard, 'selectstart', this.cancelEvent); this.addListener(box, 'click', this.cancelEvent); this.addListener(box, 'mouseup', function(vt100) { return function(e) { if (vt100.lastSelectedKey) { vt100.lastSelectedKey.className = ''; vt100.lastSelectedKey = undefined; } return false; }; }(this)); this.addListener(box, 'mouseout', function(vt100) { return function(e) { return vt100.resetLastSelectedKey(e); }; }(this)); this.addListener(box, 'mouseover', function(vt100) { return function(e) { return vt100.resetLastSelectedKey(e); }; }(this)); // Configure SHIFT key behavior var style = document.createElement('style'); var id = document.createAttribute('id'); id.nodeValue = 'shift_state'; style.setAttributeNode(id); var type = document.createAttribute('type'); type.nodeValue = 'text/css'; style.setAttributeNode(type); document.getElementsByTagName('head')[0].appendChild(style); // Set up key bindings this.initializeKeyBindings(box); }; VT100.prototype.initializeElements = function(container) { // If the necessary objects have not already been defined in the HTML // page, create them now. if (container) { this.container = container; } else if (!(this.container = document.getElementById('vt100'))) { this.container = document.createElement('div'); this.container.id = 'vt100'; document.body.appendChild(this.container); } if (!this.getChildById(this.container, 'reconnect') || !this.getChildById(this.container, 'menu') || !this.getChildById(this.container, 'keyboard') || !this.getChildById(this.container, 'kbd_button') || !this.getChildById(this.container, 'kbd_img') || !this.getChildById(this.container, 'layout') || !this.getChildById(this.container, 'scrollable') || !this.getChildById(this.container, 'console') || !this.getChildById(this.container, 'alt_console') || !this.getChildById(this.container, 'ieprobe') || !this.getChildById(this.container, 'padding') || !this.getChildById(this.container, 'cursor') || !this.getChildById(this.container, 'lineheight') || !this.getChildById(this.container, 'usercss') || !this.getChildById(this.container, 'space') || !this.getChildById(this.container, 'input') || !this.getChildById(this.container, 'cliphelper')) { // Only enable the "embed" object, if we have a suitable plugin. Otherwise, // we might get a pointless warning that a suitable plugin is not yet // installed. If in doubt, we'd rather just stay silent. var embed = ''; try { if (typeof navigator.mimeTypes["audio/x-wav"].enabledPlugin.name != 'undefined') { embed = typeof suppressAllAudio != 'undefined' && suppressAllAudio ? "" : '<embed classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" ' + 'id="beep_embed" ' + 'src="beep.wav" ' + 'autostart="false" ' + 'volume="100" ' + 'enablejavascript="true" ' + 'type="audio/x-wav" ' + 'height="16" ' + 'width="200" ' + 'style="position:absolute;left:-1000px;top:-1000px" />'; } } catch (e) { } this.container.innerHTML = '<div id="reconnect" style="visibility: hidden">' + '<input type="button" value="Connect" ' + 'onsubmit="return false" />' + '</div>' + '<div id="cursize" style="visibility: hidden">' + '</div>' + '<div id="menu"></div>' + '<div id="keyboard" unselectable="on">' + '</div>' + '<div id="scrollable">' + '<table id="kbd_button">' + '<tr><td width="100%">&nbsp;</td>' + '<td><img id="kbd_img" src="keyboard.png" /></td>' + '<td>&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>' + '</table>' + '<pre id="lineheight">&nbsp;</pre>' + '<pre id="console">' + '<pre></pre>' + '<div id="ieprobe"><span>&nbsp;</span></div>' + '</pre>' + '<pre id="alt_console" style="display: none"></pre>' + '<div id="padding"></div>' + '<pre id="cursor">&nbsp;</pre>' + '</div>' + '<div class="hidden">' + '<div id="usercss"></div>' + '<pre><div><span id="space"></span></div></pre>' + '<input type="textfield" id="input" />' + '<input type="textfield" id="cliphelper" />' + (typeof suppressAllAudio != 'undefined' && suppressAllAudio ? "" : embed + '<bgsound id="beep_bgsound" loop=1 />') + '<iframe id="layout" src="keyboard.html" />' + '</div>'; } // Find the object used for playing the "beep" sound, if any. if (typeof suppressAllAudio != 'undefined' && suppressAllAudio) { this.beeper = undefined; } else { this.beeper = this.getChildById(this.container, 'beep_embed'); if (!this.beeper || !this.beeper.Play) { this.beeper = this.getChildById(this.container, 'beep_bgsound'); if (!this.beeper || typeof this.beeper.src == 'undefined') { this.beeper = undefined; } } } // Initialize the variables for finding the text console and the // cursor. this.reconnectBtn = this.getChildById(this.container,'reconnect'); this.curSizeBox = this.getChildById(this.container, 'cursize'); this.menu = this.getChildById(this.container, 'menu'); this.keyboard = this.getChildById(this.container, 'keyboard'); this.keyboardImage = this.getChildById(this.container, 'kbd_img'); this.layout = this.getChildById(this.container, 'layout'); this.scrollable = this.getChildById(this.container, 'scrollable'); this.lineheight = this.getChildById(this.container, 'lineheight'); this.console = [ this.getChildById(this.container, 'console'), this.getChildById(this.container, 'alt_console') ]; var ieProbe = this.getChildById(this.container, 'ieprobe'); this.padding = this.getChildById(this.container, 'padding'); this.cursor = this.getChildById(this.container, 'cursor'); this.usercss = this.getChildById(this.container, 'usercss'); this.space = this.getChildById(this.container, 'space'); this.input = this.getChildById(this.container, 'input'); this.cliphelper = this.getChildById(this.container, 'cliphelper'); // Add any user selectable style sheets to the menu this.initializeUserCSSStyles(); // Remember the dimensions of a standard character glyph. We would // expect that we could just check cursor.clientWidth/Height at any time, // but it turns out that browsers sometimes invalidate these values // (e.g. while displaying a print preview screen). this.cursorWidth = this.cursor.clientWidth; this.cursorHeight = this.lineheight.clientHeight; // IE has a slightly different boxing model, that we need to compensate for this.isIE = ieProbe.offsetTop > 1; ieProbe = undefined; this.console.innerHTML = ''; // Determine if the terminal window is positioned at the beginning of the // page, or if it is embedded somewhere else in the page. For full-screen // terminals, automatically resize whenever the browser window changes. var marginTop = parseInt(this.getCurrentComputedStyle( document.body, 'marginTop')); var marginLeft = parseInt(this.getCurrentComputedStyle( document.body, 'marginLeft')); var marginRight = parseInt(this.getCurrentComputedStyle( document.body, 'marginRight')); var x = this.container.offsetLeft; var y = this.container.offsetTop; for (var parent = this.container; parent = parent.offsetParent; ) { x += parent.offsetLeft; y += parent.offsetTop; } this.isEmbedded = marginTop != y || marginLeft != x || (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) - marginRight != x + this.container.offsetWidth; if (!this.isEmbedded) { // Some browsers generate resize events when the terminal is first // shown. Disable showing the size indicator until a little bit after // the terminal has been rendered the first time. this.indicateSize = false; setTimeout(function(vt100) { return function() { vt100.indicateSize = true; }; }(this), 100); this.addListener(window, 'resize', function(vt100) { return function() { vt100.hideContextMenu(); vt100.resizer(); vt100.showCurrentSize(); } }(this)); // Hide extra scrollbars attached to window document.body.style.margin = '0px'; try { document.body.style.overflow ='hidden'; } catch (e) { } try { document.body.oncontextmenu = function() {return false;};} catch(e){} } // Set up onscreen soft keyboard this.initializeKeyboardButton(); // Hide context menu this.hideContextMenu(); // Add listener to reconnect button this.addListener(this.reconnectBtn.firstChild, 'click', function(vt100) { return function() { var rc = vt100.reconnect(); vt100.input.focus(); return rc; } }(this)); // Add input listeners this.addListener(this.input, 'blur', function(vt100) { return function() { vt100.blurCursor(); } }(this)); this.addListener(this.input, 'focus', function(vt100) { return function() { vt100.focusCursor(); } }(this)); this.addListener(this.input, 'keydown', function(vt100) { return function(e) { if (!e) e = window.event; return vt100.keyDown(e); } }(this)); this.addListener(this.input, 'keypress', function(vt100) { return function(e) { if (!e) e = window.event; return vt100.keyPressed(e); } }(this)); this.addListener(this.input, 'keyup', function(vt100) { return function(e) { if (!e) e = window.event; return vt100.keyUp(e); } }(this)); // Attach listeners that move the focus to the <input> field. This way we // can make sure that we can receive keyboard input. var mouseEvent = function(vt100, type) { return function(e) { if (!e) e = window.event; return vt100.mouseEvent(e, type); }; }; this.addListener(this.scrollable,'mousedown',mouseEvent(this, 0 /* MOUSE_DOWN */)); this.addListener(this.scrollable,'mouseup', mouseEvent(this, 1 /* MOUSE_UP */)); this.addListener(this.scrollable,'click', mouseEvent(this, 2 /* MOUSE_CLICK */)); // Initialize the blank terminal window. this.currentScreen = 0; this.cursorX = 0; this.cursorY = 0; this.numScrollbackLines = 0; this.top = 0; this.bottom = 0x7FFFFFFF; this.scale = 1.0; this.resizer(); this.focusCursor(); this.input.focus(); }; VT100.prototype.getChildById = function(parent, id) { var nodeList = parent.all || parent.getElementsByTagName('*'); if (typeof nodeList.namedItem == 'undefined') { for (var i = 0; i < nodeList.length; i++) { if (nodeList[i].id == id) { return nodeList[i]; } } return null; } else { var elem = (parent.all || parent.getElementsByTagName('*')).namedItem(id); return elem ? elem[0] || elem : null; } }; VT100.prototype.getCurrentComputedStyle = function(elem, style) { if (typeof elem.currentStyle != 'undefined') { return elem.currentStyle[style]; } else { return document.defaultView.getComputedStyle(elem, null)[style]; } }; VT100.prototype.reconnect = function() { return false; }; VT100.prototype.showReconnect = function(state) { if (state) { this.hideSoftKeyboard(); this.reconnectBtn.style.visibility = ''; } else { this.reconnectBtn.style.visibility = 'hidden'; } }; VT100.prototype.repairElements = function(console) { for (var line = console.firstChild; line; line = line.nextSibling) { if (!line.clientHeight) { var newLine = document.createElement(line.tagName); newLine.style.cssText = line.style.cssText; newLine.className = line.className; if (line.tagName == 'DIV') { for (var span = line.firstChild; span; span = span.nextSibling) { var newSpan = document.createElement(span.tagName); newSpan.style.cssText = span.style.cssText; newSpan.style.className = span.style.className; this.setTextContent(newSpan, this.getTextContent(span)); newLine.appendChild(newSpan); } } else { this.setTextContent(newLine, this.getTextContent(line)); } line.parentNode.replaceChild(newLine, line); line = newLine; } } }; VT100.prototype.resized = function(w, h) { }; VT100.prototype.resizer = function() { // Hide onscreen soft keyboard this.hideSoftKeyboard(); // The cursor can get corrupted if the print-preview is displayed in Firefox. // Recreating it, will repair it. var newCursor = document.createElement('pre'); this.setTextContent(newCursor, ' '); newCursor.id = 'cursor'; newCursor.style.cssText = this.cursor.style.cssText; this.cursor.parentNode.insertBefore(newCursor, this.cursor); if (!newCursor.clientHeight) { // Things are broken right now. This is probably because we are // displaying the print-preview. Just don't change any of our settings // until the print dialog is closed again. newCursor.parentNode.removeChild(newCursor); return; } else { // Swap the old broken cursor for the newly created one. this.cursor.parentNode.removeChild(this.cursor); this.cursor = newCursor; } // Really horrible things happen if the contents of the terminal changes // while the print-preview is showing. We get HTML elements that show up // in the DOM, but that do not take up any space. Find these elements and // try to fix them. this.repairElements(this.console[0]); this.repairElements(this.console[1]); // Lock the cursor size to the size of a normal character. This helps with // characters that are taller/shorter than normal. Unfortunately, we will // still get confused if somebody enters a character that is wider/narrower // than normal. This can happen if the browser tries to substitute a // characters from a different font. this.cursor.style.width = this.cursorWidth + 'px'; this.cursor.style.height = this.cursorHeight + 'px'; // Adjust height for one pixel padding of the #vt100 element. // The latter is necessary to properly display the inactive cursor. var console = this.console[this.currentScreen]; var height = (this.isEmbedded ? this.container.clientHeight : (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight))-1; var partial = height % this.cursorHeight; this.scrollable.style.height = (height > 0 ? height : 0) + 'px'; this.padding.style.height = (partial > 0 ? partial : 0) + 'px'; var oldTerminalHeight = this.terminalHeight; this.updateWidth(); this.updateHeight(); // Clip the cursor to the visible screen. var cx = this.cursorX; var cy = this.cursorY + this.numScrollbackLines; // The alternate screen never keeps a scroll back buffer. this.updateNumScrollbackLines(); while (this.currentScreen && this.numScrollbackLines > 0) { console.removeChild(console.firstChild); this.numScrollbackLines--; } cy -= this.numScrollbackLines; if (cx < 0) { cx = 0; } else if (cx > this.terminalWidth) { cx = this.terminalWidth - 1; if (cx < 0) { cx = 0; } } if (cy < 0) { cy = 0; } else if (cy > this.terminalHeight) { cy = this.terminalHeight - 1; if (cy < 0) { cy = 0; } } // Clip the scroll region to the visible screen. if (this.bottom > this.terminalHeight || this.bottom == oldTerminalHeight) { this.bottom = this.terminalHeight; } if (this.top >= this.bottom) { this.top = this.bottom-1; if (this.top < 0) { this.top = 0; } } // Truncate lines, if necessary. Explicitly reposition cursor (this is // particularly important after changing the screen number), and reset // the scroll region to the default. this.truncateLines(this.terminalWidth); this.putString(cx, cy, '', undefined); this.scrollable.scrollTop = this.numScrollbackLines * this.cursorHeight + 1; // Update classNames for lines in the scrollback buffer var line = console.firstChild; for (var i = 0; i < this.numScrollbackLines; i++) { line.className = 'scrollback'; line = line.nextSibling; } while (line) { line.className = ''; line = line.nextSibling; } // Reposition the reconnect button this.reconnectBtn.style.left = (this.terminalWidth*this.cursorWidth/ this.scale - this.reconnectBtn.clientWidth)/2 + 'px'; this.reconnectBtn.style.top = (this.terminalHeight*this.cursorHeight- this.reconnectBtn.clientHeight)/2 + 'px'; // Send notification that the window size has been changed this.resized(this.terminalWidth, this.terminalHeight); }; VT100.prototype.showCurrentSize = function() { if (!this.indicateSize) { return; } this.curSizeBox.innerHTML = '' + this.terminalWidth + 'x' + this.terminalHeight; this.curSizeBox.style.left = (this.terminalWidth*this.cursorWidth/ this.scale - this.curSizeBox.clientWidth)/2 + 'px'; this.curSizeBox.style.top = (this.terminalHeight*this.cursorHeight - this.curSizeBox.clientHeight)/2 + 'px'; this.curSizeBox.style.visibility = ''; if (this.curSizeTimeout) { clearTimeout(this.curSizeTimeout); } // Only show the terminal size for a short amount of time after resizing. // Then hide this information, again. Some browsers generate resize events // throughout the entire resize operation. This is nice, and we will show // the terminal size while the user is dragging the window borders. // Other browsers only generate a single event when the user releases the // mouse. In those cases, we can only show the terminal size once at the // end of the resize operation. this.curSizeTimeout = setTimeout(function(vt100) { return function() { vt100.curSizeTimeout = null; vt100.curSizeBox.style.visibility = 'hidden'; }; }(this), 1000); }; VT100.prototype.selection = function() { try { return '' + (window.getSelection && window.getSelection() || document.selection && document.selection.type == 'Text' && document.selection.createRange().text || ''); } catch (e) { } return ''; }; VT100.prototype.cancelEvent = function(event) { try { // For non-IE browsers event.stopPropagation(); event.preventDefault(); } catch (e) { } try { // For IE event.cancelBubble = true; event.returnValue = false; event.button = 0; event.keyCode = 0; } catch (e) { } return false; }; VT100.prototype.mousePosition = function(event) { var offsetX = this.container.offsetLeft; var offsetY = this.container.offsetTop; for (var e = this.container; e = e.offsetParent; ) { offsetX += e.offsetLeft; offsetY += e.offsetTop; } return [ event.clientX - offsetX, event.clientY - offsetY ]; }; VT100.prototype.mouseEvent = function(event, type) { // If any text is currently selected, do not move the focus as that would // invalidate the selection. var selection = this.selection(); if ((type == 1 /* MOUSE_UP */ || type == 2 /* MOUSE_CLICK */) && !selection.length) { this.input.focus(); } // Compute mouse position in characters. var position = this.mousePosition(event); var x = Math.floor(position[0] / this.cursorWidth); var y = Math.floor((position[1] + this.scrollable.scrollTop) / this.cursorHeight) - this.numScrollbackLines; var inside = true; if (x >= this.terminalWidth) { x = this.terminalWidth - 1; inside = false; } if (x < 0) { x = 0; inside = false; } if (y >= this.terminalHeight) { y = this.terminalHeight - 1; inside = false; } if (y < 0) { y = 0; inside = false; } // Compute button number and modifier keys. var button = type != 0 /* MOUSE_DOWN */ ? 3 : typeof event.pageX != 'undefined' ? event.button : [ undefined, 0, 2, 0, 1, 0, 1, 0 ][event.button]; if (button != undefined) { if (event.shiftKey) { button |= 0x04; } if (event.altKey || event.metaKey) { button |= 0x08; } if (event.ctrlKey) { button |= 0x10; } } // Report mouse events if they happen inside of the current screen and // with the SHIFT key unpressed. Both of these restrictions do not apply // for button releases, as we always want to report those. if (this.mouseReporting && !selection.length && (type != 0 /* MOUSE_DOWN */ || !event.shiftKey)) { if (inside || type != 0 /* MOUSE_DOWN */) { if (button != undefined) { var report = '\u001B[M' + String.fromCharCode(button + 32) + String.fromCharCode(x + 33) + String.fromCharCode(y + 33); if (type != 2 /* MOUSE_CLICK */) { this.keysPressed(report); } // If we reported the event, stop propagating it (not sure, if this // actually works on most browsers; blocking the global "oncontextmenu" // even is still necessary). return this.cancelEvent(event); } } } // Bring up context menu. if (button == 2 && !event.shiftKey) { if (type == 0 /* MOUSE_DOWN */) { this.showContextMenu(position[0], position[1]); } return this.cancelEvent(event); } if (this.mouseReporting) { try { event.shiftKey = false; } catch (e) { } } return true; }; VT100.prototype.replaceChar = function(s, ch, repl) { for (var i = -1;;) { i = s.indexOf(ch, i + 1); if (i < 0) { break; } s = s.substr(0, i) + repl + s.substr(i + 1); } return s; }; VT100.prototype.htmlEscape = function(s) { return this.replaceChar(this.replaceChar(this.replaceChar(this.replaceChar( s, '&', '&amp;'), '<', '&lt;'), '"', '&quot;'), ' ', '\u00A0'); }; VT100.prototype.getTextContent = function(elem) { return elem.textContent || (typeof elem.textContent == 'undefined' ? elem.innerText : ''); }; VT100.prototype.setTextContentRaw = function(elem, s) { // Updating the content of an element is an expensive operation. It actually // pays off to first check whether the element is still unchanged. if (typeof elem.textContent == 'undefined') { if (elem.innerText != s) { try { elem.innerText = s; } catch (e) { // Very old versions of IE do not allow setting innerText. Instead, // remove all children, by setting innerHTML and then set the text // using DOM methods. elem.innerHTML = ''; elem.appendChild(document.createTextNode( this.replaceChar(s, ' ', '\u00A0'))); } } } else { if (elem.textContent != s) { elem.textContent = s; } } }; VT100.prototype.setTextContent = function(elem, s) { // Check if we find any URLs in the text. If so, automatically convert them // to links. if (this.urlRE && this.urlRE.test(s)) { var inner = ''; for (;;) { var consumed = 0; if (RegExp.leftContext != null) { inner += this.htmlEscape(RegExp.leftContext); consumed += RegExp.leftContext.length; } var url = this.htmlEscape(RegExp.lastMatch); var fullUrl = url; // If no protocol was specified, try to guess a reasonable one. if (url.indexOf('http://') < 0 && url.indexOf('https://') < 0 && url.indexOf('ftp://') < 0 && url.indexOf('mailto:') < 0) { var slash = url.indexOf('/'); var at = url.indexOf('@'); var question = url.indexOf('?'); if (at > 0 && (at < question || question < 0) && (slash < 0 || (question > 0 && slash > question))) { fullUrl = 'mailto:' + url; } else { fullUrl = (url.indexOf('ftp.') == 0 ? 'ftp://' : 'http://') + url; } } inner += '<a target="vt100Link" href="' + fullUrl + '">' + url + '</a>'; consumed += RegExp.lastMatch.length; s = s.substr(consumed); if (!this.urlRE.test(s)) { if (RegExp.rightContext != null) { inner += this.htmlEscape(RegExp.rightContext); } break; } } elem.innerHTML = inner; return; } this.setTextContentRaw(elem, s); }; VT100.prototype.insertBlankLine = function(y, color, style) { // Insert a blank line a position y. This method ignores the scrollback // buffer. The caller has to add the length of the scrollback buffer to // the position, if necessary. // If the position is larger than the number of current lines, this // method just adds a new line right after the last existing one. It does // not add any missing lines in between. It is the caller's responsibility // to do so. if (!color) { color = 'ansi0 bgAnsi15'; } if (!style) { style = ''; } var line; if (color != 'ansi0 bgAnsi15' && !style) { line = document.createElement('pre'); this.setTextContent(line, '\n'); } else { line = document.createElement('div'); var span = document.createElement('span'); span.style.cssText = style; span.style.className = color; this.setTextContent(span, this.spaces(this.terminalWidth)); line.appendChild(span); } line.style.height = this.cursorHeight + 'px'; var console = this.console[this.currentScreen]; if (console.childNodes.length > y) { console.insertBefore(line, console.childNodes[y]); } else { console.appendChild(line); } }; VT100.prototype.updateWidth = function() { this.terminalWidth = Math.floor(this.console[this.currentScreen].offsetWidth/ this.cursorWidth*this.scale); return this.terminalWidth; }; VT100.prototype.updateHeight = function() { // We want to be able to display either a terminal window that fills the // entire browser window, or a terminal window that is contained in a // <div> which is embededded somewhere in the web page. if (this.isEmbedded) { // Embedded terminal. Use size of the containing <div> (id="vt100"). this.terminalHeight = Math.floor((this.container.clientHeight-1) / this.cursorHeight); } else { // Use the full browser window. this.terminalHeight = Math.floor(((window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight)-1)/ this.cursorHeight); } return this.terminalHeight; }; VT100.prototype.updateNumScrollbackLines = function() { var scrollback = Math.floor( this.console[this.currentScreen].offsetHeight / this.cursorHeight) - this.terminalHeight; this.numScrollbackLines = scrollback < 0 ? 0 : scrollback; return this.numScrollbackLines; }; VT100.prototype.truncateLines = function(width) { if (width < 0) { width = 0; } for (var line = this.console[this.currentScreen].firstChild; line; line = line.nextSibling) { if (line.tagName == 'DIV') { var x = 0; // Traverse current line and truncate it once we saw "width" characters for (var span = line.firstChild; span; span = span.nextSibling) { var s = this.getTextContent(span); var l = s.length; if (x + l > width) { this.setTextContent(span, s.substr(0, width - x)); while (span.nextSibling) { line.removeChild(line.lastChild); } break; } x += l; } // Prune white space from the end of the current line var span = line.lastChild; while (span && span.className == 'ansi0 bgAnsi15' && !span.style.cssText.length) { // Scan backwards looking for first non-space character var s = this.getTextContent(span); for (var i = s.length; i--; ) { if (s.charAt(i) != ' ' && s.charAt(i) != '\u00A0') { if (i+1 != s.length) { this.setTextContent(s.substr(0, i+1)); } span = null; break; } } if (span) { var sibling = span; span = span.previousSibling; if (span) { // Remove blank <span>'s from end of line line.removeChild(sibling); } else { // Remove entire line (i.e. <div>), if empty var blank = document.createElement('pre'); blank.style.height = this.cursorHeight + 'px'; this.setTextContent(blank, '\n'); line.parentNode.replaceChild(blank, line); } } } } } }; VT100.prototype.putString = function(x, y, text, color, style) { if (!color) { color = 'ansi0 bgAnsi15'; } if (!style) { style = ''; } var yIdx = y + this.numScrollbackLines; var line; var sibling; var s; var span; var xPos = 0; var console = this.console[this.currentScreen]; if (!text.length && (yIdx >= console.childNodes.length || console.childNodes[yIdx].tagName != 'DIV')) { // Positioning cursor to a blank location span = null; } else { // Create missing blank lines at end of page while (console.childNodes.length <= yIdx) { // In order to simplify lookups, we want to make sure that each line // is represented by exactly one element (and possibly a whole bunch of // children). // For non-blank lines, we can create a <div> containing one or more // <span>s. For blank lines, this fails as browsers tend to optimize them // away. But fortunately, a <pre> tag containing a newline character // appears to work for all browsers (a &nbsp; would also work, but then // copying from the browser window would insert superfluous spaces into // the clipboard). this.insertBlankLine(yIdx); } line = console.childNodes[yIdx]; // If necessary, promote blank '\n' line to a <div> tag if (line.tagName != 'DIV') { var div = document.createElement('div'); div.style.height = this.cursorHeight + 'px'; div.innerHTML = '<span></span>'; console.replaceChild(div, line); line = div; } // Scan through list of <span>'s until we find the one where our text // starts span = line.firstChild; var len; while (span.nextSibling && xPos < x) { len = this.getTextContent(span).length; if (xPos + len > x) { break; } xPos += len; span = span.nextSibling; } if (text.length) { // If current <span> is not long enough, pad with spaces or add new // span s = this.getTextContent(span); var oldColor = span.className; var oldStyle = span.style.cssText; if (xPos + s.length < x) { if (oldColor != 'ansi0 bgAnsi15' || oldStyle != '') { span = document.createElement('span'); line.appendChild(span); span.className = 'ansi0 bgAnsi15'; span.style.cssText = ''; oldColor = 'ansi0 bgAnsi15'; oldStyle = ''; xPos += s.length; s = ''; } do { s += ' '; } while (xPos + s.length < x); } // If styles do not match, create a new <span> var del = text.length - s.length + x - xPos; if (oldColor != color || (oldStyle != style && (oldStyle || style))) { if (xPos == x) { // Replacing text at beginning of existing <span> if (text.length >= s.length) { // New text is equal or longer than existing text s = text; } else { // Insert new <span> before the current one, then remove leading // part of existing <span>, adjust style of new <span>, and finally // set its contents sibling = document.createElement('span'); line.insertBefore(sibling, span); this.setTextContent(span, s.substr(text.length)); span = sibling; s = text; } } else { // Replacing text some way into the existing <span> var remainder = s.substr(x + text.length - xPos); this.setTextContent(span, s.substr(0, x - xPos)); xPos = x; sibling = document.createElement('span'); if (span.nextSibling) { line.insertBefore(sibling, span.nextSibling); span = sibling; if (remainder.length) { sibling = document.createElement('span'); sibling.className = oldColor; sibling.style.cssText = oldStyle; this.setTextContent(sibling, remainder); line.insertBefore(sibling, span.nextSibling); } } else { line.appendChild(sibling); span = sibling; if (remainder.length) { sibling = document.createElement('span'); sibling.className = oldColor; sibling.style.cssText = oldStyle; this.setTextContent(sibling, remainder); line.appendChild(sibling); } } s = text; } span.className = color; span.style.cssText = style; } else { // Overwrite (partial) <span> with new text s = s.substr(0, x - xPos) + text + s.substr(x + text.length - xPos); } this.setTextContent(span, s); // Delete all subsequent <span>'s that have just been overwritten sibling = span.nextSibling; while (del > 0 && sibling) { s = this.getTextContent(sibling); len = s.length; if (len <= del) { line.removeChild(sibling); del -= len; sibling = span.nextSibling; } else { this.setTextContent(sibling, s.substr(del)); break; } } // Merge <span> with next sibling, if styles are identical if (sibling && span.className == sibling.className && span.style.cssText == sibling.style.cssText) { this.setTextContent(span, this.getTextContent(span) + this.getTextContent(sibling)); line.removeChild(sibling); } } } // Position cursor this.cursorX = x + text.length; if (this.cursorX >= this.terminalWidth) { this.cursorX = this.terminalWidth - 1; if (this.cursorX < 0) { this.cursorX = 0; } } var pixelX = -1; var pixelY = -1; if (!this.cursor.style.visibility) { var idx = this.cursorX - xPos; if (span) { // If we are in a non-empty line, take the cursor Y position from the // other elements in this line. If dealing with broken, non-proportional // fonts, this is likely to yield better results. pixelY = span.offsetTop + span.offsetParent.offsetTop; s = this.getTextContent(span); var nxtIdx = idx - s.length; if (nxtIdx < 0) { this.setTextContent(this.cursor, s.charAt(idx)); pixelX = span.offsetLeft + idx*span.offsetWidth / s.length; } else { if (nxtIdx == 0) { pixelX = span.offsetLeft + span.offsetWidth; } if (span.nextSibling) { s = this.getTextContent(span.nextSibling); this.setTextContent(this.cursor, s.charAt(nxtIdx)); if (pixelX < 0) { pixelX = span.nextSibling.offsetLeft + nxtIdx*span.offsetWidth / s.length; } } else { this.setTextContent(this.cursor, ' '); } } } else { this.setTextContent(this.cursor, ' '); } } if (pixelX >= 0) { this.cursor.style.left = (pixelX + (this.isIE ? 1 : 0))/ this.scale + 'px'; } else { this.setTextContent(this.space, this.spaces(this.cursorX)); this.cursor.style.left = (this.space.offsetWidth + console.offsetLeft)/this.scale + 'px'; } this.cursorY = yIdx - this.numScrollbackLines; if (pixelY >= 0) { this.cursor.style.top = pixelY + 'px'; } else { this.cursor.style.top = yIdx*this.cursorHeight + console.offsetTop + 'px'; } if (text.length) { // Merge <span> with previous sibling, if styles are identical if ((sibling = span.previousSibling) && span.className == sibling.className && span.style.cssText == sibling.style.cssText) { this.setTextContent(span, this.getTextContent(sibling) + this.getTextContent(span)); line.removeChild(sibling); } // Prune white space from the end of the current line span = line.lastChild; while (span && span.className == 'ansi0 bgAnsi15' && !span.style.cssText.length) { // Scan backwards looking for first non-space character s = this.getTextContent(span); for (var i = s.length; i--; ) { if (s.charAt(i) != ' ' && s.charAt(i) != '\u00A0') { if (i+1 != s.length) { this.setTextContent(s.substr(0, i+1)); } span = null; break; } } if (span) { sibling = span; span = span.previousSibling; if (span) { // Remove blank <span>'s from end of line line.removeChild(sibling); } else { // Remove entire line (i.e. <div>), if empty var blank = document.createElement('pre'); blank.style.height = this.cursorHeight + 'px'; this.setTextContent(blank, '\n'); line.parentNode.replaceChild(blank, line); } } } } }; VT100.prototype.gotoXY = function(x, y) { if (x >= this.terminalWidth) { x = this.terminalWidth - 1; } if (x < 0) { x = 0; } var minY, maxY; if (this.offsetMode) { minY = this.top; maxY = this.bottom; } else { minY = 0; maxY = this.terminalHeight; } if (y >= maxY) { y = maxY - 1; } if (y < minY) { y = minY; } this.putString(x, y, '', undefined); this.needWrap = false; }; VT100.prototype.gotoXaY = function(x, y) { this.gotoXY(x, this.offsetMode ? (this.top + y) : y); }; VT100.prototype.refreshInvertedState = function() { if (this.isInverted) { this.scrollable.className += ' inverted'; } else { this.scrollable.className = this.scrollable.className. replace(/ *inverted/, ''); } }; VT100.prototype.enableAlternateScreen = function(state) { // Don't do anything, if we are already on the desired screen if ((state ? 1 : 0) == this.currentScreen) { // Calling the resizer is not actually necessary. But it is a good way // of resetting state that might have gotten corrupted. this.resizer(); return; } // We save the full state of the normal screen, when we switch away from it. // But for the alternate screen, no saving is necessary. We always reset // it when we switch to it. if (state) { this.saveCursor(); } // Display new screen, and initialize state (the resizer does that for us). this.currentScreen = state ? 1 : 0; this.console[1-this.currentScreen].style.display = 'none'; this.console[this.currentScreen].style.display = ''; // Select appropriate character pitch. var transform = this.getTransformName(); if (transform) { if (state) { // Upon enabling the alternate screen, we switch to 80 column mode. But // upon returning to the regular screen, we restore the mode that was // in effect previously. this.console[1].style[transform] = ''; } var style = this.console[this.currentScreen].style[transform]; this.cursor.style[transform] = style; this.space.style[transform] = style; this.scale = style == '' ? 1.0:1.65; if (transform == 'filter') { this.console[this.currentScreen].style.width = style == '' ? '165%':''; } } this.resizer(); // If we switched to the alternate screen, reset it completely. Otherwise, // restore the saved state. if (state) { this.gotoXY(0, 0); this.clearRegion(0, 0, this.terminalWidth, this.terminalHeight); } else { this.restoreCursor(); } }; VT100.prototype.hideCursor = function() { var hidden = this.cursor.style.visibility == 'hidden'; if (!hidden) { this.cursor.style.visibility = 'hidden'; return true; } return false; }; VT100.prototype.showCursor = function(x, y) { if (this.cursor.style.visibility) { this.cursor.style.visibility = ''; this.putString(x == undefined ? this.cursorX : x, y == undefined ? this.cursorY : y, '', undefined); return true; } return false; }; VT100.prototype.scrollBack = function() { var i = this.scrollable.scrollTop - this.scrollable.clientHeight; this.scrollable.scrollTop = i < 0 ? 0 : i; }; VT100.prototype.scrollFore = function() { var i = this.scrollable.scrollTop + this.scrollable.clientHeight; this.scrollable.scrollTop = i > this.numScrollbackLines * this.cursorHeight + 1 ? this.numScrollbackLines * this.cursorHeight + 1 : i; }; VT100.prototype.spaces = function(i) { var s = ''; while (i-- > 0) { s += ' '; } return s; }; VT100.prototype.clearRegion = function(x, y, w, h, color, style) { w += x; if (x < 0) { x = 0; } if (w > this.terminalWidth) { w = this.terminalWidth; } if ((w -= x) <= 0) { return; } h += y; if (y < 0) { y = 0; } if (h > this.terminalHeight) { h = this.terminalHeight; } if ((h -= y) <= 0) { return; } // Special case the situation where we clear the entire screen, and we do // not have a scrollback buffer. In that case, we should just remove all // child nodes. if (!this.numScrollbackLines && w == this.terminalWidth && h == this.terminalHeight && (color == undefined || color == 'ansi0 bgAnsi15') && !style) { var console = this.console[this.currentScreen]; while (console.lastChild) { console.removeChild(console.lastChild); } this.putString(this.cursorX, this.cursorY, '', undefined); } else { var hidden = this.hideCursor(); var cx = this.cursorX; var cy = this.cursorY; var s = this.spaces(w); for (var i = y+h; i-- > y; ) { this.putString(x, i, s, color, style); } hidden ? this.showCursor(cx, cy) : this.putString(cx, cy, '', undefined); } }; VT100.prototype.copyLineSegment = function(dX, dY, sX, sY, w) { var text = [ ]; var className = [ ]; var style = [ ]; var console = this.console[this.currentScreen]; if (sY >= console.childNodes.length) { text[0] = this.spaces(w); className[0] = undefined; style[0] = undefined; } else { var line = console.childNodes[sY]; if (line.tagName != 'DIV' || !line.childNodes.length) { text[0] = this.spaces(w); className[0] = undefined; style[0] = undefined; } else { var x = 0; for (var span = line.firstChild; span && w > 0; span = span.nextSibling){ var s = this.getTextContent(span); var len = s.length; if (x + len > sX) { var o = sX > x ? sX - x : 0; text[text.length] = s.substr(o, w); className[className.length] = span.className; style[style.length] = span.style.cssText; w -= len - o; } x += len; } if (w > 0) { text[text.length] = this.spaces(w); className[className.length] = undefined; style[style.length] = undefined; } } } var hidden = this.hideCursor(); var cx = this.cursorX; var cy = this.cursorY; for (var i = 0; i < text.length; i++) { var color; if (className[i]) { color = className[i]; } else { color = 'ansi0 bgAnsi15'; } this.putString(dX, dY - this.numScrollbackLines, text[i], color, style[i]); dX += text[i].length; } hidden ? this.showCursor(cx, cy) : this.putString(cx, cy, '', undefined); }; VT100.prototype.scrollRegion = function(x, y, w, h, incX, incY, color, style) { var left = incX < 0 ? -incX : 0; var right = incX > 0 ? incX : 0; var up = incY < 0 ? -incY : 0; var down = incY > 0 ? incY : 0; // Clip region against terminal size var dontScroll = null; w += x; if (x < left) { x = left; } if (w > this.terminalWidth - right) { w = this.terminalWidth - right; } if ((w -= x) <= 0) { dontScroll = 1; } h += y; if (y < up) { y = up; } if (h > this.terminalHeight - down) { h = this.terminalHeight - down; } if ((h -= y) < 0) { dontScroll = 1; } if (!dontScroll) { if (style && style.indexOf('underline')) { // Different terminal emulators disagree on the attributes that // are used for scrolling. The consensus seems to be, never to // fill with underlined spaces. N.B. this is different from the // cases when the user blanks a region. User-initiated blanking // always fills with all of the current attributes. style = style.replace(/text-decoration:underline;/, ''); } // Compute current scroll position var scrollPos = this.numScrollbackLines - (this.scrollable.scrollTop-1) / this.cursorHeight; // Determine original cursor position. Hide cursor temporarily to avoid // visual artifacts. var hidden = this.hideCursor(); var cx = this.cursorX; var cy = this.cursorY; var console = this.console[this.currentScreen]; if (!incX && !x && w == this.terminalWidth) { // Scrolling entire lines if (incY < 0) { // Scrolling up if (!this.currentScreen && y == -incY && h == this.terminalHeight + incY) { // Scrolling up with adding to the scrollback buffer. This is only // possible if there are at least as many lines in the console, // as the terminal is high while (console.childNodes.length < this.terminalHeight) { this.insertBlankLine(this.terminalHeight); } // Add new lines at bottom in order to force scrolling for (var i = 0; i < y; i++) { this.insertBlankLine(console.childNodes.length, color, style); } // Adjust the number of lines in the scrollback buffer by // removing excess entries. this.updateNumScrollbackLines(); while (this.numScrollbackLines > (this.currentScreen ? 0 : this.maxScrollbackLines)) { console.removeChild(console.firstChild); this.numScrollbackLines--; } // Mark lines in the scrollback buffer, so that they do not get // printed. for (var i = this.numScrollbackLines, j = -incY; i-- > 0 && j-- > 0; ) { console.childNodes[i].className = 'scrollback'; } } else { // Scrolling up without adding to the scrollback buffer. for (var i = -incY; i-- > 0 && console.childNodes.length > this.numScrollbackLines + y + incY; ) { console.removeChild(console.childNodes[ this.numScrollbackLines + y + incY]); } // If we used to have a scrollback buffer, then we must make sure // that we add back blank lines at the bottom of the terminal. // Similarly, if we are scrolling in the middle of the screen, // we must add blank lines to ensure that the bottom of the screen // does not move up. if (this.numScrollbackLines > 0 || console.childNodes.length > this.numScrollbackLines+y+h+incY) { for (var i = -incY; i-- > 0; ) { this.insertBlankLine(this.numScrollbackLines + y + h + incY, color, style); } } } } else { // Scrolling down for (var i = incY; i-- > 0 && console.childNodes.length > this.numScrollbackLines + y + h; ) { console.removeChild(console.childNodes[this.numScrollbackLines+y+h]); } for (var i = incY; i--; ) { this.insertBlankLine(this.numScrollbackLines + y, color, style); } } } else { // Scrolling partial lines if (incY <= 0) { // Scrolling up or horizontally within a line for (var i = y + this.numScrollbackLines; i < y + this.numScrollbackLines + h; i++) { this.copyLineSegment(x + incX, i + incY, x, i, w); } } else { // Scrolling down for (var i = y + this.numScrollbackLines + h; i-- > y + this.numScrollbackLines; ) { this.copyLineSegment(x + incX, i + incY, x, i, w); } } // Clear blank regions if (incX > 0) { this.clearRegion(x, y, incX, h, color, style); } else if (incX < 0) { this.clearRegion(x + w + incX, y, -incX, h, color, style); } if (incY > 0) { this.clearRegion(x, y, w, incY, color, style); } else if (incY < 0) { this.clearRegion(x, y + h + incY, w, -incY, color, style); } } // Reset scroll position this.scrollable.scrollTop = (this.numScrollbackLines-scrollPos) * this.cursorHeight + 1; // Move cursor back to its original position hidden ? this.showCursor(cx, cy) : this.putString(cx, cy, '', undefined); } }; VT100.prototype.copy = function(selection) { if (selection == undefined) { selection = this.selection(); } this.internalClipboard = undefined; if (selection.length) { try { // IE this.cliphelper.value = selection; this.cliphelper.select(); this.cliphelper.createTextRange().execCommand('copy'); } catch (e) { this.internalClipboard = selection; } this.cliphelper.value = ''; } }; VT100.prototype.copyLast = function() { // Opening the context menu can remove the selection. We try to prevent this // from happening, but that is not possible for all browsers. So, instead, // we compute the selection before showing the menu. this.copy(this.lastSelection); }; VT100.prototype.pasteFnc = function() { var clipboard = undefined; if (this.internalClipboard != undefined) { clipboard = this.internalClipboard; } else { try { this.cliphelper.value = ''; this.cliphelper.createTextRange().execCommand('paste'); clipboard = this.cliphelper.value; } catch (e) { } } this.cliphelper.value = ''; if (clipboard && this.menu.style.visibility == 'hidden') { return function() { this.keysPressed('' + clipboard); }; } else { return undefined; } }; VT100.prototype.toggleUTF = function() { this.utfEnabled = !this.utfEnabled; // We always persist the last value that the user selected. Not necessarily // the last value that a random program requested. this.utfPreferred = this.utfEnabled; }; VT100.prototype.toggleBell = function() { this.visualBell = !this.visualBell; }; VT100.prototype.toggleSoftKeyboard = function() { this.softKeyboard = !this.softKeyboard; this.keyboardImage.style.visibility = this.softKeyboard ? 'visible' : ''; }; VT100.prototype.deselectKeys = function(elem) { if (elem && elem.className == 'selected') { elem.className = ''; } for (elem = elem.firstChild; elem; elem = elem.nextSibling) { this.deselectKeys(elem); } }; VT100.prototype.showSoftKeyboard = function() { // Make sure no key is currently selected this.lastSelectedKey = undefined; this.deselectKeys(this.keyboard); this.isShift = false; this.showShiftState(false); this.isCtrl = false; this.showCtrlState(false); this.isAlt = false; this.showAltState(false); this.keyboard.style.left = '0px'; this.keyboard.style.top = '0px'; this.keyboard.style.width = this.container.offsetWidth + 'px'; this.keyboard.style.height = this.container.offsetHeight + 'px'; this.keyboard.style.visibility = 'hidden'; this.keyboard.style.display = ''; var kbd = this.keyboard.firstChild; var scale = 1.0; var transform = this.getTransformName(); if (transform) { kbd.style[transform] = ''; if (kbd.offsetWidth > 0.9 * this.container.offsetWidth) { scale = (kbd.offsetWidth/ this.container.offsetWidth)/0.9; } if (kbd.offsetHeight > 0.9 * this.container.offsetHeight) { scale = Math.max((kbd.offsetHeight/ this.container.offsetHeight)/0.9); } var style = this.getTransformStyle(transform, scale > 1.0 ? scale : undefined); kbd.style[transform] = style; } if (transform == 'filter') { scale = 1.0; } kbd.style.left = ((this.container.offsetWidth - kbd.offsetWidth/scale)/2) + 'px'; kbd.style.top = ((this.container.offsetHeight - kbd.offsetHeight/scale)/2) + 'px'; this.keyboard.style.visibility = 'visible'; }; VT100.prototype.hideSoftKeyboard = function() { this.keyboard.style.display = 'none'; }; VT100.prototype.toggleCursorBlinking = function() { this.blinkingCursor = !this.blinkingCursor; }; VT100.prototype.about = function() { alert("VT100 Terminal Emulator " + "2.10 (revision 239)" + "\nCopyright 2008-2010 by Markus Gutschke\n" + "For more information check http://shellinabox.com"); }; VT100.prototype.hideContextMenu = function() { this.menu.style.visibility = 'hidden'; this.menu.style.top = '-100px'; this.menu.style.left = '-100px'; this.menu.style.width = '0px'; this.menu.style.height = '0px'; }; VT100.prototype.extendContextMenu = function(entries, actions) { }; VT100.prototype.showContextMenu = function(x, y) { this.menu.innerHTML = '<table class="popup" ' + 'cellpadding="0" cellspacing="0">' + '<tr><td>' + '<ul id="menuentries">' + '<li id="beginclipboard">Copy</li>' + '<li id="endclipboard">Paste</li>' + '<hr />' + '<li id="reset">Reset</li>' + '<hr />' + '<li id="beginconfig">' + (this.utfEnabled ? '<img src="enabled.gif" />' : '') + 'Unicode</li>' + '<li>' + (this.visualBell ? '<img src="enabled.gif" />' : '') + 'Visual Bell</li>'+ '<li>' + (this.softKeyboard ? '<img src="enabled.gif" />' : '') + 'Onscreen Keyboard</li>' + '<li id="endconfig">' + (this.blinkingCursor ? '<img src="enabled.gif" />' : '') + 'Blinking Cursor</li>'+ (this.usercss.firstChild ? '<hr id="beginusercss" />' + this.usercss.innerHTML + '<hr id="endusercss" />' : '<hr />') + '<li id="about">About...</li>' + '</ul>' + '</td></tr>' + '</table>'; var popup = this.menu.firstChild; var menuentries = this.getChildById(popup, 'menuentries'); // Determine menu entries that should be disabled this.lastSelection = this.selection(); if (!this.lastSelection.length) { menuentries.firstChild.className = 'disabled'; } var p = this.pasteFnc(); if (!p) { menuentries.childNodes[1].className = 'disabled'; } // Actions for default items var actions = [ this.copyLast, p, this.reset, this.toggleUTF, this.toggleBell, this.toggleSoftKeyboard, this.toggleCursorBlinking ]; // Actions for user CSS styles (if any) for (var i = 0; i < this.usercssActions.length; ++i) { actions[actions.length] = this.usercssActions[i]; } actions[actions.length] = this.about; // Allow subclasses to dynamically add entries to the context menu this.extendContextMenu(menuentries, actions); // Hook up event listeners for (var node = menuentries.firstChild, i = 0; node; node = node.nextSibling) { if (node.tagName == 'LI') { if (node.className != 'disabled') { this.addListener(node, 'mouseover', function(vt100, node) { return function() { node.className = 'hover'; } }(this, node)); this.addListener(node, 'mouseout', function(vt100, node) { return function() { node.className = ''; } }(this, node)); this.addListener(node, 'mousedown', function(vt100, action) { return function(event) { vt100.hideContextMenu(); action.call(vt100); vt100.storeUserSettings(); return vt100.cancelEvent(event || window.event); } }(this, actions[i])); this.addListener(node, 'mouseup', function(vt100) { return function(event) { return vt100.cancelEvent(event || window.event); } }(this)); this.addListener(node, 'mouseclick', function(vt100) { return function(event) { return vt100.cancelEvent(event || window.event); } }()); } i++; } } // Position menu next to the mouse pointer this.menu.style.left = '0px'; this.menu.style.top = '0px'; this.menu.style.width = this.container.offsetWidth + 'px'; this.menu.style.height = this.container.offsetHeight + 'px'; popup.style.left = '0px'; popup.style.top = '0px'; var margin = 2; if (x + popup.clientWidth >= this.container.offsetWidth - margin) { x = this.container.offsetWidth-popup.clientWidth - margin - 1; } if (x < margin) { x = margin; } if (y + popup.clientHeight >= this.container.offsetHeight - margin) { y = this.container.offsetHeight-popup.clientHeight - margin - 1; } if (y < margin) { y = margin; } popup.style.left = x + 'px'; popup.style.top = y + 'px'; // Block all other interactions with the terminal emulator this.addListener(this.menu, 'click', function(vt100) { return function() { vt100.hideContextMenu(); } }(this)); // Show the menu this.menu.style.visibility = ''; }; VT100.prototype.keysPressed = function(ch) { for (var i = 0; i < ch.length; i++) { var c = ch.charCodeAt(i); this.vt100(c >= 7 && c <= 15 || c == 24 || c == 26 || c == 27 || c >= 32 ? String.fromCharCode(c) : '<' + c + '>'); } }; VT100.prototype.applyModifiers = function(ch, event) { if (ch) { if (event.ctrlKey) { if (ch >= 32 && ch <= 127) { // For historic reasons, some control characters are treated specially switch (ch) { case /* 3 */ 51: ch = 27; break; case /* 4 */ 52: ch = 28; break; case /* 5 */ 53: ch = 29; break; case /* 6 */ 54: ch = 30; break; case /* 7 */ 55: ch = 31; break; case /* 8 */ 56: ch = 127; break; case /* ? */ 63: ch = 127; break; default: ch &= 31; break; } } } return String.fromCharCode(ch); } else { return undefined; } }; VT100.prototype.handleKey = function(event) { // this.vt100('H: c=' + event.charCode + ', k=' + event.keyCode + // (event.shiftKey || event.ctrlKey || event.altKey || // event.metaKey ? ', ' + // (event.shiftKey ? 'S' : '') + (event.ctrlKey ? 'C' : '') + // (event.altKey ? 'A' : '') + (event.metaKey ? 'M' : '') : '') + // '\r\n'); var ch, key; if (typeof event.charCode != 'undefined') { // non-IE keypress events have a translated charCode value. Also, our // fake events generated when receiving keydown events include this data // on all browsers. ch = event.charCode; key = event.keyCode; } else { // When sending a keypress event, IE includes the translated character // code in the keyCode field. ch = event.keyCode; key = undefined; } // Apply modifier keys (ctrl and shift) if (ch) { key = undefined; } ch = this.applyModifiers(ch, event); // By this point, "ch" is either defined and contains the character code, or // it is undefined and "key" defines the code of a function key if (ch != undefined) { this.scrollable.scrollTop = this.numScrollbackLines * this.cursorHeight + 1; } else { if ((event.altKey || event.metaKey) && !event.shiftKey && !event.ctrlKey) { // Many programs have difficulties dealing with parametrized escape // sequences for function keys. Thus, if ALT is the only modifier // key, return Emacs-style keycodes for commonly used keys. switch (key) { case 33: /* Page Up */ ch = '\u001B<'; break; case 34: /* Page Down */ ch = '\u001B>'; break; case 37: /* Left */ ch = '\u001Bb'; break; case 38: /* Up */ ch = '\u001Bp'; break; case 39: /* Right */ ch = '\u001Bf'; break; case 40: /* Down */ ch = '\u001Bn'; break; case 46: /* Delete */ ch = '\u001Bd'; break; default: break; } } else if (event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey) { switch (key) { case 33: /* Page Up */ this.scrollBack(); return; case 34: /* Page Down */ this.scrollFore(); return; default: break; } } if (ch == undefined) { switch (key) { case 8: /* Backspace */ ch = '\u007f'; break; case 9: /* Tab */ ch = '\u0009'; break; case 10: /* Return */ ch = '\u000A'; break; case 13: /* Enter */ ch = this.crLfMode ? '\r\n' : '\r'; break; case 16: /* Shift */ return; case 17: /* Ctrl */ return; case 18: /* Alt */ return; case 19: /* Break */ return; case 20: /* Caps Lock */ return; case 27: /* Escape */ ch = '\u001B'; break; case 33: /* Page Up */ ch = '\u001B[5~'; break; case 34: /* Page Down */ ch = '\u001B[6~'; break; case 35: /* End */ ch = '\u001BOF'; break; case 36: /* Home */ ch = '\u001BOH'; break; case 37: /* Left */ ch = this.cursorKeyMode ? '\u001BOD' : '\u001B[D'; break; case 38: /* Up */ ch = this.cursorKeyMode ? '\u001BOA' : '\u001B[A'; break; case 39: /* Right */ ch = this.cursorKeyMode ? '\u001BOC' : '\u001B[C'; break; case 40: /* Down */ ch = this.cursorKeyMode ? '\u001BOB' : '\u001B[B'; break; case 45: /* Insert */ ch = '\u001B[2~'; break; case 46: /* Delete */ ch = '\u001B[3~'; break; case 91: /* Left Window */ return; case 92: /* Right Window */ return; case 93: /* Select */ return; case 96: /* 0 */ ch = this.applyModifiers(48, event); break; case 97: /* 1 */ ch = this.applyModifiers(49, event); break; case 98: /* 2 */ ch = this.applyModifiers(50, event); break; case 99: /* 3 */ ch = this.applyModifiers(51, event); break; case 100: /* 4 */ ch = this.applyModifiers(52, event); break; case 101: /* 5 */ ch = this.applyModifiers(53, event); break; case 102: /* 6 */ ch = this.applyModifiers(54, event); break; case 103: /* 7 */ ch = this.applyModifiers(55, event); break; case 104: /* 8 */ ch = this.applyModifiers(56, event); break; case 105: /* 9 */ ch = this.applyModifiers(58, event); break; case 106: /* * */ ch = this.applyModifiers(42, event); break; case 107: /* + */ ch = this.applyModifiers(43, event); break; case 109: /* - */ ch = this.applyModifiers(45, event); break; case 110: /* . */ ch = this.applyModifiers(46, event); break; case 111: /* / */ ch = this.applyModifiers(47, event); break; case 112: /* F1 */ ch = '\u001BOP'; break; case 113: /* F2 */ ch = '\u001BOQ'; break; case 114: /* F3 */ ch = '\u001BOR'; break; case 115: /* F4 */ ch = '\u001BOS'; break; case 116: /* F5 */ ch = '\u001B[15~'; break; case 117: /* F6 */ ch = '\u001B[17~'; break; case 118: /* F7 */ ch = '\u001B[18~'; break; case 119: /* F8 */ ch = '\u001B[19~'; break; case 120: /* F9 */ ch = '\u001B[20~'; break; case 121: /* F10 */ ch = '\u001B[21~'; break; case 122: /* F11 */ ch = '\u001B[23~'; break; case 123: /* F12 */ ch = '\u001B[24~'; break; case 144: /* Num Lock */ return; case 145: /* Scroll Lock */ return; case 186: /* ; */ ch = this.applyModifiers(59, event); break; case 187: /* = */ ch = this.applyModifiers(61, event); break; case 188: /* , */ ch = this.applyModifiers(44, event); break; case 189: /* - */ ch = this.applyModifiers(45, event); break; case 190: /* . */ ch = this.applyModifiers(46, event); break; case 191: /* / */ ch = this.applyModifiers(47, event); break; case 192: /* ` */ ch = this.applyModifiers(96, event); break; case 219: /* [ */ ch = this.applyModifiers(91, event); break; case 220: /* \ */ ch = this.applyModifiers(92, event); break; case 221: /* ] */ ch = this.applyModifiers(93, event); break; case 222: /* ' */ ch = this.applyModifiers(39, event); break; default: return; } this.scrollable.scrollTop = this.numScrollbackLines * this.cursorHeight + 1; } } // "ch" now contains the sequence of keycodes to send. But we might still // have to apply the effects of modifier keys. if (event.shiftKey || event.ctrlKey || event.altKey || event.metaKey) { var start, digit, part1, part2; if ((start = ch.substr(0, 2)) == '\u001B[') { for (part1 = start; part1.length < ch.length && (digit = ch.charCodeAt(part1.length)) >= 48 && digit <= 57; ) { part1 = ch.substr(0, part1.length + 1); } part2 = ch.substr(part1.length); if (part1.length > 2) { part1 += ';'; } } else if (start == '\u001BO') { part1 = start; part2 = ch.substr(2); } if (part1 != undefined) { ch = part1 + ((event.shiftKey ? 1 : 0) + (event.altKey|event.metaKey ? 2 : 0) + (event.ctrlKey ? 4 : 0)) + part2; } else if (ch.length == 1 && (event.altKey || event.metaKey)) { ch = '\u001B' + ch; } } if (this.menu.style.visibility == 'hidden') { // this.vt100('R: c='); // for (var i = 0; i < ch.length; i++) // this.vt100((i != 0 ? ', ' : '') + ch.charCodeAt(i)); // this.vt100('\r\n'); this.keysPressed(ch); } }; VT100.prototype.inspect = function(o, d) { if (d == undefined) { d = 0; } var rc = ''; if (typeof o == 'object' && ++d < 2) { rc = '[\r\n'; for (i in o) { rc += this.spaces(d * 2) + i + ' -> '; try { rc += this.inspect(o[i], d); } catch (e) { rc += '?' + '?' + '?\r\n'; } } rc += ']\r\n'; } else { rc += ('' + o).replace(/\n/g, ' ').replace(/ +/g,' ') + '\r\n'; } return rc; }; VT100.prototype.checkComposedKeys = function(event) { // Composed keys (at least on Linux) do not generate normal events. // Instead, they get entered into the text field. We normally catch // this on the next keyup event. var s = this.input.value; if (s.length) { this.input.value = ''; if (this.menu.style.visibility == 'hidden') { this.keysPressed(s); } } }; VT100.prototype.fixEvent = function(event) { // Some browsers report AltGR as a combination of ALT and CTRL. As AltGr // is used as a second-level selector, clear the modifier bits before // handling the event. if (event.ctrlKey && event.altKey) { var fake = [ ]; fake.charCode = event.charCode; fake.keyCode = event.keyCode; fake.ctrlKey = false; fake.shiftKey = event.shiftKey; fake.altKey = false; fake.metaKey = event.metaKey; return fake; } // Some browsers fail to translate keys, if both shift and alt/meta is // pressed at the same time. We try to translate those cases, but that // only works for US keyboard layouts. if (event.shiftKey) { var u = undefined; var s = undefined; switch (this.lastNormalKeyDownEvent.keyCode) { case 39: /* ' -> " */ u = 39; s = 34; break; case 44: /* , -> < */ u = 44; s = 60; break; case 45: /* - -> _ */ u = 45; s = 95; break; case 46: /* . -> > */ u = 46; s = 62; break; case 47: /* / -> ? */ u = 47; s = 63; break; case 48: /* 0 -> ) */ u = 48; s = 41; break; case 49: /* 1 -> ! */ u = 49; s = 33; break; case 50: /* 2 -> @ */ u = 50; s = 64; break; case 51: /* 3 -> # */ u = 51; s = 35; break; case 52: /* 4 -> $ */ u = 52; s = 36; break; case 53: /* 5 -> % */ u = 53; s = 37; break; case 54: /* 6 -> ^ */ u = 54; s = 94; break; case 55: /* 7 -> & */ u = 55; s = 38; break; case 56: /* 8 -> * */ u = 56; s = 42; break; case 57: /* 9 -> ( */ u = 57; s = 40; break; case 59: /* ; -> : */ u = 59; s = 58; break; case 61: /* = -> + */ u = 61; s = 43; break; case 91: /* [ -> { */ u = 91; s = 123; break; case 92: /* \ -> | */ u = 92; s = 124; break; case 93: /* ] -> } */ u = 93; s = 125; break; case 96: /* ` -> ~ */ u = 96; s = 126; break; case 109: /* - -> _ */ u = 45; s = 95; break; case 111: /* / -> ? */ u = 47; s = 63; break; case 186: /* ; -> : */ u = 59; s = 58; break; case 187: /* = -> + */ u = 61; s = 43; break; case 188: /* , -> < */ u = 44; s = 60; break; case 189: /* - -> _ */ u = 45; s = 95; break; case 190: /* . -> > */ u = 46; s = 62; break; case 191: /* / -> ? */ u = 47; s = 63; break; case 192: /* ` -> ~ */ u = 96; s = 126; break; case 219: /* [ -> { */ u = 91; s = 123; break; case 220: /* \ -> | */ u = 92; s = 124; break; case 221: /* ] -> } */ u = 93; s = 125; break; case 222: /* ' -> " */ u = 39; s = 34; break; default: break; } if (s && (event.charCode == u || event.charCode == 0)) { var fake = [ ]; fake.charCode = s; fake.keyCode = event.keyCode; fake.ctrlKey = event.ctrlKey; fake.shiftKey = event.shiftKey; fake.altKey = event.altKey; fake.metaKey = event.metaKey; return fake; } } return event; }; VT100.prototype.keyDown = function(event) { // this.vt100('D: c=' + event.charCode + ', k=' + event.keyCode + // (event.shiftKey || event.ctrlKey || event.altKey || // event.metaKey ? ', ' + // (event.shiftKey ? 'S' : '') + (event.ctrlKey ? 'C' : '') + // (event.altKey ? 'A' : '') + (event.metaKey ? 'M' : '') : '') + // '\r\n'); this.checkComposedKeys(event); this.lastKeyPressedEvent = undefined; this.lastKeyDownEvent = undefined; this.lastNormalKeyDownEvent = event; var asciiKey = event.keyCode == 32 || event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode >= 65 && event.keyCode <= 90; var alphNumKey = asciiKey || event.keyCode >= 96 && event.keyCode <= 105 || event.keyCode == 226; var normalKey = alphNumKey || event.keyCode == 59 || event.keyCode == 61 || event.keyCode == 106 || event.keyCode == 107 || event.keyCode >= 109 && event.keyCode <= 111 || event.keyCode >= 186 && event.keyCode <= 192 || event.keyCode >= 219 && event.keyCode <= 223 || event.keyCode == 252; try { if (navigator.appName == 'Konqueror') { normalKey |= event.keyCode < 128; } } catch (e) { } // We normally prefer to look at keypress events, as they perform the // translation from keyCode to charCode. This is important, as the // translation is locale-dependent. // But for some keys, we must intercept them during the keydown event, // as they would otherwise get interpreted by the browser. // Even, when doing all of this, there are some keys that we can never // intercept. This applies to some of the menu navigation keys in IE. // In fact, we see them, but we cannot stop IE from seeing them, too. if ((event.charCode || event.keyCode) && ((alphNumKey && (event.ctrlKey || event.altKey || event.metaKey) && !event.shiftKey && // Some browsers signal AltGR as both CTRL and ALT. Do not try to // interpret this sequence ourselves, as some keyboard layouts use // it for second-level layouts. !(event.ctrlKey && event.altKey)) || this.catchModifiersEarly && normalKey && !alphNumKey && (event.ctrlKey || event.altKey || event.metaKey) || !normalKey)) { this.lastKeyDownEvent = event; var fake = [ ]; fake.ctrlKey = event.ctrlKey; fake.shiftKey = event.shiftKey; fake.altKey = event.altKey; fake.metaKey = event.metaKey; if (asciiKey) { fake.charCode = event.keyCode; fake.keyCode = 0; } else { fake.charCode = 0; fake.keyCode = event.keyCode; if (!alphNumKey && event.shiftKey) { fake = this.fixEvent(fake); } } this.handleKey(fake); this.lastNormalKeyDownEvent = undefined; try { // For non-IE browsers event.stopPropagation(); event.preventDefault(); } catch (e) { } try { // For IE event.cancelBubble = true; event.returnValue = false; event.keyCode = 0; } catch (e) { } return false; } return true; }; VT100.prototype.keyPressed = function(event) { // this.vt100('P: c=' + event.charCode + ', k=' + event.keyCode + // (event.shiftKey || event.ctrlKey || event.altKey || // event.metaKey ? ', ' + // (event.shiftKey ? 'S' : '') + (event.ctrlKey ? 'C' : '') + // (event.altKey ? 'A' : '') + (event.metaKey ? 'M' : '') : '') + // '\r\n'); if (this.lastKeyDownEvent) { // If we already processed the key on keydown, do not process it // again here. Ideally, the browser should not even have generated a // keypress event in this case. But that does not appear to always work. this.lastKeyDownEvent = undefined; } else { this.handleKey(event.altKey || event.metaKey ? this.fixEvent(event) : event); } try { // For non-IE browsers event.preventDefault(); } catch (e) { } try { // For IE event.cancelBubble = true; event.returnValue = false; event.keyCode = 0; } catch (e) { } this.lastNormalKeyDownEvent = undefined; this.lastKeyPressedEvent = event; return false; }; VT100.prototype.keyUp = function(event) { // this.vt100('U: c=' + event.charCode + ', k=' + event.keyCode + // (event.shiftKey || event.ctrlKey || event.altKey || // event.metaKey ? ', ' + // (event.shiftKey ? 'S' : '') + (event.ctrlKey ? 'C' : '') + // (event.altKey ? 'A' : '') + (event.metaKey ? 'M' : '') : '') + // '\r\n'); if (this.lastKeyPressedEvent) { // The compose key on Linux occasionally confuses the browser and keeps // inserting bogus characters into the input field, even if just a regular // key has been pressed. Detect this case and drop the bogus characters. (event.target || event.srcElement).value = ''; } else { // This is usually were we notice that a key has been composed and // thus failed to generate normal events. this.checkComposedKeys(event); // Some browsers don't report keypress events if ctrl or alt is pressed // for non-alphanumerical keys. Patch things up for now, but in the // future we will catch these keys earlier (in the keydown handler). if (this.lastNormalKeyDownEvent) { // this.vt100('ENABLING EARLY CATCHING OF MODIFIER KEYS\r\n'); this.catchModifiersEarly = true; var asciiKey = event.keyCode == 32 || event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode >= 65 && event.keyCode <= 90; var alphNumKey = asciiKey || event.keyCode >= 96 && event.keyCode <= 105; var normalKey = alphNumKey || event.keyCode == 59 || event.keyCode == 61 || event.keyCode == 106 || event.keyCode == 107 || event.keyCode >= 109 && event.keyCode <= 111 || event.keyCode >= 186 && event.keyCode <= 192 || event.keyCode >= 219 && event.keyCode <= 223 || event.keyCode == 252; var fake = [ ]; fake.ctrlKey = event.ctrlKey; fake.shiftKey = event.shiftKey; fake.altKey = event.altKey; fake.metaKey = event.metaKey; if (asciiKey) { fake.charCode = event.keyCode; fake.keyCode = 0; } else { fake.charCode = 0; fake.keyCode = event.keyCode; if (!alphNumKey && (event.ctrlKey || event.altKey || event.metaKey)) { fake = this.fixEvent(fake); } } this.lastNormalKeyDownEvent = undefined; this.handleKey(fake); } } try { // For IE event.cancelBubble = true; event.returnValue = false; event.keyCode = 0; } catch (e) { } this.lastKeyDownEvent = undefined; this.lastKeyPressedEvent = undefined; return false; }; VT100.prototype.animateCursor = function(inactive) { if (!this.cursorInterval) { this.cursorInterval = setInterval( function(vt100) { return function() { vt100.animateCursor(); // Use this opportunity to check whether the user entered a composed // key, or whether somebody pasted text into the textfield. vt100.checkComposedKeys(); } }(this), 500); } if (inactive != undefined || this.cursor.className != 'inactive') { if (inactive) { this.cursor.className = 'inactive'; } else { if (this.blinkingCursor) { this.cursor.className = this.cursor.className == 'bright' ? 'dim' : 'bright'; } else { this.cursor.className = 'bright'; } } } }; VT100.prototype.blurCursor = function() { this.animateCursor(true); }; VT100.prototype.focusCursor = function() { this.animateCursor(false); }; VT100.prototype.flashScreen = function() { this.isInverted = !this.isInverted; this.refreshInvertedState(); this.isInverted = !this.isInverted; setTimeout(function(vt100) { return function() { vt100.refreshInvertedState(); }; }(this), 100); }; VT100.prototype.beep = function() { if (this.visualBell) { this.flashScreen(); } else { try { this.beeper.Play(); } catch (e) { try { this.beeper.src = 'beep.wav'; } catch (e) { } } } }; VT100.prototype.bs = function() { if (this.cursorX > 0) { this.gotoXY(this.cursorX - 1, this.cursorY); this.needWrap = false; } }; VT100.prototype.ht = function(count) { if (count == undefined) { count = 1; } var cx = this.cursorX; while (count-- > 0) { while (cx++ < this.terminalWidth) { var tabState = this.userTabStop[cx]; if (tabState == false) { // Explicitly cleared tab stop continue; } else if (tabState) { // Explicitly set tab stop break; } else { // Default tab stop at each eighth column if (cx % 8 == 0) { break; } } } } if (cx > this.terminalWidth - 1) { cx = this.terminalWidth - 1; } if (cx != this.cursorX) { this.gotoXY(cx, this.cursorY); } }; VT100.prototype.rt = function(count) { if (count == undefined) { count = 1 ; } var cx = this.cursorX; while (count-- > 0) { while (cx-- > 0) { var tabState = this.userTabStop[cx]; if (tabState == false) { // Explicitly cleared tab stop continue; } else if (tabState) { // Explicitly set tab stop break; } else { // Default tab stop at each eighth column if (cx % 8 == 0) { break; } } } } if (cx < 0) { cx = 0; } if (cx != this.cursorX) { this.gotoXY(cx, this.cursorY); } }; VT100.prototype.cr = function() { this.gotoXY(0, this.cursorY); this.needWrap = false; }; VT100.prototype.lf = function(count) { if (count == undefined) { count = 1; } else { if (count > this.terminalHeight) { count = this.terminalHeight; } if (count < 1) { count = 1; } } while (count-- > 0) { if (this.cursorY == this.bottom - 1) { this.scrollRegion(0, this.top + 1, this.terminalWidth, this.bottom - this.top - 1, 0, -1, this.color, this.style); offset = undefined; } else if (this.cursorY < this.terminalHeight - 1) { this.gotoXY(this.cursorX, this.cursorY + 1); } } }; VT100.prototype.ri = function(count) { if (count == undefined) { count = 1; } else { if (count > this.terminalHeight) { count = this.terminalHeight; } if (count < 1) { count = 1; } } while (count-- > 0) { if (this.cursorY == this.top) { this.scrollRegion(0, this.top, this.terminalWidth, this.bottom - this.top - 1, 0, 1, this.color, this.style); } else if (this.cursorY > 0) { this.gotoXY(this.cursorX, this.cursorY - 1); } } this.needWrap = false; }; VT100.prototype.respondID = function() { this.respondString += '\u001B[?6c'; }; VT100.prototype.respondSecondaryDA = function() { this.respondString += '\u001B[>0;0;0c'; }; VT100.prototype.updateStyle = function() { this.style = ''; if (this.attr & 0x0200 /* ATTR_UNDERLINE */) { this.style = 'text-decoration: underline;'; } var bg = (this.attr >> 4) & 0xF; var fg = this.attr & 0xF; if (this.attr & 0x0100 /* ATTR_REVERSE */) { var tmp = bg; bg = fg; fg = tmp; } if ((this.attr & (0x0100 /* ATTR_REVERSE */ | 0x0400 /* ATTR_DIM */)) == 0x0400 /* ATTR_DIM */) { fg = 8; // Dark grey } else if (this.attr & 0x0800 /* ATTR_BRIGHT */) { fg |= 8; this.style = 'font-weight: bold;'; } if (this.attr & 0x1000 /* ATTR_BLINK */) { this.style = 'text-decoration: blink;'; } this.color = 'ansi' + fg + ' bgAnsi' + bg; }; VT100.prototype.setAttrColors = function(attr) { if (attr != this.attr) { this.attr = attr; this.updateStyle(); } }; VT100.prototype.saveCursor = function() { this.savedX[this.currentScreen] = this.cursorX; this.savedY[this.currentScreen] = this.cursorY; this.savedAttr[this.currentScreen] = this.attr; this.savedUseGMap = this.useGMap; for (var i = 0; i < 4; i++) { this.savedGMap[i] = this.GMap[i]; } this.savedValid[this.currentScreen] = true; }; VT100.prototype.restoreCursor = function() { if (!this.savedValid[this.currentScreen]) { return; } this.attr = this.savedAttr[this.currentScreen]; this.updateStyle(); this.useGMap = this.savedUseGMap; for (var i = 0; i < 4; i++) { this.GMap[i] = this.savedGMap[i]; } this.translate = this.GMap[this.useGMap]; this.needWrap = false; this.gotoXY(this.savedX[this.currentScreen], this.savedY[this.currentScreen]); }; VT100.prototype.getTransformName = function() { var styles = [ 'transform', 'WebkitTransform', 'MozTransform', 'filter' ]; for (var i = 0; i < styles.length; ++i) { if (typeof this.console[0].style[styles[i]] != 'undefined') { return styles[i]; } } return undefined; }; VT100.prototype.getTransformStyle = function(transform, scale) { return scale && scale != 1.0 ? transform == 'filter' ? 'progid:DXImageTransform.Microsoft.Matrix(' + 'M11=' + (1.0/scale) + ',M12=0,M21=0,M22=1,' + "sizingMethod='auto expand')" : 'translateX(-50%) ' + 'scaleX(' + (1.0/scale) + ') ' + 'translateX(50%)' : ''; }; VT100.prototype.set80_132Mode = function(state) { var transform = this.getTransformName(); if (transform) { if ((this.console[this.currentScreen].style[transform] != '') == state) { return; } var style = state ? this.getTransformStyle(transform, 1.65):''; this.console[this.currentScreen].style[transform] = style; this.cursor.style[transform] = style; this.space.style[transform] = style; this.scale = state ? 1.65 : 1.0; if (transform == 'filter') { this.console[this.currentScreen].style.width = state ? '165%' : ''; } this.resizer(); } }; VT100.prototype.setMode = function(state) { for (var i = 0; i <= this.npar; i++) { if (this.isQuestionMark) { switch (this.par[i]) { case 1: this.cursorKeyMode = state; break; case 3: this.set80_132Mode(state); break; case 5: this.isInverted = state; this.refreshInvertedState(); break; case 6: this.offsetMode = state; break; case 7: this.autoWrapMode = state; break; case 1000: case 9: this.mouseReporting = state; break; case 25: this.cursorNeedsShowing = state; if (state) { this.showCursor(); } else { this.hideCursor(); } break; case 1047: case 1049: case 47: this.enableAlternateScreen(state); break; default: break; } } else { switch (this.par[i]) { case 3: this.dispCtrl = state; break; case 4: this.insertMode = state; break; case 20:this.crLfMode = state; break; default: break; } } } }; VT100.prototype.statusReport = function() { // Ready and operational. this.respondString += '\u001B[0n'; }; VT100.prototype.cursorReport = function() { this.respondString += '\u001B[' + (this.cursorY + (this.offsetMode ? this.top + 1 : 1)) + ';' + (this.cursorX + 1) + 'R'; }; VT100.prototype.setCursorAttr = function(setAttr, xorAttr) { // Changing of cursor color is not implemented. }; VT100.prototype.openPrinterWindow = function() { var rc = true; try { if (!this.printWin || this.printWin.closed) { this.printWin = window.open('', 'print-output', 'width=800,height=600,directories=no,location=no,menubar=yes,' + 'status=no,toolbar=no,titlebar=yes,scrollbars=yes,resizable=yes'); this.printWin.document.body.innerHTML = '<link rel="stylesheet" href="' + document.location.protocol + '//' + document.location.host + document.location.pathname.replace(/[^/]*$/, '') + 'print-styles.css" type="text/css">\n' + '<div id="options"><input id="autoprint" type="checkbox"' + (this.autoprint ? ' checked' : '') + '>' + 'Automatically, print page(s) when job is ready' + '</input></div>\n' + '<div id="spacer"><input type="checkbox">&nbsp;</input></div>' + '<pre id="print"></pre>\n'; var autoprint = this.printWin.document.getElementById('autoprint'); this.addListener(autoprint, 'click', (function(vt100, autoprint) { return function() { vt100.autoprint = autoprint.checked; vt100.storeUserSettings(); return false; }; })(this, autoprint)); this.printWin.document.title = 'ShellInABox Printer Output'; } } catch (e) { // Maybe, a popup blocker prevented us from working. Better catch the // exception, so that we won't break the entire terminal session. The // user probably needs to disable the blocker first before retrying the // operation. rc = false; } rc &= this.printWin && !this.printWin.closed && (this.printWin.innerWidth || this.printWin.document.documentElement.clientWidth || this.printWin.document.body.clientWidth) > 1; if (!rc && this.printing == 100) { // Different popup blockers work differently. We try to detect a couple // of common methods. And then we retry again a brief amount later, as // false positives are otherwise possible. If we are sure that there is // a popup blocker in effect, we alert the user to it. This is helpful // as some popup blockers have minimal or no UI, and the user might not // notice that they are missing the popup. In any case, we only show at // most one message per print job. this.printing = true; setTimeout((function(win) { return function() { if (!win || win.closed || (win.innerWidth || win.document.documentElement.clientWidth || win.document.body.clientWidth) <= 1) { alert('Attempted to print, but a popup blocker ' + 'prevented the printer window from opening'); } }; })(this.printWin), 2000); } return rc; }; VT100.prototype.sendToPrinter = function(s) { this.openPrinterWindow(); try { var doc = this.printWin.document; var print = doc.getElementById('print'); if (print.lastChild && print.lastChild.nodeName == '#text') { print.lastChild.textContent += this.replaceChar(s, ' ', '\u00A0'); } else { print.appendChild(doc.createTextNode(this.replaceChar(s, ' ','\u00A0'))); } } catch (e) { // There probably was a more aggressive popup blocker that prevented us // from accessing the printer windows. } }; VT100.prototype.sendControlToPrinter = function(ch) { // We get called whenever doControl() is active. But for the printer, we // only implement a basic line printer that doesn't understand most of // the escape sequences of the VT100 terminal. In fact, the only escape // sequence that we really need to recognize is '^[[5i' for turning the // printer off. try { switch (ch) { case 9: // HT this.openPrinterWindow(); var doc = this.printWin.document; var print = doc.getElementById('print'); var chars = print.lastChild && print.lastChild.nodeName == '#text' ? print.lastChild.textContent.length : 0; this.sendToPrinter(this.spaces(8 - (chars % 8))); break; case 10: // CR break; case 12: // FF this.openPrinterWindow(); var pageBreak = this.printWin.document.createElement('div'); pageBreak.className = 'pagebreak'; pageBreak.innerHTML = '<hr />'; this.printWin.document.getElementById('print').appendChild(pageBreak); break; case 13: // LF this.openPrinterWindow(); var lineBreak = this.printWin.document.createElement('br'); this.printWin.document.getElementById('print').appendChild(lineBreak); break; case 27: // ESC this.isEsc = 1 /* ESesc */; break; default: switch (this.isEsc) { case 1 /* ESesc */: this.isEsc = 0 /* ESnormal */; switch (ch) { case 0x5B /*[*/: this.isEsc = 2 /* ESsquare */; break; default: break; } break; case 2 /* ESsquare */: this.npar = 0; this.par = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; this.isEsc = 3 /* ESgetpars */; this.isQuestionMark = ch == 0x3F /*?*/; if (this.isQuestionMark) { break; } // Fall through case 3 /* ESgetpars */: if (ch == 0x3B /*;*/) { this.npar++; break; } else if (ch >= 0x30 /*0*/ && ch <= 0x39 /*9*/) { var par = this.par[this.npar]; if (par == undefined) { par = 0; } this.par[this.npar] = 10*par + (ch & 0xF); break; } else { this.isEsc = 4 /* ESgotpars */; } // Fall through case 4 /* ESgotpars */: this.isEsc = 0 /* ESnormal */; if (this.isQuestionMark) { break; } switch (ch) { case 0x69 /*i*/: this.csii(this.par[0]); break; default: break; } break; default: this.isEsc = 0 /* ESnormal */; break; } break; } } catch (e) { // There probably was a more aggressive popup blocker that prevented us // from accessing the printer windows. } }; VT100.prototype.csiAt = function(number) { // Insert spaces if (number == 0) { number = 1; } if (number > this.terminalWidth - this.cursorX) { number = this.terminalWidth - this.cursorX; } this.scrollRegion(this.cursorX, this.cursorY, this.terminalWidth - this.cursorX - number, 1, number, 0, this.color, this.style); this.needWrap = false; }; VT100.prototype.csii = function(number) { // Printer control switch (number) { case 0: // Print Screen window.print(); break; case 4: // Stop printing try { if (this.printing && this.printWin && !this.printWin.closed) { var print = this.printWin.document.getElementById('print'); while (print.lastChild && print.lastChild.tagName == 'DIV' && print.lastChild.className == 'pagebreak') { // Remove trailing blank pages print.removeChild(print.lastChild); } if (this.autoprint) { this.printWin.print(); } } } catch (e) { } this.printing = false; break; case 5: // Start printing if (!this.printing && this.printWin && !this.printWin.closed) { this.printWin.document.getElementById('print').innerHTML = ''; } this.printing = 100; break; default: break; } }; VT100.prototype.csiJ = function(number) { switch (number) { case 0: // Erase from cursor to end of display this.clearRegion(this.cursorX, this.cursorY, this.terminalWidth - this.cursorX, 1, this.color, this.style); if (this.cursorY < this.terminalHeight-2) { this.clearRegion(0, this.cursorY+1, this.terminalWidth, this.terminalHeight-this.cursorY-1, this.color, this.style); } break; case 1: // Erase from start to cursor if (this.cursorY > 0) { this.clearRegion(0, 0, this.terminalWidth, this.cursorY, this.color, this.style); } this.clearRegion(0, this.cursorY, this.cursorX + 1, 1, this.color, this.style); break; case 2: // Erase whole display this.clearRegion(0, 0, this.terminalWidth, this.terminalHeight, this.color, this.style); break; default: return; } needWrap = false; }; VT100.prototype.csiK = function(number) { switch (number) { case 0: // Erase from cursor to end of line this.clearRegion(this.cursorX, this.cursorY, this.terminalWidth - this.cursorX, 1, this.color, this.style); break; case 1: // Erase from start of line to cursor this.clearRegion(0, this.cursorY, this.cursorX + 1, 1, this.color, this.style); break; case 2: // Erase whole line this.clearRegion(0, this.cursorY, this.terminalWidth, 1, this.color, this.style); break; default: return; } needWrap = false; }; VT100.prototype.csiL = function(number) { // Open line by inserting blank line(s) if (this.cursorY >= this.bottom) { return; } if (number == 0) { number = 1; } if (number > this.bottom - this.cursorY) { number = this.bottom - this.cursorY; } this.scrollRegion(0, this.cursorY, this.terminalWidth, this.bottom - this.cursorY - number, 0, number, this.color, this.style); needWrap = false; }; VT100.prototype.csiM = function(number) { // Delete line(s), scrolling up the bottom of the screen. if (this.cursorY >= this.bottom) { return; } if (number == 0) { number = 1; } if (number > this.bottom - this.cursorY) { number = bottom - cursorY; } this.scrollRegion(0, this.cursorY + number, this.terminalWidth, this.bottom - this.cursorY - number, 0, -number, this.color, this.style); needWrap = false; }; VT100.prototype.csim = function() { for (var i = 0; i <= this.npar; i++) { switch (this.par[i]) { case 0: this.attr = 0x00F0 /* ATTR_DEFAULT */; break; case 1: this.attr = (this.attr & ~0x0400 /* ATTR_DIM */)|0x0800 /* ATTR_BRIGHT */; break; case 2: this.attr = (this.attr & ~0x0800 /* ATTR_BRIGHT */)|0x0400 /* ATTR_DIM */; break; case 4: this.attr |= 0x0200 /* ATTR_UNDERLINE */; break; case 5: this.attr |= 0x1000 /* ATTR_BLINK */; break; case 7: this.attr |= 0x0100 /* ATTR_REVERSE */; break; case 10: this.translate = this.GMap[this.useGMap]; this.dispCtrl = false; this.toggleMeta = false; break; case 11: this.translate = this.CodePage437Map; this.dispCtrl = true; this.toggleMeta = false; break; case 12: this.translate = this.CodePage437Map; this.dispCtrl = true; this.toggleMeta = true; break; case 21: case 22: this.attr &= ~(0x0800 /* ATTR_BRIGHT */|0x0400 /* ATTR_DIM */); break; case 24: this.attr &= ~ 0x0200 /* ATTR_UNDERLINE */; break; case 25: this.attr &= ~ 0x1000 /* ATTR_BLINK */; break; case 27: this.attr &= ~ 0x0100 /* ATTR_REVERSE */; break; case 38: this.attr = (this.attr & ~(0x0400 /* ATTR_DIM */|0x0800 /* ATTR_BRIGHT */|0x0F))| 0x0200 /* ATTR_UNDERLINE */; break; case 39: this.attr &= ~(0x0400 /* ATTR_DIM */|0x0800 /* ATTR_BRIGHT */|0x0200 /* ATTR_UNDERLINE */|0x0F); break; case 49: this.attr |= 0xF0; break; default: if (this.par[i] >= 30 && this.par[i] <= 37) { var fg = this.par[i] - 30; this.attr = (this.attr & ~0x0F) | fg; } else if (this.par[i] >= 40 && this.par[i] <= 47) { var bg = this.par[i] - 40; this.attr = (this.attr & ~0xF0) | (bg << 4); } break; } } this.updateStyle(); }; VT100.prototype.csiP = function(number) { // Delete character(s) following cursor if (number == 0) { number = 1; } if (number > this.terminalWidth - this.cursorX) { number = this.terminalWidth - this.cursorX; } this.scrollRegion(this.cursorX + number, this.cursorY, this.terminalWidth - this.cursorX - number, 1, -number, 0, this.color, this.style); needWrap = false; }; VT100.prototype.csiX = function(number) { // Clear characters following cursor if (number == 0) { number++; } if (number > this.terminalWidth - this.cursorX) { number = this.terminalWidth - this.cursorX; } this.clearRegion(this.cursorX, this.cursorY, number, 1, this.color, this.style); needWrap = false; }; VT100.prototype.settermCommand = function() { // Setterm commands are not implemented }; VT100.prototype.doControl = function(ch) { if (this.printing) { this.sendControlToPrinter(ch); return ''; } var lineBuf = ''; switch (ch) { case 0x00: /* ignored */ break; case 0x08: this.bs(); break; case 0x09: this.ht(); break; case 0x0A: case 0x0B: case 0x0C: case 0x84: this.lf(); if (!this.crLfMode) break; case 0x0D: this.cr(); break; case 0x85: this.cr(); this.lf(); break; case 0x0E: this.useGMap = 1; this.translate = this.GMap[1]; this.dispCtrl = true; break; case 0x0F: this.useGMap = 0; this.translate = this.GMap[0]; this.dispCtrl = false; break; case 0x18: case 0x1A: this.isEsc = 0 /* ESnormal */; break; case 0x1B: this.isEsc = 1 /* ESesc */; break; case 0x7F: /* ignored */ break; case 0x88: this.userTabStop[this.cursorX] = true; break; case 0x8D: this.ri(); break; case 0x8E: this.isEsc = 18 /* ESss2 */; break; case 0x8F: this.isEsc = 19 /* ESss3 */; break; case 0x9A: this.respondID(); break; case 0x9B: this.isEsc = 2 /* ESsquare */; break; case 0x07: if (this.isEsc != 17 /* EStitle */) { this.beep(); break; } /* fall thru */ default: switch (this.isEsc) { case 1 /* ESesc */: this.isEsc = 0 /* ESnormal */; switch (ch) { /*%*/ case 0x25: this.isEsc = 13 /* ESpercent */; break; /*(*/ case 0x28: this.isEsc = 8 /* ESsetG0 */; break; /*-*/ case 0x2D: /*)*/ case 0x29: this.isEsc = 9 /* ESsetG1 */; break; /*.*/ case 0x2E: /***/ case 0x2A: this.isEsc = 10 /* ESsetG2 */; break; /*/*/ case 0x2F: /*+*/ case 0x2B: this.isEsc = 11 /* ESsetG3 */; break; /*#*/ case 0x23: this.isEsc = 7 /* EShash */; break; /*7*/ case 0x37: this.saveCursor(); break; /*8*/ case 0x38: this.restoreCursor(); break; /*>*/ case 0x3E: this.applKeyMode = false; break; /*=*/ case 0x3D: this.applKeyMode = true; break; /*D*/ case 0x44: this.lf(); break; /*E*/ case 0x45: this.cr(); this.lf(); break; /*M*/ case 0x4D: this.ri(); break; /*N*/ case 0x4E: this.isEsc = 18 /* ESss2 */; break; /*O*/ case 0x4F: this.isEsc = 19 /* ESss3 */; break; /*H*/ case 0x48: this.userTabStop[this.cursorX] = true; break; /*Z*/ case 0x5A: this.respondID(); break; /*[*/ case 0x5B: this.isEsc = 2 /* ESsquare */; break; /*]*/ case 0x5D: this.isEsc = 15 /* ESnonstd */; break; /*c*/ case 0x63: this.reset(); break; /*g*/ case 0x67: this.flashScreen(); break; default: break; } break; case 15 /* ESnonstd */: switch (ch) { /*0*/ case 0x30: /*1*/ case 0x31: /*2*/ case 0x32: this.isEsc = 17 /* EStitle */; this.titleString = ''; break; /*P*/ case 0x50: this.npar = 0; this.par = [ 0, 0, 0, 0, 0, 0, 0 ]; this.isEsc = 16 /* ESpalette */; break; /*R*/ case 0x52: // Palette support is not implemented this.isEsc = 0 /* ESnormal */; break; default: this.isEsc = 0 /* ESnormal */; break; } break; case 16 /* ESpalette */: if ((ch >= 0x30 /*0*/ && ch <= 0x39 /*9*/) || (ch >= 0x41 /*A*/ && ch <= 0x46 /*F*/) || (ch >= 0x61 /*a*/ && ch <= 0x66 /*f*/)) { this.par[this.npar++] = ch > 0x39 /*9*/ ? (ch & 0xDF) - 55 : (ch & 0xF); if (this.npar == 7) { // Palette support is not implemented this.isEsc = 0 /* ESnormal */; } } else { this.isEsc = 0 /* ESnormal */; } break; case 2 /* ESsquare */: this.npar = 0; this.par = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; this.isEsc = 3 /* ESgetpars */; /*[*/ if (ch == 0x5B) { // Function key this.isEsc = 6 /* ESfunckey */; break; } else { /*?*/ this.isQuestionMark = ch == 0x3F; if (this.isQuestionMark) { break; } } // Fall through case 5 /* ESdeviceattr */: case 3 /* ESgetpars */: /*;*/ if (ch == 0x3B) { this.npar++; break; } else if (ch >= 0x30 /*0*/ && ch <= 0x39 /*9*/) { var par = this.par[this.npar]; if (par == undefined) { par = 0; } this.par[this.npar] = 10*par + (ch & 0xF); break; } else if (this.isEsc == 5 /* ESdeviceattr */) { switch (ch) { /*c*/ case 0x63: if (this.par[0] == 0) this.respondSecondaryDA(); break; /*m*/ case 0x6D: /* (re)set key modifier resource values */ break; /*n*/ case 0x6E: /* disable key modifier resource values */ break; /*p*/ case 0x70: /* set pointer mode resource value */ break; default: break; } this.isEsc = 0 /* ESnormal */; break; } else { this.isEsc = 4 /* ESgotpars */; } // Fall through case 4 /* ESgotpars */: this.isEsc = 0 /* ESnormal */; if (this.isQuestionMark) { switch (ch) { /*h*/ case 0x68: this.setMode(true); break; /*l*/ case 0x6C: this.setMode(false); break; /*c*/ case 0x63: this.setCursorAttr(this.par[2], this.par[1]); break; default: break; } this.isQuestionMark = false; break; } switch (ch) { /*!*/ case 0x21: this.isEsc = 12 /* ESbang */; break; /*>*/ case 0x3E: if (!this.npar) this.isEsc = 5 /* ESdeviceattr */; break; /*G*/ case 0x47: /*`*/ case 0x60: this.gotoXY(this.par[0] - 1, this.cursorY); break; /*A*/ case 0x41: this.gotoXY(this.cursorX, this.cursorY - (this.par[0] ? this.par[0] : 1)); break; /*B*/ case 0x42: /*e*/ case 0x65: this.gotoXY(this.cursorX, this.cursorY + (this.par[0] ? this.par[0] : 1)); break; /*C*/ case 0x43: /*a*/ case 0x61: this.gotoXY(this.cursorX + (this.par[0] ? this.par[0] : 1), this.cursorY); break; /*D*/ case 0x44: this.gotoXY(this.cursorX - (this.par[0] ? this.par[0] : 1), this.cursorY); break; /*E*/ case 0x45: this.gotoXY(0, this.cursorY + (this.par[0] ? this.par[0] :1)); break; /*F*/ case 0x46: this.gotoXY(0, this.cursorY - (this.par[0] ? this.par[0] :1)); break; /*d*/ case 0x64: this.gotoXaY(this.cursorX, this.par[0] - 1); break; /*H*/ case 0x48: /*f*/ case 0x66: this.gotoXaY(this.par[1] - 1, this.par[0] - 1); break; /*I*/ case 0x49: this.ht(this.par[0] ? this.par[0] : 1); break; /*@*/ case 0x40: this.csiAt(this.par[0]); break; /*i*/ case 0x69: this.csii(this.par[0]); break; /*J*/ case 0x4A: this.csiJ(this.par[0]); break; /*K*/ case 0x4B: this.csiK(this.par[0]); break; /*L*/ case 0x4C: this.csiL(this.par[0]); break; /*M*/ case 0x4D: this.csiM(this.par[0]); break; /*m*/ case 0x6D: this.csim(); break; /*P*/ case 0x50: this.csiP(this.par[0]); break; /*X*/ case 0x58: this.csiX(this.par[0]); break; /*S*/ case 0x53: this.lf(this.par[0] ? this.par[0] : 1); break; /*T*/ case 0x54: this.ri(this.par[0] ? this.par[0] : 1); break; /*c*/ case 0x63: if (!this.par[0]) this.respondID(); break; /*g*/ case 0x67: if (this.par[0] == 0) { this.userTabStop[this.cursorX] = false; } else if (this.par[0] == 2 || this.par[0] == 3) { this.userTabStop = [ ]; for (var i = 0; i < this.terminalWidth; i++) { this.userTabStop[i] = false; } } break; /*h*/ case 0x68: this.setMode(true); break; /*l*/ case 0x6C: this.setMode(false); break; /*n*/ case 0x6E: switch (this.par[0]) { case 5: this.statusReport(); break; case 6: this.cursorReport(); break; default: break; } break; /*q*/ case 0x71: // LED control not implemented break; /*r*/ case 0x72: var t = this.par[0] ? this.par[0] : 1; var b = this.par[1] ? this.par[1] : this.terminalHeight; if (t < b && b <= this.terminalHeight) { this.top = t - 1; this.bottom= b; this.gotoXaY(0, 0); } break; /*b*/ case 0x62: var c = this.par[0] ? this.par[0] : 1; if (c > this.terminalWidth * this.terminalHeight) { c = this.terminalWidth * this.terminalHeight; } while (c-- > 0) { lineBuf += this.lastCharacter; } break; /*s*/ case 0x73: this.saveCursor(); break; /*u*/ case 0x75: this.restoreCursor(); break; /*Z*/ case 0x5A: this.rt(this.par[0] ? this.par[0] : 1); break; /*]*/ case 0x5D: this.settermCommand(); break; default: break; } break; case 12 /* ESbang */: if (ch == 'p') { this.reset(); } this.isEsc = 0 /* ESnormal */; break; case 13 /* ESpercent */: this.isEsc = 0 /* ESnormal */; switch (ch) { /*@*/ case 0x40: this.utfEnabled = false; break; /*G*/ case 0x47: /*8*/ case 0x38: this.utfEnabled = true; break; default: break; } break; case 6 /* ESfunckey */: this.isEsc = 0 /* ESnormal */; break; case 7 /* EShash */: this.isEsc = 0 /* ESnormal */; /*8*/ if (ch == 0x38) { // Screen alignment test not implemented } break; case 8 /* ESsetG0 */: case 9 /* ESsetG1 */: case 10 /* ESsetG2 */: case 11 /* ESsetG3 */: var g = this.isEsc - 8 /* ESsetG0 */; this.isEsc = 0 /* ESnormal */; switch (ch) { /*0*/ case 0x30: this.GMap[g] = this.VT100GraphicsMap; break; /*A*/ case 0x42: /*B*/ case 0x42: this.GMap[g] = this.Latin1Map; break; /*U*/ case 0x55: this.GMap[g] = this.CodePage437Map; break; /*K*/ case 0x4B: this.GMap[g] = this.DirectToFontMap; break; default: break; } if (this.useGMap == g) { this.translate = this.GMap[g]; } break; case 17 /* EStitle */: if (ch == 0x07) { if (this.titleString && this.titleString.charAt(0) == ';') { this.titleString = this.titleString.substr(1); if (this.titleString != '') { this.titleString += ' - '; } this.titleString += 'Shell In A Box' } try { window.document.title = this.titleString; } catch (e) { } this.isEsc = 0 /* ESnormal */; } else { this.titleString += String.fromCharCode(ch); } break; case 18 /* ESss2 */: case 19 /* ESss3 */: if (ch < 256) { ch = this.GMap[this.isEsc - 18 /* ESss2 */ + 2] [this.toggleMeta ? (ch | 0x80) : ch]; if ((ch & 0xFF00) == 0xF000) { ch = ch & 0xFF; } else if (ch == 0xFEFF || (ch >= 0x200A && ch <= 0x200F)) { this.isEsc = 0 /* ESnormal */; break; } } this.lastCharacter = String.fromCharCode(ch); lineBuf += this.lastCharacter; this.isEsc = 0 /* ESnormal */; break; default: this.isEsc = 0 /* ESnormal */; break; } break; } return lineBuf; }; VT100.prototype.renderString = function(s, showCursor) { if (this.printing) { this.sendToPrinter(s); if (showCursor) { this.showCursor(); } return; } // We try to minimize the number of DOM operations by coalescing individual // characters into strings. This is a significant performance improvement. var incX = s.length; if (incX > this.terminalWidth - this.cursorX) { incX = this.terminalWidth - this.cursorX; if (incX <= 0) { return; } s = s.substr(0, incX - 1) + s.charAt(s.length - 1); } if (showCursor) { // Minimize the number of calls to putString(), by avoiding a direct // call to this.showCursor() this.cursor.style.visibility = ''; } this.putString(this.cursorX, this.cursorY, s, this.color, this.style); }; VT100.prototype.vt100 = function(s) { this.cursorNeedsShowing = this.hideCursor(); this.respondString = ''; var lineBuf = ''; for (var i = 0; i < s.length; i++) { var ch = s.charCodeAt(i); if (this.utfEnabled) { // Decode UTF8 encoded character if (ch > 0x7F) { if (this.utfCount > 0 && (ch & 0xC0) == 0x80) { this.utfChar = (this.utfChar << 6) | (ch & 0x3F); if (--this.utfCount <= 0) { if (this.utfChar > 0xFFFF || this.utfChar < 0) { ch = 0xFFFD; } else { ch = this.utfChar; } } else { continue; } } else { if ((ch & 0xE0) == 0xC0) { this.utfCount = 1; this.utfChar = ch & 0x1F; } else if ((ch & 0xF0) == 0xE0) { this.utfCount = 2; this.utfChar = ch & 0x0F; } else if ((ch & 0xF8) == 0xF0) { this.utfCount = 3; this.utfChar = ch & 0x07; } else if ((ch & 0xFC) == 0xF8) { this.utfCount = 4; this.utfChar = ch & 0x03; } else if ((ch & 0xFE) == 0xFC) { this.utfCount = 5; this.utfChar = ch & 0x01; } else { this.utfCount = 0; } continue; } } else { this.utfCount = 0; } } var isNormalCharacter = (ch >= 32 && ch <= 127 || ch >= 160 || this.utfEnabled && ch >= 128 || !(this.dispCtrl ? this.ctrlAlways : this.ctrlAction)[ch & 0x1F]) && (ch != 0x7F || this.dispCtrl); if (isNormalCharacter && this.isEsc == 0 /* ESnormal */) { if (ch < 256) { ch = this.translate[this.toggleMeta ? (ch | 0x80) : ch]; } if ((ch & 0xFF00) == 0xF000) { ch = ch & 0xFF; } else if (ch == 0xFEFF || (ch >= 0x200A && ch <= 0x200F)) { continue; } if (!this.printing) { if (this.needWrap || this.insertMode) { if (lineBuf) { this.renderString(lineBuf); lineBuf = ''; } } if (this.needWrap) { this.cr(); this.lf(); } if (this.insertMode) { this.scrollRegion(this.cursorX, this.cursorY, this.terminalWidth - this.cursorX - 1, 1, 1, 0, this.color, this.style); } } this.lastCharacter = String.fromCharCode(ch); lineBuf += this.lastCharacter; if (!this.printing && this.cursorX + lineBuf.length >= this.terminalWidth) { this.needWrap = this.autoWrapMode; } } else { if (lineBuf) { this.renderString(lineBuf); lineBuf = ''; } var expand = this.doControl(ch); if (expand.length) { var r = this.respondString; this.respondString= r + this.vt100(expand); } } } if (lineBuf) { this.renderString(lineBuf, this.cursorNeedsShowing); } else if (this.cursorNeedsShowing) { this.showCursor(); } return this.respondString; }; VT100.prototype.Latin1Map = [ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x007F, 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x008D, 0x008E, 0x008F, 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E, 0x009F, 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF ]; VT100.prototype.VT100GraphicsMap = [ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x2192, 0x2190, 0x2191, 0x2193, 0x002F, 0x2588, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x00A0, 0x25C6, 0x2592, 0x2409, 0x240C, 0x240D, 0x240A, 0x00B0, 0x00B1, 0x2591, 0x240B, 0x2518, 0x2510, 0x250C, 0x2514, 0x253C, 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251C, 0x2524, 0x2534, 0x252C, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00B7, 0x007F, 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x008D, 0x008E, 0x008F, 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E, 0x009F, 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF ]; VT100.prototype.CodePage437Map = [ 0x0000, 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, 0x25B6, 0x25C0, 0x2195, 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x2302, 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 ]; VT100.prototype.DirectToFontMap = [ 0xF000, 0xF001, 0xF002, 0xF003, 0xF004, 0xF005, 0xF006, 0xF007, 0xF008, 0xF009, 0xF00A, 0xF00B, 0xF00C, 0xF00D, 0xF00E, 0xF00F, 0xF010, 0xF011, 0xF012, 0xF013, 0xF014, 0xF015, 0xF016, 0xF017, 0xF018, 0xF019, 0xF01A, 0xF01B, 0xF01C, 0xF01D, 0xF01E, 0xF01F, 0xF020, 0xF021, 0xF022, 0xF023, 0xF024, 0xF025, 0xF026, 0xF027, 0xF028, 0xF029, 0xF02A, 0xF02B, 0xF02C, 0xF02D, 0xF02E, 0xF02F, 0xF030, 0xF031, 0xF032, 0xF033, 0xF034, 0xF035, 0xF036, 0xF037, 0xF038, 0xF039, 0xF03A, 0xF03B, 0xF03C, 0xF03D, 0xF03E, 0xF03F, 0xF040, 0xF041, 0xF042, 0xF043, 0xF044, 0xF045, 0xF046, 0xF047, 0xF048, 0xF049, 0xF04A, 0xF04B, 0xF04C, 0xF04D, 0xF04E, 0xF04F, 0xF050, 0xF051, 0xF052, 0xF053, 0xF054, 0xF055, 0xF056, 0xF057, 0xF058, 0xF059, 0xF05A, 0xF05B, 0xF05C, 0xF05D, 0xF05E, 0xF05F, 0xF060, 0xF061, 0xF062, 0xF063, 0xF064, 0xF065, 0xF066, 0xF067, 0xF068, 0xF069, 0xF06A, 0xF06B, 0xF06C, 0xF06D, 0xF06E, 0xF06F, 0xF070, 0xF071, 0xF072, 0xF073, 0xF074, 0xF075, 0xF076, 0xF077, 0xF078, 0xF079, 0xF07A, 0xF07B, 0xF07C, 0xF07D, 0xF07E, 0xF07F, 0xF080, 0xF081, 0xF082, 0xF083, 0xF084, 0xF085, 0xF086, 0xF087, 0xF088, 0xF089, 0xF08A, 0xF08B, 0xF08C, 0xF08D, 0xF08E, 0xF08F, 0xF090, 0xF091, 0xF092, 0xF093, 0xF094, 0xF095, 0xF096, 0xF097, 0xF098, 0xF099, 0xF09A, 0xF09B, 0xF09C, 0xF09D, 0xF09E, 0xF09F, 0xF0A0, 0xF0A1, 0xF0A2, 0xF0A3, 0xF0A4, 0xF0A5, 0xF0A6, 0xF0A7, 0xF0A8, 0xF0A9, 0xF0AA, 0xF0AB, 0xF0AC, 0xF0AD, 0xF0AE, 0xF0AF, 0xF0B0, 0xF0B1, 0xF0B2, 0xF0B3, 0xF0B4, 0xF0B5, 0xF0B6, 0xF0B7, 0xF0B8, 0xF0B9, 0xF0BA, 0xF0BB, 0xF0BC, 0xF0BD, 0xF0BE, 0xF0BF, 0xF0C0, 0xF0C1, 0xF0C2, 0xF0C3, 0xF0C4, 0xF0C5, 0xF0C6, 0xF0C7, 0xF0C8, 0xF0C9, 0xF0CA, 0xF0CB, 0xF0CC, 0xF0CD, 0xF0CE, 0xF0CF, 0xF0D0, 0xF0D1, 0xF0D2, 0xF0D3, 0xF0D4, 0xF0D5, 0xF0D6, 0xF0D7, 0xF0D8, 0xF0D9, 0xF0DA, 0xF0DB, 0xF0DC, 0xF0DD, 0xF0DE, 0xF0DF, 0xF0E0, 0xF0E1, 0xF0E2, 0xF0E3, 0xF0E4, 0xF0E5, 0xF0E6, 0xF0E7, 0xF0E8, 0xF0E9, 0xF0EA, 0xF0EB, 0xF0EC, 0xF0ED, 0xF0EE, 0xF0EF, 0xF0F0, 0xF0F1, 0xF0F2, 0xF0F3, 0xF0F4, 0xF0F5, 0xF0F6, 0xF0F7, 0xF0F8, 0xF0F9, 0xF0FA, 0xF0FB, 0xF0FC, 0xF0FD, 0xF0FE, 0xF0FF ]; VT100.prototype.ctrlAction = [ true, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, true, false, true, true, false, false, false, false ]; VT100.prototype.ctrlAlways = [ true, false, false, false, false, false, false, false, true, false, true, false, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false ];
JavaScript
// Demo.js -- Demonstrate some of the features of ShellInABox // Copyright (C) 2008-2009 Markus Gutschke <markus@shellinabox.com> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // In addition to these license terms, the author grants the following // additional rights: // // If you modify this program, or any covered work, by linking or // combining it with the OpenSSL project's OpenSSL library (or a // modified version of that library), containing parts covered by the // terms of the OpenSSL or SSLeay licenses, the author // grants you additional permission to convey the resulting work. // Corresponding Source for a non-source form of such a combination // shall include the source code for the parts of OpenSSL used as well // as that of the covered work. // // You may at your option choose to remove this additional permission from // the work, or from any part of it. // // It is possible to build this program in a way that it loads OpenSSL // libraries at run-time. If doing so, the following notices are required // by the OpenSSL and SSLeay licenses: // // This product includes software developed by the OpenSSL Project // for use in the OpenSSL Toolkit. (http://www.openssl.org/) // // This product includes cryptographic software written by Eric Young // (eay@cryptsoft.com) // // // The most up-to-date version of this program is always available from // http://shellinabox.com // // // Notes: // // The author believes that for the purposes of this license, you meet the // requirements for publishing the source code, if your web server publishes // the source in unmodified form (i.e. with licensing information, comments, // formatting, and identifier names intact). If there are technical reasons // that require you to make changes to the source code when serving the // JavaScript (e.g to remove pre-processor directives from the source), these // changes should be done in a reversible fashion. // // The author does not consider websites that reference this script in // unmodified form, and web servers that serve this script in unmodified form // to be derived works. As such, they are believed to be outside of the // scope of this license and not subject to the rights or restrictions of the // GNU General Public License. // // If in doubt, consult a legal professional familiar with the laws that // apply in your country. // #define STATE_IDLE 0 // #define STATE_INIT 1 // #define STATE_PROMPT 2 // #define STATE_READLINE 3 // #define STATE_COMMAND 4 // #define STATE_EXEC 5 // #define STATE_NEW_Y_N 6 // #define TYPE_STRING 0 // #define TYPE_NUMBER 1 function extend(subClass, baseClass) { function inheritance() { } inheritance.prototype = baseClass.prototype; subClass.prototype = new inheritance(); subClass.prototype.constructor = subClass; subClass.prototype.superClass = baseClass.prototype; }; function Demo(container) { this.superClass.constructor.call(this, container); this.gotoState(1 /* STATE_INIT */); }; extend(Demo, VT100); Demo.prototype.keysPressed = function(ch) { if (this.state == 5 /* STATE_EXEC */) { for (var i = 0; i < ch.length; i++) { var c = ch.charAt(i); if (c == '\u0003') { this.keys = ''; this.error('Interrupted'); return; } } } this.keys += ch; this.gotoState(this.state); }; Demo.prototype.gotoState = function(state, tmo) { this.state = state; if (!this.timer || tmo) { if (!tmo) { tmo = 1; } this.nextTimer = setTimeout(function(demo) { return function() { demo.demo(); }; }(this), tmo); } }; Demo.prototype.demo = function() { var done = false; this.nextTimer = undefined; while (!done) { var state = this.state; this.state = 2 /* STATE_PROMPT */; switch (state) { case 1 /* STATE_INIT */: done = this.doInit(); break; case 2 /* STATE_PROMPT */: done = this.doPrompt(); break; case 3 /* STATE_READLINE */: done = this.doReadLine(); break; case 4 /* STATE_COMMAND */: done = this.doCommand(); break; case 5 /* STATE_EXEC */: done = this.doExec(); break; case 6 /* STATE_NEW_Y_N */: done = this.doNewYN(); break; default: done = true; break; } } this.timer = this.nextTimer; this.nextTimer = undefined; }; Demo.prototype.ok = function() { this.vt100('OK\r\n'); this.gotoState(2 /* STATE_PROMPT */); }; Demo.prototype.error = function(msg) { if (msg == undefined) { msg = 'Syntax Error'; } this.printUnicode((this.cursorX != 0 ? '\r\n' : '') + '\u0007? ' + msg + (this.currentLineIndex >= 0 ? ' in line ' + this.program[this.evalLineIndex].lineNumber() : '') + '\r\n'); this.gotoState(2 /* STATE_PROMPT */); this.currentLineIndex = -1; this.evalLineIndex = -1; return undefined; }; Demo.prototype.doInit = function() { this.vars = new Object(); this.program = new Array(); this.printUnicode( '\u001Bc\u001B[34;4m' + 'ShellInABox Demo Script\u001B[24;31m\r\n' + '\r\n' + 'Copyright 2009 by Markus Gutschke <markus@shellinabox.com>\u001B[0m\r\n' + '\r\n' + '\r\n' + 'This script simulates a minimal BASIC interpreter, allowing you to\r\n' + 'experiment with the JavaScript terminal emulator that is part of\r\n' + 'the ShellInABox project.\r\n' + '\r\n' + 'Type HELP for a list of commands.\r\n' + '\r\n'); this.gotoState(2 /* STATE_PROMPT */); return false; }; Demo.prototype.doPrompt = function() { this.keys = ''; this.line = ''; this.currentLineIndex = -1; this.evalLineIndex = -1; this.vt100((this.cursorX != 0 ? '\r\n' : '') + '> '); this.gotoState(3 /* STATE_READLINE */); return false; }; Demo.prototype.printUnicode = function(s) { var out = ''; for (var i = 0; i < s.length; i++) { var c = s.charAt(i); if (c < '\x0080') { out += c; } else { var c = s.charCodeAt(i); if (c < 0x800) { out += String.fromCharCode(0xC0 + (c >> 6) ) + String.fromCharCode(0x80 + ( c & 0x3F)); } else if (c < 0x10000) { out += String.fromCharCode(0xE0 + (c >> 12) ) + String.fromCharCode(0x80 + ((c >> 6) & 0x3F)) + String.fromCharCode(0x80 + ( c & 0x3F)); } else if (c < 0x110000) { out += String.fromCharCode(0xF0 + (c >> 18) ) + String.fromCharCode(0x80 + ((c >> 12) & 0x3F)) + String.fromCharCode(0x80 + ((c >> 6) & 0x3F)) + String.fromCharCode(0x80 + ( c & 0x3F)); } } } this.vt100(out); }; Demo.prototype.doReadLine = function() { this.gotoState(3 /* STATE_READLINE */); var keys = this.keys; this.keys = ''; for (var i = 0; i < keys.length; i++) { var ch = keys.charAt(i); if (ch == '\u0008' || ch == '\u007F') { if (this.line.length > 0) { this.line = this.line.substr(0, this.line.length - 1); if (this.cursorX == 0) { var x = this.terminalWidth - 1; var y = this.cursorY - 1; this.gotoXY(x, y); this.vt100(' '); this.gotoXY(x, y); } else { this.vt100('\u0008 \u0008'); } } else { this.vt100('\u0007'); } } else if (ch >= ' ') { this.line += ch; this.printUnicode(ch); } else if (ch == '\r' || ch == '\n') { this.vt100('\r\n'); this.gotoState(4 /* STATE_COMMAND */); return false; } else if (ch == '\u001B') { // This was probably a function key. Just eat all of the following keys. break; } } return true; }; Demo.prototype.doCommand = function() { this.gotoState(2 /* STATE_PROMPT */); var tokens = new this.Tokens(this.line); this.line = ''; var cmd = tokens.nextToken(); if (cmd) { cmd = cmd; if (cmd.match(/^[0-9]+$/)) { tokens.removeLineNumber(); var lineNumber = parseInt(cmd); var index = this.findLine(lineNumber); if (tokens.nextToken() == null) { if (index > 0) { // Delete line from program this.program.splice(index, 1); } } else { tokens.reset(); if (index >= 0) { // Replace line in program this.program[index].setTokens(tokens); } else { // Add new line to program this.program.splice(-index - 1, 0, new this.Line(lineNumber, tokens)); } } } else { this.currentLineIndex = -1; this.evalLineIndex = -1; tokens.reset(); this.tokens = tokens; return this.doEval(); } } return false; }; Demo.prototype.doEval = function() { var token = this.tokens.peekToken(); if (token == "DIM") { this.tokens.consume(); this.doDim(); } else if (token == "END") { this.tokens.consume(); this.doEnd(); } else if (token == "GOTO") { this.tokens.consume(); this.doGoto(); } else if (token == "HELP") { this.tokens.consume(); if (this.tokens.nextToken() != undefined) { this.error('HELP does not take any arguments'); } else { this.vt100('Supported commands:\r\n' + 'DIM END GOTO HELP LET LIST NEW PRINT RUN\r\n'+ '\r\n'+ 'Supported functions:\r\n'+ 'ABS() ASC() ATN() CHR$() COS() EXP() INT() LEFT$() LEN()\r\n'+ 'LOG() MID$() POS() RIGHT$() RND() SGN() SIN() SPC() SQR()\r\n'+ 'STR$() TAB() TAN() TI VAL()\r\n'); } } else if (token == "LET") { this.tokens.consume(); this.doAssignment(); } else if (token == "LIST") { this.tokens.consume(); this.doList(); } else if (token == "NEW") { this.tokens.consume(); if (this.tokens.nextToken() != undefined) { this.error('NEW does not take any arguments'); } else if (this.currentLineIndex >= 0) { this.error('Cannot call NEW from a program'); } else if (this.program.length == 0) { this.ok(); } else { this.vt100('Do you really want to delete the program (y/N) '); this.gotoState(6 /* STATE_NEW_Y_N */); } } else if (token == "PRINT" || token == "?") { this.tokens.consume(); this.doPrint(); } else if (token == "RUN") { this.tokens.consume(); if (this.tokens.nextToken() != null) { this.error('RUN does not take any parameters'); } else if (this.program.length > 0) { this.currentLineIndex = 0; this.vars = new Object(); this.gotoState(5 /* STATE_EXEC */); } else { this.ok(); } } else { this.doAssignment(); } return false; }; Demo.prototype.arrayIndex = function() { var token = this.tokens.peekToken(); var arr = ''; if (token == '(') { this.tokens.consume(); do { var idx = this.expr(); if (idx == undefined) { return idx; } else if (idx.type() != 1 /* TYPE_NUMBER */) { return this.error('Numeric value expected'); } idx = Math.floor(idx.val()); if (idx < 0) { return this.error('Indices have to be positive'); } arr += ',' + idx; token = this.tokens.nextToken(); } while (token == ','); if (token != ')') { return this.error('")" expected'); } } return arr; }; Demo.prototype.toInt = function(v) { if (v < 0) { return -Math.floor(-v); } else { return Math.floor( v); } }; Demo.prototype.doAssignment = function() { var id = this.tokens.nextToken(); if (!id || !id.match(/^[A-Za-z][A-Za-z0-9_]*$/)) { return this.error('Identifier expected'); } var token = this.tokens.peekToken(); var isString = false; var isInt = false; if (token == '$') { isString = true; this.tokens.consume(); } else if (token == '%') { isInt = true; this.tokens.consume(); } var arr = this.arrayIndex(); if (arr == undefined) { return arr; } token = this.tokens.nextToken(); if (token != '=') { return this.error('"=" expected'); } var value = this.expr(); if (value == undefined) { return value; } if (isString) { if (value.type() != 0 /* TYPE_STRING */) { return this.error('String expected'); } this.vars['str_' + id + arr] = value; } else { if (value.type() != 1 /* TYPE_NUMBER */) { return this.error('Numeric value expected'); } if (isInt) { value = this.toInt(value.val()); value = new this.Value(1 /* TYPE_NUMBER */, '' + value, value); this.vars['int_' + id + arr] = value; } else { this.vars['var_' + id + arr] = value; } } }; Demo.prototype.doDim = function() { for (;;) { var token = this.tokens.nextToken(); if (token == undefined) { return; } if (!token || !token.match(/^[A-Za-z][A-Za-z0-9_]*$/)) { return this.error('Identifier expected'); } token = this.tokens.nextToken(); if (token == '$' || token == '%') { token = this.tokens.nextToken(); } if (token != '(') { return this.error('"(" expected'); } do { var size = this.expr(); if (!size) { return size; } if (size.type() != 1 /* TYPE_NUMBER */) { return this.error('Numeric value expected'); } if (Math.floor(size.val()) < 1) { return this.error('Range error'); } token = this.tokens.nextToken(); } while (token == ','); if (token != ')') { return this.error('")" expected'); } if (this.tokens.peekToken() != ',') { break; } this.tokens.consume(); } if (this.tokens.peekToken() != undefined) { return this.error(); } }; Demo.prototype.doEnd = function() { if (this.evalLineIndex < 0) { return this.error('Cannot use END interactively'); } if (this.tokens.nextToken() != undefined) { return this.error('END does not take any arguments'); } this.currentLineIndex = this.program.length; }; Demo.prototype.doGoto = function() { if (this.evalLineIndex < 0) { return this.error('Cannot use GOTO interactively'); } var value = this.expr(); if (value == undefined) { return; } if (value.type() != 1 /* TYPE_NUMBER */) { return this.error('Numeric value expected'); } if (this.tokens.nextToken() != undefined) { return this.error('GOTO takes exactly one numeric argument'); } var number = this.toInt(value.val()); if (number <= 0) { return this.error('Range error'); } var idx = this.findLine(number); if (idx < 0) { return this.error('No line number ' + line); } this.currentLineIndex = idx; }; Demo.prototype.doList = function() { var start = undefined; var stop = undefined; var token = this.tokens.nextToken(); if (token) { if (token != '-' && !token.match(/[0-9]+/)) { return this.error('LIST can optional take a start and stop line number'); } if (token != '-') { start = parseInt(token); token = this.tokens.nextToken(); } if (!token) { stop = start; } else { if (token != '-') { return this.error('Dash expected'); } token = this.tokens.nextToken(); if (token) { if (!token.match(/[0-9]+/)) { return this.error( 'LIST can optionally take a start and stop line number'); } stop = parseInt(token); if (start && stop < start) { return this.error('Start line number has to come before stop'); } } if (this.tokens.peekToken()) { return this.error('Unexpected trailing arguments'); } } } var listed = false; for (var i = 0; i < this.program.length; i++) { var line = this.program[i]; var lineNumber = line.lineNumber(); if (start != undefined && start > lineNumber) { continue; } if (stop != undefined && stop < lineNumber) { break; } listed = true; this.vt100('' + line.lineNumber() + ' '); line.tokens().reset(); var space = true; var id = false; for (var token; (token = line.tokens().nextToken()) != null; ) { switch (token) { case '=': case '+': case '-': case '*': case '/': case '\\': case '^': this.vt100((space ? '' : ' ') + token + ' '); space = true; id = false; break; case '(': case ')': case '$': case '%': case '#': this.vt100(token); space = false; id = false; break; case ',': case ';': case ':': this.vt100(token + ' '); space = true; id = false; break; case '?': token = 'PRINT'; // fall thru default: this.printUnicode((id ? ' ' : '') + token); space = false; id = true; break; } } this.vt100('\r\n'); } if (!listed) { this.ok(); } }; Demo.prototype.doPrint = function() { var tokens = this.tokens; var last = undefined; for (var token; (token = tokens.peekToken()); ) { last = token; if (token == ',') { this.vt100('\t'); tokens.consume(); } else if (token == ';') { // Do nothing tokens.consume(); } else { var value = this.expr(); if (value == undefined) { return; } this.printUnicode(value.toString()); } } if (last != ';') { this.vt100('\r\n'); } }; Demo.prototype.doExec = function() { this.evalLineIndex = this.currentLineIndex++; this.tokens = this.program[this.evalLineIndex].tokens(); this.tokens.reset(); this.doEval(); if (this.currentLineIndex < 0) { return false; } else if (this.currentLineIndex >= this.program.length) { this.currentLineIndex = -1; this.ok(); return false; } else { this.gotoState(5 /* STATE_EXEC */, 20); return true; } }; Demo.prototype.doNewYN = function() { for (var i = 0; i < this.keys.length; ) { var ch = this.keys.charAt(i++); if (ch == 'n' || ch == 'N' || ch == '\r' || ch == '\n') { this.vt100('N\r\n'); this.keys = this.keys.substr(i); this.error('Aborted'); return false; } else if (ch == 'y' || ch == 'Y') { this.vt100('Y\r\n'); this.vars = new Object(); this.program.splice(0, this.program.length); this.keys = this.keys.substr(i); this.ok(); return false; } else { this.vt100('\u0007'); } } this.gotoState(6 /* STATE_NEW_Y_N */); return true; }; Demo.prototype.findLine = function(lineNumber) { var l = 0; var h = this.program.length; while (h > l) { var m = Math.floor((l + h) / 2); var n = this.program[m].lineNumber(); if (n == lineNumber) { return m; } else if (n > lineNumber) { h = m; } else { l = m + 1; } } return -l - 1; }; Demo.prototype.expr = function() { var value = this.term(); while (value) { var token = this.tokens.peekToken(); if (token != '+' && token != '-') { break; } this.tokens.consume(); var v = this.term(); if (!v) { return v; } if (value.type() != v.type()) { if (value.type() != 0 /* TYPE_STRING */) { value = new this.Value(0 /* TYPE_STRING */, ''+value.val(), ''+value.val()); } if (v.type() != 0 /* TYPE_STRING */) { v = new this.Value(0 /* TYPE_STRING */, ''+v.val(), ''+v.val()); } } if (token == '-') { if (value.type() == 0 /* TYPE_STRING */) { return this.error('Cannot subtract strings'); } v = value.val() - v.val(); } else { v = value.val() + v.val(); } if (v == NaN) { return this.error('Numeric range error'); } value = new this.Value(value.type(), ''+v, v); } return value; }; Demo.prototype.term = function() { var value = this.expn(); while (value) { var token = this.tokens.peekToken(); if (token != '*' && token != '/' && token != '\\') { break; } this.tokens.consume(); var v = this.expn(); if (!v) { return v; } if (value.type() != 1 /* TYPE_NUMBER */ || v.type() != 1 /* TYPE_NUMBER */) { return this.error('Cannot multiply or divide strings'); } if (token == '*') { v = value.val() * v.val(); } else { v = value.val() / v.val(); if (token == '\\') { v = this.toInt(v); } } if (v == NaN) { return this.error('Numeric range error'); } value = new this.Value(1 /* TYPE_NUMBER */, ''+v, v); } return value; }; Demo.prototype.expn = function() { var value = this.intrinsic(); var token = this.tokens.peekToken(); if (token == '^') { this.tokens.consume(); var exp = this.intrinsic(); if (exp == undefined || exp.val() == NaN) { return exp; } if (value.type() != 1 /* TYPE_NUMBER */ || exp.type() != 1 /* TYPE_NUMBER */) { return this.error("Numeric value expected"); } var v = Math.pow(value.val(), exp.val()); value = new this.Value(1 /* TYPE_NUMBER */, '' + v, v); } return value; }; Demo.prototype.intrinsic = function() { var token = this.tokens.peekToken(); var args = undefined; var value, v, fnc, arg1, arg2, arg3; if (!token) { return this.error('Unexpected end of input'); } else if (token.match(/^(?:ABS|ASC|ATN|CHR\$|COS|EXP|INT|LEN|LOG|POS|RND|SGN|SIN|SPC|SQR|STR\$|TAB|TAN|VAL)$/)) { fnc = token; args = 1; } else if (token.match(/^(?:LEFT\$|RIGHT\$)$/)) { fnc = token; args = 2; } else if (token == 'MID$') { fnc = token; args = 3; } else if (token == 'TI') { this.tokens.consume(); v = (new Date()).getTime() / 1000.0; return new this.Value(1 /* TYPE_NUMBER */, '' + v, v); } else { return this.factor(); } this.tokens.consume(); token = this.tokens.nextToken(); if (token != '(') { return this.error('"(" expected'); } arg1 = this.expr(); if (!arg1) { return arg1; } token = this.tokens.nextToken(); if (--args) { if (token != ',') { return this.error('"," expected'); } arg2 = this.expr(); if (!arg2) { return arg2; } token = this.tokens.nextToken(); if (--args) { if (token != ',') { return this.error('"," expected'); } arg3 = this.expr(); if (!arg3) { return arg3; } token = this.tokens.nextToken(); } } if (token != ')') { return this.error('")" expected'); } switch (fnc) { case 'ASC': if (arg1.type() != 0 /* TYPE_STRING */ || arg1.val().length < 1) { return this.error('Non-empty string expected'); } v = arg1.val().charCodeAt(0); value = new this.Value(1 /* TYPE_NUMBER */, '' + v, v); break; case 'LEN': if (arg1.type() != 0 /* TYPE_STRING */) { return this.error('String expected'); } v = arg1.val().length; value = new this.Value(1 /* TYPE_NUMBER */, '' + v, v); break; case 'LEFT$': if (arg1.type() != 0 /* TYPE_STRING */ || arg2.type() != 1 /* TYPE_NUMBER */ || arg2.type() < 0) { return this.error('Invalid arguments'); } v = arg1.val().substr(0, Math.floor(arg2.val())); value = new this.Value(0 /* TYPE_STRING */, v, v); break; case 'MID$': if (arg1.type() != 0 /* TYPE_STRING */ || arg2.type() != 1 /* TYPE_NUMBER */ || arg3.type() != 1 /* TYPE_NUMBER */ || arg2.val() < 0 || arg3.val() < 0) { return this.error('Invalid arguments'); } v = arg1.val().substr(Math.floor(arg2.val()), Math.floor(arg3.val())); value = new this.Value(0 /* TYPE_STRING */, v, v); break; case 'RIGHT$': if (arg1.type() != 0 /* TYPE_STRING */ || arg2.type() != 1 /* TYPE_NUMBER */ || arg2.type() < 0) { return this.error('Invalid arguments'); } v = Math.floor(arg2.val()); if (v > arg1.val().length) { v = arg1.val().length; } v = arg1.val().substr(arg1.val().length - v); value = new this.Value(0 /* TYPE_STRING */, v, v); break; case 'STR$': value = new this.Value(0 /* TYPE_STRING */, arg1.toString(), arg1.toString()); break; case 'VAL': if (arg1.type() == 1 /* TYPE_NUMBER */) { value = arg1; } else { if (arg1.val().match(/^[0-9]+$/)) { v = parseInt(arg1.val()); } else { v = parseFloat(arg1.val()); } value = new this.Value(1 /* TYPE_NUMBER */, '' + v, v); } break; default: if (arg1.type() != 1 /* TYPE_NUMBER */) { return this.error('Numeric value expected'); } switch (fnc) { case 'CHR$': if (arg1.val() < 0 || arg1.val() > 65535) { return this.error('Invalid Unicode range'); } v = String.fromCharCode(arg1.val()); value = new this.Value(0 /* TYPE_STRING */, v, v); break; case 'SPC': if (arg1.val() < 0) { return this.error('Range error'); } v = arg1.val() >= 1 ? '\u001B[' + Math.floor(arg1.val()) + 'C' : ''; value = new this.Value(0 /* TYPE_STRING */, v, v); break; case 'TAB': if (arg1.val() < 0) { return this.error('Range error'); } v = '\r' + (arg1.val() >= 1 ? '\u001B[' + (Math.floor(arg1.val())*8) + 'C' : ''); value = new this.Value(0 /* TYPE_STRING */, v, v); break; default: switch (fnc) { case 'ABS': v = Math.abs(arg1.val()); break; case 'ATN': v = Math.atan(arg1.val()); break; case 'COS': v = Math.cos(arg1.val()); break; case 'EXP': v = Math.exp(arg1.val()); break; case 'INT': v = Math.floor(arg1.val()); break; case 'LOG': v = Math.log(arg1.val()); break; case 'POS': v = this.cursorX; break; case 'SGN': v = arg1.val() < 0 ? -1 : arg1.val() ? 1 : 0; break; case 'SIN': v = Math.sin(arg1.val()); break; case 'SQR': v = Math.sqrt(arg1.val()); break; case 'TAN': v = Math.tan(arg1.val()); break; case 'RND': if (this.prng == undefined) { this.prng = 1013904223; } if (arg1.type() == 1 /* TYPE_NUMBER */ && arg1.val() < 0) { this.prng = Math.floor(1664525*arg1.val()) & 0xFFFFFFFF; } if (arg1.type() != 1 /* TYPE_NUMBER */ || arg1.val() != 0) { this.prng = Math.floor(1664525*this.prng + 1013904223) & 0xFFFFFFFF; } v = ((this.prng & 0x7FFFFFFF) / 65536.0) / 32768; break; } value = new this.Value(1 /* TYPE_NUMBER */, '' + v, v); } } if (v == NaN) { return this.error('Numeric range error'); } return value; }; Demo.prototype.factor = function() { var token = this.tokens.nextToken(); var value; if (token == '-') { value = this.expr(); if (!value) { return value; } if (value.type() != 1 /* TYPE_NUMBER */) { return this.error('Numeric value expected'); } return new this.Value(1 /* TYPE_NUMBER */, '' + -value.val(), -value.val()); } if (!token) { return this.error(); } if (token == '(') { value = this.expr(); token = this.tokens.nextToken(); if (token != ')' && value != undefined) { return this.error('")" expected'); } } else { var str; if ((str = token.match(/^"(.*)"/)) != null) { value = new this.Value(0 /* TYPE_STRING */, str[1], str[1]); } else if (token.match(/^[0-9]/)) { var number; if (token.match(/^[0-9]*$/)) { number = parseInt(token); } else { number = parseFloat(token); } if (number == NaN) { return this.error('Numeric range error'); } value = new this.Value(1 /* TYPE_NUMBER */, token, number); } else if (token.match(/^[A-Za-z][A-Za-z0-9_]*$/)) { if (this.tokens.peekToken() == '$') { this.tokens.consume(); var arr= this.arrayIndex(); if (arr == undefined) { return arr; } value = this.vars['str_' + token + arr]; if (value == undefined) { value= new this.Value(0 /* TYPE_STRING */, '', ''); } } else { var n = 'var_'; if (this.tokens.peekToken() == '%') { this.tokens.consume(); n = 'int_'; } var arr= this.arrayIndex(); if (arr == undefined) { return arr; } value = this.vars[n + token + arr]; if (value == undefined) { value= new this.Value(1 /* TYPE_NUMBER */, '0', 0); } } } else { return this.error(); } } return value; }; Demo.prototype.Tokens = function(line) { this.line = line; this.tokens = line; this.len = undefined; }; Demo.prototype.Tokens.prototype.peekToken = function() { this.len = undefined; this.tokens = this.tokens.replace(/^[ \t]*/, ''); var tokens = this.tokens; if (!tokens.length) { return null; } var token = tokens.charAt(0); switch (token) { case '<': if (tokens.length > 1) { if (tokens.charAt(1) == '>') { token = '<>'; } else if (tokens.charAt(1) == '=') { token = '<='; } } break; case '>': if (tokens.charAt(1) == '=') { token = '>='; } break; case '=': case '+': case '-': case '*': case '/': case '\\': case '^': case '(': case ')': case '?': case ',': case ';': case ':': case '$': case '%': case '#': break; case '"': token = tokens.match(/"((?:""|[^"])*)"/); // " if (!token) { token = undefined; } else { this.len = token[0].length; token = '"' + token[1].replace(/""/g, '"') + '"'; } break; default: if (token >= '0' && token <= '9' || token == '.') { token = tokens.match(/^[0-9]*(?:[.][0-9]*)?(?:[eE][-+]?[0-9]+)?/); if (!token) { token = undefined; } else { token = token[0]; } } else if (token >= 'A' && token <= 'Z' || token >= 'a' && token <= 'z') { token = tokens.match(/^(?:CHR\$|STR\$|LEFT\$|RIGHT\$|MID\$)/i); if (token) { token = token[0].toUpperCase(); } else { token = tokens.match(/^[A-Za-z][A-Za-z0-9_]*/); if (!token) { token = undefined; } else { token = token[0].toUpperCase(); } } } else { token = ''; } } if (this.len == undefined) { if (token) { this.len = token.length; } else { this.len = 1; } } return token; }; Demo.prototype.Tokens.prototype.consume = function() { if (this.len) { this.tokens = this.tokens.substr(this.len); this.len = undefined; } }; Demo.prototype.Tokens.prototype.nextToken = function() { var token = this.peekToken(); this.consume(); return token; }; Demo.prototype.Tokens.prototype.removeLineNumber = function() { this.line = this.line.replace(/^[0-9]*[ \t]*/, ''); }; Demo.prototype.Tokens.prototype.reset = function() { this.tokens = this.line; }; Demo.prototype.Line = function(lineNumber, tokens) { this.lineNumber_ = lineNumber; this.tokens_ = tokens; }; Demo.prototype.Line.prototype.lineNumber = function() { return this.lineNumber_; }; Demo.prototype.Line.prototype.tokens = function() { return this.tokens_; }; Demo.prototype.Line.prototype.setTokens = function(tokens) { this.tokens_ = tokens; }; Demo.prototype.Line.prototype.sort = function(a, b) { return a.lineNumber_ - b.lineNumber_; }; Demo.prototype.Value = function(type, str, val) { this.t = type; this.s = str; this.v = val; }; Demo.prototype.Value.prototype.type = function() { return this.t; }; Demo.prototype.Value.prototype.val = function() { return this.v; }; Demo.prototype.Value.prototype.toString = function() { return this.s; };
JavaScript
// VT100.js -- JavaScript based terminal emulator // Copyright (C) 2008-2010 Markus Gutschke <markus@shellinabox.com> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // In addition to these license terms, the author grants the following // additional rights: // // If you modify this program, or any covered work, by linking or // combining it with the OpenSSL project's OpenSSL library (or a // modified version of that library), containing parts covered by the // terms of the OpenSSL or SSLeay licenses, the author // grants you additional permission to convey the resulting work. // Corresponding Source for a non-source form of such a combination // shall include the source code for the parts of OpenSSL used as well // as that of the covered work. // // You may at your option choose to remove this additional permission from // the work, or from any part of it. // // It is possible to build this program in a way that it loads OpenSSL // libraries at run-time. If doing so, the following notices are required // by the OpenSSL and SSLeay licenses: // // This product includes software developed by the OpenSSL Project // for use in the OpenSSL Toolkit. (http://www.openssl.org/) // // This product includes cryptographic software written by Eric Young // (eay@cryptsoft.com) // // // The most up-to-date version of this program is always available from // http://shellinabox.com // // // Notes: // // The author believes that for the purposes of this license, you meet the // requirements for publishing the source code, if your web server publishes // the source in unmodified form (i.e. with licensing information, comments, // formatting, and identifier names intact). If there are technical reasons // that require you to make changes to the source code when serving the // JavaScript (e.g to remove pre-processor directives from the source), these // changes should be done in a reversible fashion. // // The author does not consider websites that reference this script in // unmodified form, and web servers that serve this script in unmodified form // to be derived works. As such, they are believed to be outside of the // scope of this license and not subject to the rights or restrictions of the // GNU General Public License. // // If in doubt, consult a legal professional familiar with the laws that // apply in your country. // #define ESnormal 0 // #define ESesc 1 // #define ESsquare 2 // #define ESgetpars 3 // #define ESgotpars 4 // #define ESdeviceattr 5 // #define ESfunckey 6 // #define EShash 7 // #define ESsetG0 8 // #define ESsetG1 9 // #define ESsetG2 10 // #define ESsetG3 11 // #define ESbang 12 // #define ESpercent 13 // #define ESignore 14 // #define ESnonstd 15 // #define ESpalette 16 // #define EStitle 17 // #define ESss2 18 // #define ESss3 19 // #define ATTR_DEFAULT 0x00F0 // #define ATTR_REVERSE 0x0100 // #define ATTR_UNDERLINE 0x0200 // #define ATTR_DIM 0x0400 // #define ATTR_BRIGHT 0x0800 // #define ATTR_BLINK 0x1000 // #define MOUSE_DOWN 0 // #define MOUSE_UP 1 // #define MOUSE_CLICK 2 function VT100(container) { if (typeof linkifyURLs == 'undefined' || linkifyURLs <= 0) { this.urlRE = null; } else { this.urlRE = new RegExp( // Known URL protocol are "http", "https", and "ftp". '(?:http|https|ftp)://' + // Optionally allow username and passwords. '(?:[^:@/ \u00A0]*(?::[^@/ \u00A0]*)?@)?' + // Hostname. '(?:[1-9][0-9]{0,2}(?:[.][1-9][0-9]{0,2}){3}|' + '[0-9a-fA-F]{0,4}(?::{1,2}[0-9a-fA-F]{1,4})+|' + '(?!-)[^[!"#$%&\'()*+,/:;<=>?@\\^_`{|}~\u0000- \u007F-\u00A0]+)' + // Port '(?::[1-9][0-9]*)?' + // Path. '(?:/(?:(?![/ \u00A0]|[,.)}"\u0027!]+[ \u00A0]|[,.)}"\u0027!]+$).)*)*|' + (linkifyURLs <= 1 ? '' : // Also support URLs without a protocol (assume "http"). // Optional username and password. '(?:[^:@/ \u00A0]*(?::[^@/ \u00A0]*)?@)?' + // Hostnames must end with a well-known top-level domain or must be // numeric. '(?:[1-9][0-9]{0,2}(?:[.][1-9][0-9]{0,2}){3}|' + 'localhost|' + '(?:(?!-)' + '[^.[!"#$%&\'()*+,/:;<=>?@\\^_`{|}~\u0000- \u007F-\u00A0]+[.]){2,}' + '(?:(?:com|net|org|edu|gov|aero|asia|biz|cat|coop|info|int|jobs|mil|mobi|'+ 'museum|name|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|' + 'au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|' + 'ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|' + 'dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|' + 'gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|' + 'ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|' + 'lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|' + 'mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|' + 'pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|' + 'sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|' + 'tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|' + 'yu|za|zm|zw|arpa)(?![a-zA-Z0-9])|[Xx][Nn]--[-a-zA-Z0-9]+))' + // Port '(?::[1-9][0-9]{0,4})?' + // Path. '(?:/(?:(?![/ \u00A0]|[,.)}"\u0027!]+[ \u00A0]|[,.)}"\u0027!]+$).)*)*|') + // In addition, support e-mail address. Optionally, recognize "mailto:" '(?:mailto:)' + (linkifyURLs <= 1 ? '' : '?') + // Username: '[-_.+a-zA-Z0-9]+@' + // Hostname. '(?!-)[-a-zA-Z0-9]+(?:[.](?!-)[-a-zA-Z0-9]+)?[.]' + '(?:(?:com|net|org|edu|gov|aero|asia|biz|cat|coop|info|int|jobs|mil|mobi|'+ 'museum|name|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|' + 'au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|' + 'ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|' + 'dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|' + 'gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|' + 'ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|' + 'lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|' + 'mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|' + 'pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|' + 'sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|' + 'tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|' + 'yu|za|zm|zw|arpa)(?![a-zA-Z0-9])|[Xx][Nn]--[-a-zA-Z0-9]+)' + // Optional arguments '(?:[?](?:(?![ \u00A0]|[,.)}"\u0027!]+[ \u00A0]|[,.)}"\u0027!]+$).)*)?'); } this.getUserSettings(); this.initializeElements(container); this.maxScrollbackLines = 500; this.npar = 0; this.par = [ ]; this.isQuestionMark = false; this.savedX = [ ]; this.savedY = [ ]; this.savedAttr = [ ]; this.savedUseGMap = 0; this.savedGMap = [ this.Latin1Map, this.VT100GraphicsMap, this.CodePage437Map, this.DirectToFontMap ]; this.savedValid = [ ]; this.respondString = ''; this.titleString = ''; this.internalClipboard = undefined; this.reset(true); } VT100.prototype.reset = function(clearHistory) { this.isEsc = 0 /* ESnormal */; this.needWrap = false; this.autoWrapMode = true; this.dispCtrl = false; this.toggleMeta = false; this.insertMode = false; this.applKeyMode = false; this.cursorKeyMode = false; this.crLfMode = false; this.offsetMode = false; this.mouseReporting = false; this.printing = false; if (typeof this.printWin != 'undefined' && this.printWin && !this.printWin.closed) { this.printWin.close(); } this.printWin = null; this.utfEnabled = this.utfPreferred; this.utfCount = 0; this.utfChar = 0; this.color = 'ansi0 bgAnsi15'; this.style = ''; this.attr = 0x00F0 /* ATTR_DEFAULT */; this.useGMap = 0; this.GMap = [ this.Latin1Map, this.VT100GraphicsMap, this.CodePage437Map, this.DirectToFontMap]; this.translate = this.GMap[this.useGMap]; this.top = 0; this.bottom = this.terminalHeight; this.lastCharacter = ' '; this.userTabStop = [ ]; if (clearHistory) { for (var i = 0; i < 2; i++) { while (this.console[i].firstChild) { this.console[i].removeChild(this.console[i].firstChild); } } } this.enableAlternateScreen(false); var wasCompressed = false; var transform = this.getTransformName(); if (transform) { for (var i = 0; i < 2; ++i) { wasCompressed |= this.console[i].style[transform] != ''; this.console[i].style[transform] = ''; } this.cursor.style[transform] = ''; this.space.style[transform] = ''; if (transform == 'filter') { this.console[this.currentScreen].style.width = ''; } } this.scale = 1.0; if (wasCompressed) { this.resizer(); } this.gotoXY(0, 0); this.showCursor(); this.isInverted = false; this.refreshInvertedState(); this.clearRegion(0, 0, this.terminalWidth, this.terminalHeight, this.color, this.style); }; VT100.prototype.addListener = function(elem, event, listener) { try { if (elem.addEventListener) { elem.addEventListener(event, listener, false); } else { elem.attachEvent('on' + event, listener); } } catch (e) { } }; VT100.prototype.getUserSettings = function() { // Compute hash signature to identify the entries in the userCSS menu. // If the menu is unchanged from last time, default values can be // looked up in a cookie associated with this page. this.signature = 3; this.utfPreferred = true; this.visualBell = typeof suppressAllAudio != 'undefined' && suppressAllAudio; this.autoprint = true; this.softKeyboard = false; this.blinkingCursor = true; if (this.visualBell) { this.signature = Math.floor(16807*this.signature + 1) % ((1 << 31) - 1); } if (typeof userCSSList != 'undefined') { for (var i = 0; i < userCSSList.length; ++i) { var label = userCSSList[i][0]; for (var j = 0; j < label.length; ++j) { this.signature = Math.floor(16807*this.signature+ label.charCodeAt(j)) % ((1 << 31) - 1); } if (userCSSList[i][1]) { this.signature = Math.floor(16807*this.signature + 1) % ((1 << 31) - 1); } } } var key = 'shellInABox=' + this.signature + ':'; var settings = document.cookie.indexOf(key); if (settings >= 0) { settings = document.cookie.substr(settings + key.length). replace(/([0-1]*).*/, "$1"); if (settings.length == 5 + (typeof userCSSList == 'undefined' ? 0 : userCSSList.length)) { this.utfPreferred = settings.charAt(0) != '0'; this.visualBell = settings.charAt(1) != '0'; this.autoprint = settings.charAt(2) != '0'; this.softKeyboard = settings.charAt(3) != '0'; this.blinkingCursor = settings.charAt(4) != '0'; if (typeof userCSSList != 'undefined') { for (var i = 0; i < userCSSList.length; ++i) { userCSSList[i][2] = settings.charAt(i + 5) != '0'; } } } } this.utfEnabled = this.utfPreferred; }; VT100.prototype.storeUserSettings = function() { var settings = 'shellInABox=' + this.signature + ':' + (this.utfEnabled ? '1' : '0') + (this.visualBell ? '1' : '0') + (this.autoprint ? '1' : '0') + (this.softKeyboard ? '1' : '0') + (this.blinkingCursor ? '1' : '0'); if (typeof userCSSList != 'undefined') { for (var i = 0; i < userCSSList.length; ++i) { settings += userCSSList[i][2] ? '1' : '0'; } } var d = new Date(); d.setDate(d.getDate() + 3653); document.cookie = settings + ';expires=' + d.toGMTString(); }; VT100.prototype.initializeUserCSSStyles = function() { this.usercssActions = []; if (typeof userCSSList != 'undefined') { var menu = ''; var group = ''; var wasSingleSel = 1; var beginOfGroup = 0; for (var i = 0; i <= userCSSList.length; ++i) { if (i < userCSSList.length) { var label = userCSSList[i][0]; var newGroup = userCSSList[i][1]; var enabled = userCSSList[i][2]; // Add user style sheet to document var style = document.createElement('link'); var id = document.createAttribute('id'); id.nodeValue = 'usercss-' + i; style.setAttributeNode(id); var rel = document.createAttribute('rel'); rel.nodeValue = 'stylesheet'; style.setAttributeNode(rel); var href = document.createAttribute('href'); href.nodeValue = 'usercss-' + i + '.css'; style.setAttributeNode(href); var type = document.createAttribute('type'); type.nodeValue = 'text/css'; style.setAttributeNode(type); document.getElementsByTagName('head')[0].appendChild(style); style.disabled = !enabled; } // Add entry to menu if (newGroup || i == userCSSList.length) { if (beginOfGroup != 0 && (i - beginOfGroup > 1 || !wasSingleSel)) { // The last group had multiple entries that are mutually exclusive; // or the previous to last group did. In either case, we need to // append a "<hr />" before we can add the last group to the menu. menu += '<hr />'; } wasSingleSel = i - beginOfGroup < 1; menu += group; group = ''; for (var j = beginOfGroup; j < i; ++j) { this.usercssActions[this.usercssActions.length] = function(vt100, current, begin, count) { // Deselect all other entries in the group, then either select // (for multiple entries in group) or toggle (for on/off entry) // the current entry. return function() { var entry = vt100.getChildById(vt100.menu, 'beginusercss'); var i = -1; var j = -1; for (var c = count; c > 0; ++j) { if (entry.tagName == 'LI') { if (++i >= begin) { --c; var label = vt100.usercss.childNodes[j]; // Restore label to just the text content if (typeof label.textContent == 'undefined') { var s = label.innerText; label.innerHTML = ''; label.appendChild(document.createTextNode(s)); } else { label.textContent= label.textContent; } // User style sheets are numbered sequentially var sheet = document.getElementById( 'usercss-' + i); if (i == current) { if (count == 1) { sheet.disabled = !sheet.disabled; } else { sheet.disabled = false; } if (!sheet.disabled) { label.innerHTML= '<img src="enabled.gif" />' + label.innerHTML; } } else { sheet.disabled = true; } userCSSList[i][2] = !sheet.disabled; } } entry = entry.nextSibling; } // If the font size changed, adjust cursor and line dimensions this.cursor.style.cssText= ''; this.cursorWidth = this.cursor.clientWidth; this.cursorHeight = this.lineheight.clientHeight; for (i = 0; i < this.console.length; ++i) { for (var line = this.console[i].firstChild; line; line = line.nextSibling) { line.style.height = this.cursorHeight + 'px'; } } vt100.resizer(); }; }(this, j, beginOfGroup, i - beginOfGroup); } if (i == userCSSList.length) { break; } beginOfGroup = i; } // Collect all entries in a group, before attaching them to the menu. // This is necessary as we don't know whether this is a group of // mutually exclusive options (which should be separated by "<hr />" on // both ends), or whether this is a on/off toggle, which can be grouped // together with other on/off options. group += '<li>' + (enabled ? '<img src="enabled.gif" />' : '') + label + '</li>'; } this.usercss.innerHTML = menu; } }; VT100.prototype.resetLastSelectedKey = function(e) { var key = this.lastSelectedKey; if (!key) { return false; } var position = this.mousePosition(e); // We don't get all the necessary events to reliably reselect a key // if we moved away from it and then back onto it. We approximate the // behavior by remembering the key until either we release the mouse // button (we might never get this event if the mouse has since left // the window), or until we move away too far. var box = this.keyboard.firstChild; if (position[0] < box.offsetLeft + key.offsetWidth || position[1] < box.offsetTop + key.offsetHeight || position[0] >= box.offsetLeft + box.offsetWidth - key.offsetWidth || position[1] >= box.offsetTop + box.offsetHeight - key.offsetHeight || position[0] < box.offsetLeft + key.offsetLeft - key.offsetWidth || position[1] < box.offsetTop + key.offsetTop - key.offsetHeight || position[0] >= box.offsetLeft + key.offsetLeft + 2*key.offsetWidth || position[1] >= box.offsetTop + key.offsetTop + 2*key.offsetHeight) { if (this.lastSelectedKey.className) log.console('reset: deselecting'); this.lastSelectedKey.className = ''; this.lastSelectedKey = undefined; } return false; }; VT100.prototype.showShiftState = function(state) { var style = document.getElementById('shift_state'); if (state) { this.setTextContentRaw(style, '#vt100 #keyboard .shifted {' + 'display: inline }' + '#vt100 #keyboard .unshifted {' + 'display: none }'); } else { this.setTextContentRaw(style, ''); } var elems = this.keyboard.getElementsByTagName('I'); for (var i = 0; i < elems.length; ++i) { if (elems[i].id == '16') { elems[i].className = state ? 'selected' : ''; } } }; VT100.prototype.showCtrlState = function(state) { var ctrl = this.getChildById(this.keyboard, '17' /* Ctrl */); if (ctrl) { ctrl.className = state ? 'selected' : ''; } }; VT100.prototype.showAltState = function(state) { var alt = this.getChildById(this.keyboard, '18' /* Alt */); if (alt) { alt.className = state ? 'selected' : ''; } }; VT100.prototype.clickedKeyboard = function(e, elem, ch, key, shift, ctrl, alt){ var fake = [ ]; fake.charCode = ch; fake.keyCode = key; fake.ctrlKey = ctrl; fake.shiftKey = shift; fake.altKey = alt; fake.metaKey = alt; return this.handleKey(fake); }; VT100.prototype.addKeyBinding = function(elem, ch, key, CH, KEY) { if (elem == undefined) { return; } if (ch == '\u00A0') { // &nbsp; should be treated as a regular space character. ch = ' '; } if (ch != undefined && CH == undefined) { // For letter keys, we automatically compute the uppercase character code // from the lowercase one. CH = ch.toUpperCase(); } if (KEY == undefined && key != undefined) { // Most keys have identically key codes for both lowercase and uppercase // keypresses. Normally, only function keys would have distinct key codes, // whereas regular keys have character codes. KEY = key; } else if (KEY == undefined && CH != undefined) { // For regular keys, copy the character code to the key code. KEY = CH.charCodeAt(0); } if (key == undefined && ch != undefined) { // For regular keys, copy the character code to the key code. key = ch.charCodeAt(0); } // Convert characters to numeric character codes. If the character code // is undefined (i.e. this is a function key), set it to zero. ch = ch ? ch.charCodeAt(0) : 0; CH = CH ? CH.charCodeAt(0) : 0; // Mouse down events high light the key. We also set lastSelectedKey. This // is needed to that mouseout/mouseover can keep track of the key that // is currently being clicked. this.addListener(elem, 'mousedown', function(vt100, elem, key) { return function(e) { if ((e.which || e.button) == 1) { if (vt100.lastSelectedKey) { vt100.lastSelectedKey.className= ''; } // Highlight the key while the mouse button is held down. if (key == 16 /* Shift */) { if (!elem.className != vt100.isShift) { vt100.showShiftState(!vt100.isShift); } } else if (key == 17 /* Ctrl */) { if (!elem.className != vt100.isCtrl) { vt100.showCtrlState(!vt100.isCtrl); } } else if (key == 18 /* Alt */) { if (!elem.className != vt100.isAlt) { vt100.showAltState(!vt100.isAlt); } } else { elem.className = 'selected'; } vt100.lastSelectedKey = elem; } return false; }; }(this, elem, key)); var clicked = // Modifier keys update the state of the keyboard, but do not generate // any key clicks that get forwarded to the application. key >= 16 /* Shift */ && key <= 18 /* Alt */ ? function(vt100, elem) { return function(e) { if (elem == vt100.lastSelectedKey) { if (key == 16 /* Shift */) { // The user clicked the Shift key vt100.isShift = !vt100.isShift; vt100.showShiftState(vt100.isShift); } else if (key == 17 /* Ctrl */) { vt100.isCtrl = !vt100.isCtrl; vt100.showCtrlState(vt100.isCtrl); } else if (key == 18 /* Alt */) { vt100.isAlt = !vt100.isAlt; vt100.showAltState(vt100.isAlt); } vt100.lastSelectedKey = undefined; } if (vt100.lastSelectedKey) { vt100.lastSelectedKey.className = ''; vt100.lastSelectedKey = undefined; } return false; }; }(this, elem) : // Regular keys generate key clicks, when the mouse button is released or // when a mouse click event is received. function(vt100, elem, ch, key, CH, KEY) { return function(e) { if (vt100.lastSelectedKey) { if (elem == vt100.lastSelectedKey) { // The user clicked a key. if (vt100.isShift) { vt100.clickedKeyboard(e, elem, CH, KEY, true, vt100.isCtrl, vt100.isAlt); } else { vt100.clickedKeyboard(e, elem, ch, key, false, vt100.isCtrl, vt100.isAlt); } vt100.isShift = false; vt100.showShiftState(false); vt100.isCtrl = false; vt100.showCtrlState(false); vt100.isAlt = false; vt100.showAltState(false); } vt100.lastSelectedKey.className = ''; vt100.lastSelectedKey = undefined; } elem.className = ''; return false; }; }(this, elem, ch, key, CH, KEY); this.addListener(elem, 'mouseup', clicked); this.addListener(elem, 'click', clicked); // When moving the mouse away from a key, check if any keys need to be // deselected. this.addListener(elem, 'mouseout', function(vt100, elem, key) { return function(e) { if (key == 16 /* Shift */) { if (!elem.className == vt100.isShift) { vt100.showShiftState(vt100.isShift); } } else if (key == 17 /* Ctrl */) { if (!elem.className == vt100.isCtrl) { vt100.showCtrlState(vt100.isCtrl); } } else if (key == 18 /* Alt */) { if (!elem.className == vt100.isAlt) { vt100.showAltState(vt100.isAlt); } } else if (elem.className) { elem.className = ''; vt100.lastSelectedKey = elem; } else if (vt100.lastSelectedKey) { vt100.resetLastSelectedKey(e); } return false; }; }(this, elem, key)); // When moving the mouse over a key, select it if the user is still holding // the mouse button down (i.e. elem == lastSelectedKey) this.addListener(elem, 'mouseover', function(vt100, elem, key) { return function(e) { if (elem == vt100.lastSelectedKey) { if (key == 16 /* Shift */) { if (!elem.className != vt100.isShift) { vt100.showShiftState(!vt100.isShift); } } else if (key == 17 /* Ctrl */) { if (!elem.className != vt100.isCtrl) { vt100.showCtrlState(!vt100.isCtrl); } } else if (key == 18 /* Alt */) { if (!elem.className != vt100.isAlt) { vt100.showAltState(!vt100.isAlt); } } else if (!elem.className) { elem.className = 'selected'; } } else { vt100.resetLastSelectedKey(e); } return false; }; }(this, elem, key)); }; VT100.prototype.initializeKeyBindings = function(elem) { if (elem) { if (elem.nodeName == "I" || elem.nodeName == "B") { if (elem.id) { // Function keys. The Javascript keycode is part of the "id" var i = parseInt(elem.id); if (i) { // If the id does not parse as a number, it is not a keycode. this.addKeyBinding(elem, undefined, i); } } else { var child = elem.firstChild; if (child) { if (child.nodeName == "#text") { // If the key only has a text node as a child, then it is a letter. // Automatically compute the lower and upper case version of the // key. var text = this.getTextContent(child) || this.getTextContent(elem); this.addKeyBinding(elem, text.toLowerCase()); } else if (child.nextSibling) { // If the key has two children, they are the lower and upper case // character code, respectively. this.addKeyBinding(elem, this.getTextContent(child), undefined, this.getTextContent(child.nextSibling)); } } } } } // Recursively parse all other child nodes. for (elem = elem.firstChild; elem; elem = elem.nextSibling) { this.initializeKeyBindings(elem); } }; VT100.prototype.initializeKeyboardButton = function() { // Configure mouse event handlers for button that displays/hides keyboard this.addListener(this.keyboardImage, 'click', function(vt100) { return function(e) { if (vt100.keyboard.style.display != '') { if (vt100.reconnectBtn.style.visibility != '') { vt100.initializeKeyboard(); vt100.showSoftKeyboard(); } } else { vt100.hideSoftKeyboard(); vt100.input.focus(); } return false; }; }(this)); // Enable button that displays keyboard if (this.softKeyboard) { this.keyboardImage.style.visibility = 'visible'; } }; VT100.prototype.initializeKeyboard = function() { // Only need to initialize the keyboard the very first time. When doing so, // copy the keyboard layout from the iframe. if (this.keyboard.firstChild) { return; } this.keyboard.innerHTML = this.layout.contentDocument.body.innerHTML; var box = this.keyboard.firstChild; this.hideSoftKeyboard(); // Configure mouse event handlers for on-screen keyboard this.addListener(this.keyboard, 'click', function(vt100) { return function(e) { vt100.hideSoftKeyboard(); vt100.input.focus(); return false; }; }(this)); this.addListener(this.keyboard, 'selectstart', this.cancelEvent); this.addListener(box, 'click', this.cancelEvent); this.addListener(box, 'mouseup', function(vt100) { return function(e) { if (vt100.lastSelectedKey) { vt100.lastSelectedKey.className = ''; vt100.lastSelectedKey = undefined; } return false; }; }(this)); this.addListener(box, 'mouseout', function(vt100) { return function(e) { return vt100.resetLastSelectedKey(e); }; }(this)); this.addListener(box, 'mouseover', function(vt100) { return function(e) { return vt100.resetLastSelectedKey(e); }; }(this)); // Configure SHIFT key behavior var style = document.createElement('style'); var id = document.createAttribute('id'); id.nodeValue = 'shift_state'; style.setAttributeNode(id); var type = document.createAttribute('type'); type.nodeValue = 'text/css'; style.setAttributeNode(type); document.getElementsByTagName('head')[0].appendChild(style); // Set up key bindings this.initializeKeyBindings(box); }; VT100.prototype.initializeElements = function(container) { // If the necessary objects have not already been defined in the HTML // page, create them now. if (container) { this.container = container; } else if (!(this.container = document.getElementById('vt100'))) { this.container = document.createElement('div'); this.container.id = 'vt100'; document.body.appendChild(this.container); } if (!this.getChildById(this.container, 'reconnect') || !this.getChildById(this.container, 'menu') || !this.getChildById(this.container, 'keyboard') || !this.getChildById(this.container, 'kbd_button') || !this.getChildById(this.container, 'kbd_img') || !this.getChildById(this.container, 'layout') || !this.getChildById(this.container, 'scrollable') || !this.getChildById(this.container, 'console') || !this.getChildById(this.container, 'alt_console') || !this.getChildById(this.container, 'ieprobe') || !this.getChildById(this.container, 'padding') || !this.getChildById(this.container, 'cursor') || !this.getChildById(this.container, 'lineheight') || !this.getChildById(this.container, 'usercss') || !this.getChildById(this.container, 'space') || !this.getChildById(this.container, 'input') || !this.getChildById(this.container, 'cliphelper')) { // Only enable the "embed" object, if we have a suitable plugin. Otherwise, // we might get a pointless warning that a suitable plugin is not yet // installed. If in doubt, we'd rather just stay silent. var embed = ''; try { if (typeof navigator.mimeTypes["audio/x-wav"].enabledPlugin.name != 'undefined') { embed = typeof suppressAllAudio != 'undefined' && suppressAllAudio ? "" : '<embed classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" ' + 'id="beep_embed" ' + 'src="beep.wav" ' + 'autostart="false" ' + 'volume="100" ' + 'enablejavascript="true" ' + 'type="audio/x-wav" ' + 'height="16" ' + 'width="200" ' + 'style="position:absolute;left:-1000px;top:-1000px" />'; } } catch (e) { } this.container.innerHTML = '<div id="reconnect" style="visibility: hidden">' + '<input type="button" value="Connect" ' + 'onsubmit="return false" />' + '</div>' + '<div id="cursize" style="visibility: hidden">' + '</div>' + '<div id="menu"></div>' + '<div id="keyboard" unselectable="on">' + '</div>' + '<div id="scrollable">' + '<table id="kbd_button">' + '<tr><td width="100%">&nbsp;</td>' + '<td><img id="kbd_img" src="keyboard.png" /></td>' + '<td>&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>' + '</table>' + '<pre id="lineheight">&nbsp;</pre>' + '<pre id="console">' + '<pre></pre>' + '<div id="ieprobe"><span>&nbsp;</span></div>' + '</pre>' + '<pre id="alt_console" style="display: none"></pre>' + '<div id="padding"></div>' + '<pre id="cursor">&nbsp;</pre>' + '</div>' + '<div class="hidden">' + '<div id="usercss"></div>' + '<pre><div><span id="space"></span></div></pre>' + '<input type="textfield" id="input" autocorrect="off" autocapitalize="off" />' + '<input type="textfield" id="cliphelper" />' + (typeof suppressAllAudio != 'undefined' && suppressAllAudio ? "" : embed + '<bgsound id="beep_bgsound" loop=1 />') + '<iframe id="layout" src="keyboard.html" />' + '</div>'; } // Find the object used for playing the "beep" sound, if any. if (typeof suppressAllAudio != 'undefined' && suppressAllAudio) { this.beeper = undefined; } else { this.beeper = this.getChildById(this.container, 'beep_embed'); if (!this.beeper || !this.beeper.Play) { this.beeper = this.getChildById(this.container, 'beep_bgsound'); if (!this.beeper || typeof this.beeper.src == 'undefined') { this.beeper = undefined; } } } // Initialize the variables for finding the text console and the // cursor. this.reconnectBtn = this.getChildById(this.container,'reconnect'); this.curSizeBox = this.getChildById(this.container, 'cursize'); this.menu = this.getChildById(this.container, 'menu'); this.keyboard = this.getChildById(this.container, 'keyboard'); this.keyboardImage = this.getChildById(this.container, 'kbd_img'); this.layout = this.getChildById(this.container, 'layout'); this.scrollable = this.getChildById(this.container, 'scrollable'); this.lineheight = this.getChildById(this.container, 'lineheight'); this.console = [ this.getChildById(this.container, 'console'), this.getChildById(this.container, 'alt_console') ]; var ieProbe = this.getChildById(this.container, 'ieprobe'); this.padding = this.getChildById(this.container, 'padding'); this.cursor = this.getChildById(this.container, 'cursor'); this.usercss = this.getChildById(this.container, 'usercss'); this.space = this.getChildById(this.container, 'space'); this.input = this.getChildById(this.container, 'input'); this.cliphelper = this.getChildById(this.container, 'cliphelper'); // Add any user selectable style sheets to the menu this.initializeUserCSSStyles(); // Remember the dimensions of a standard character glyph. We would // expect that we could just check cursor.clientWidth/Height at any time, // but it turns out that browsers sometimes invalidate these values // (e.g. while displaying a print preview screen). this.cursorWidth = this.cursor.clientWidth; this.cursorHeight = this.lineheight.clientHeight; // IE has a slightly different boxing model, that we need to compensate for this.isIE = ieProbe.offsetTop > 1; ieProbe = undefined; this.console.innerHTML = ''; // Determine if the terminal window is positioned at the beginning of the // page, or if it is embedded somewhere else in the page. For full-screen // terminals, automatically resize whenever the browser window changes. var marginTop = parseInt(this.getCurrentComputedStyle( document.body, 'marginTop')); var marginLeft = parseInt(this.getCurrentComputedStyle( document.body, 'marginLeft')); var marginRight = parseInt(this.getCurrentComputedStyle( document.body, 'marginRight')); var x = this.container.offsetLeft; var y = this.container.offsetTop; for (var parent = this.container; parent = parent.offsetParent; ) { x += parent.offsetLeft; y += parent.offsetTop; } this.isEmbedded = marginTop != y || marginLeft != x || (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) - marginRight != x + this.container.offsetWidth; if (!this.isEmbedded) { // Some browsers generate resize events when the terminal is first // shown. Disable showing the size indicator until a little bit after // the terminal has been rendered the first time. this.indicateSize = false; setTimeout(function(vt100) { return function() { vt100.indicateSize = true; }; }(this), 100); this.addListener(window, 'resize', function(vt100) { return function() { vt100.hideContextMenu(); vt100.resizer(); vt100.showCurrentSize(); } }(this)); // Hide extra scrollbars attached to window document.body.style.margin = '0px'; try { document.body.style.overflow ='hidden'; } catch (e) { } try { document.body.oncontextmenu = function() {return false;};} catch(e){} } // Set up onscreen soft keyboard this.initializeKeyboardButton(); // Hide context menu this.hideContextMenu(); // Add listener to reconnect button this.addListener(this.reconnectBtn.firstChild, 'click', function(vt100) { return function() { var rc = vt100.reconnect(); vt100.input.focus(); return rc; } }(this)); // Add input listeners this.addListener(this.input, 'blur', function(vt100) { return function() { vt100.blurCursor(); } }(this)); this.addListener(this.input, 'focus', function(vt100) { return function() { vt100.focusCursor(); } }(this)); this.addListener(this.input, 'keydown', function(vt100) { return function(e) { if (!e) e = window.event; return vt100.keyDown(e); } }(this)); this.addListener(this.input, 'keypress', function(vt100) { return function(e) { if (!e) e = window.event; return vt100.keyPressed(e); } }(this)); this.addListener(this.input, 'keyup', function(vt100) { return function(e) { if (!e) e = window.event; return vt100.keyUp(e); } }(this)); // Attach listeners that move the focus to the <input> field. This way we // can make sure that we can receive keyboard input. var mouseEvent = function(vt100, type) { return function(e) { if (!e) e = window.event; return vt100.mouseEvent(e, type); }; }; this.addListener(this.scrollable,'mousedown',mouseEvent(this, 0 /* MOUSE_DOWN */)); this.addListener(this.scrollable,'mouseup', mouseEvent(this, 1 /* MOUSE_UP */)); this.addListener(this.scrollable,'click', mouseEvent(this, 2 /* MOUSE_CLICK */)); // Check that browser supports drag and drop if ('draggable' in document.createElement('span')) { var dropEvent = function (vt100) { return function(e) { if (!e) e = window.event; if (e.preventDefault) e.preventDefault(); vt100.keysPressed(e.dataTransfer.getData('Text')); return false; }; }; // Tell the browser that we *can* drop on this target this.addListener(this.scrollable, 'dragover', cancel); this.addListener(this.scrollable, 'dragenter', cancel); // Add a listener for the drop event this.addListener(this.scrollable, 'drop', dropEvent(this)); } // Initialize the blank terminal window. this.currentScreen = 0; this.cursorX = 0; this.cursorY = 0; this.numScrollbackLines = 0; this.top = 0; this.bottom = 0x7FFFFFFF; this.scale = 1.0; this.resizer(); this.focusCursor(); this.input.focus(); }; function cancel(event) { if (event.preventDefault) { event.preventDefault(); } return false; } VT100.prototype.getChildById = function(parent, id) { var nodeList = parent.all || parent.getElementsByTagName('*'); if (typeof nodeList.namedItem == 'undefined') { for (var i = 0; i < nodeList.length; i++) { if (nodeList[i].id == id) { return nodeList[i]; } } return null; } else { var elem = (parent.all || parent.getElementsByTagName('*')).namedItem(id); return elem ? elem[0] || elem : null; } }; VT100.prototype.getCurrentComputedStyle = function(elem, style) { if (typeof elem.currentStyle != 'undefined') { return elem.currentStyle[style]; } else { return document.defaultView.getComputedStyle(elem, null)[style]; } }; VT100.prototype.reconnect = function() { return false; }; VT100.prototype.showReconnect = function(state) { if (state) { this.hideSoftKeyboard(); this.reconnectBtn.style.visibility = ''; } else { this.reconnectBtn.style.visibility = 'hidden'; } }; VT100.prototype.repairElements = function(console) { for (var line = console.firstChild; line; line = line.nextSibling) { if (!line.clientHeight) { var newLine = document.createElement(line.tagName); newLine.style.cssText = line.style.cssText; newLine.className = line.className; if (line.tagName == 'DIV') { for (var span = line.firstChild; span; span = span.nextSibling) { var newSpan = document.createElement(span.tagName); newSpan.style.cssText = span.style.cssText; newSpan.className = span.className; this.setTextContent(newSpan, this.getTextContent(span)); newLine.appendChild(newSpan); } } else { this.setTextContent(newLine, this.getTextContent(line)); } line.parentNode.replaceChild(newLine, line); line = newLine; } } }; VT100.prototype.resized = function(w, h) { }; VT100.prototype.resizer = function() { // Hide onscreen soft keyboard this.hideSoftKeyboard(); // The cursor can get corrupted if the print-preview is displayed in Firefox. // Recreating it, will repair it. var newCursor = document.createElement('pre'); this.setTextContent(newCursor, ' '); newCursor.id = 'cursor'; newCursor.style.cssText = this.cursor.style.cssText; this.cursor.parentNode.insertBefore(newCursor, this.cursor); if (!newCursor.clientHeight) { // Things are broken right now. This is probably because we are // displaying the print-preview. Just don't change any of our settings // until the print dialog is closed again. newCursor.parentNode.removeChild(newCursor); return; } else { // Swap the old broken cursor for the newly created one. this.cursor.parentNode.removeChild(this.cursor); this.cursor = newCursor; } // Really horrible things happen if the contents of the terminal changes // while the print-preview is showing. We get HTML elements that show up // in the DOM, but that do not take up any space. Find these elements and // try to fix them. this.repairElements(this.console[0]); this.repairElements(this.console[1]); // Lock the cursor size to the size of a normal character. This helps with // characters that are taller/shorter than normal. Unfortunately, we will // still get confused if somebody enters a character that is wider/narrower // than normal. This can happen if the browser tries to substitute a // characters from a different font. this.cursor.style.width = this.cursorWidth + 'px'; this.cursor.style.height = this.cursorHeight + 'px'; // Adjust height for one pixel padding of the #vt100 element. // The latter is necessary to properly display the inactive cursor. var console = this.console[this.currentScreen]; var height = (this.isEmbedded ? this.container.clientHeight : (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight))-1; var partial = height % this.cursorHeight; this.scrollable.style.height = (height > 0 ? height : 0) + 'px'; this.padding.style.height = (partial > 0 ? partial : 0) + 'px'; var oldTerminalHeight = this.terminalHeight; this.updateWidth(); this.updateHeight(); // Clip the cursor to the visible screen. var cx = this.cursorX; var cy = this.cursorY + this.numScrollbackLines; // The alternate screen never keeps a scroll back buffer. this.updateNumScrollbackLines(); while (this.currentScreen && this.numScrollbackLines > 0) { console.removeChild(console.firstChild); this.numScrollbackLines--; } cy -= this.numScrollbackLines; if (cx < 0) { cx = 0; } else if (cx > this.terminalWidth) { cx = this.terminalWidth - 1; if (cx < 0) { cx = 0; } } if (cy < 0) { cy = 0; } else if (cy > this.terminalHeight) { cy = this.terminalHeight - 1; if (cy < 0) { cy = 0; } } // Clip the scroll region to the visible screen. if (this.bottom > this.terminalHeight || this.bottom == oldTerminalHeight) { this.bottom = this.terminalHeight; } if (this.top >= this.bottom) { this.top = this.bottom-1; if (this.top < 0) { this.top = 0; } } // Truncate lines, if necessary. Explicitly reposition cursor (this is // particularly important after changing the screen number), and reset // the scroll region to the default. this.truncateLines(this.terminalWidth); this.putString(cx, cy, '', undefined); this.scrollable.scrollTop = this.numScrollbackLines * this.cursorHeight + 1; // Update classNames for lines in the scrollback buffer var line = console.firstChild; for (var i = 0; i < this.numScrollbackLines; i++) { line.className = 'scrollback'; line = line.nextSibling; } while (line) { line.className = ''; line = line.nextSibling; } // Reposition the reconnect button this.reconnectBtn.style.left = (this.terminalWidth*this.cursorWidth/ this.scale - this.reconnectBtn.clientWidth)/2 + 'px'; this.reconnectBtn.style.top = (this.terminalHeight*this.cursorHeight- this.reconnectBtn.clientHeight)/2 + 'px'; // Send notification that the window size has been changed this.resized(this.terminalWidth, this.terminalHeight); }; VT100.prototype.showCurrentSize = function() { if (!this.indicateSize) { return; } this.curSizeBox.innerHTML = '' + this.terminalWidth + 'x' + this.terminalHeight; this.curSizeBox.style.left = (this.terminalWidth*this.cursorWidth/ this.scale - this.curSizeBox.clientWidth)/2 + 'px'; this.curSizeBox.style.top = (this.terminalHeight*this.cursorHeight - this.curSizeBox.clientHeight)/2 + 'px'; this.curSizeBox.style.visibility = ''; if (this.curSizeTimeout) { clearTimeout(this.curSizeTimeout); } // Only show the terminal size for a short amount of time after resizing. // Then hide this information, again. Some browsers generate resize events // throughout the entire resize operation. This is nice, and we will show // the terminal size while the user is dragging the window borders. // Other browsers only generate a single event when the user releases the // mouse. In those cases, we can only show the terminal size once at the // end of the resize operation. this.curSizeTimeout = setTimeout(function(vt100) { return function() { vt100.curSizeTimeout = null; vt100.curSizeBox.style.visibility = 'hidden'; }; }(this), 1000); }; VT100.prototype.selection = function() { try { return '' + (window.getSelection && window.getSelection() || document.selection && document.selection.type == 'Text' && document.selection.createRange().text || ''); } catch (e) { } return ''; }; VT100.prototype.cancelEvent = function(event) { try { // For non-IE browsers event.stopPropagation(); event.preventDefault(); } catch (e) { } try { // For IE event.cancelBubble = true; event.returnValue = false; event.button = 0; event.keyCode = 0; } catch (e) { } return false; }; VT100.prototype.mousePosition = function(event) { var offsetX = this.container.offsetLeft; var offsetY = this.container.offsetTop; for (var e = this.container; e = e.offsetParent; ) { offsetX += e.offsetLeft; offsetY += e.offsetTop; } return [ event.clientX - offsetX, event.clientY - offsetY ]; }; VT100.prototype.mouseEvent = function(event, type) { // If any text is currently selected, do not move the focus as that would // invalidate the selection. var selection = this.selection(); if ((type == 1 /* MOUSE_UP */ || type == 2 /* MOUSE_CLICK */) && !selection.length) { this.input.focus(); } // Compute mouse position in characters. var position = this.mousePosition(event); var x = Math.floor(position[0] / this.cursorWidth); var y = Math.floor((position[1] + this.scrollable.scrollTop) / this.cursorHeight) - this.numScrollbackLines; var inside = true; if (x >= this.terminalWidth) { x = this.terminalWidth - 1; inside = false; } if (x < 0) { x = 0; inside = false; } if (y >= this.terminalHeight) { y = this.terminalHeight - 1; inside = false; } if (y < 0) { y = 0; inside = false; } // Compute button number and modifier keys. var button = type != 0 /* MOUSE_DOWN */ ? 3 : typeof event.pageX != 'undefined' ? event.button : [ undefined, 0, 2, 0, 1, 0, 1, 0 ][event.button]; if (button != undefined) { if (event.shiftKey) { button |= 0x04; } if (event.altKey || event.metaKey) { button |= 0x08; } if (event.ctrlKey) { button |= 0x10; } } // Report mouse events if they happen inside of the current screen and // with the SHIFT key unpressed. Both of these restrictions do not apply // for button releases, as we always want to report those. if (this.mouseReporting && !selection.length && (type != 0 /* MOUSE_DOWN */ || !event.shiftKey)) { if (inside || type != 0 /* MOUSE_DOWN */) { if (button != undefined) { var report = '\u001B[M' + String.fromCharCode(button + 32) + String.fromCharCode(x + 33) + String.fromCharCode(y + 33); if (type != 2 /* MOUSE_CLICK */) { this.keysPressed(report); } // If we reported the event, stop propagating it (not sure, if this // actually works on most browsers; blocking the global "oncontextmenu" // even is still necessary). return this.cancelEvent(event); } } } // Bring up context menu. if (button == 2 && !event.shiftKey) { if (type == 0 /* MOUSE_DOWN */) { this.showContextMenu(position[0], position[1]); } return this.cancelEvent(event); } if (this.mouseReporting) { try { event.shiftKey = false; } catch (e) { } } return true; }; VT100.prototype.replaceChar = function(s, ch, repl) { for (var i = -1;;) { i = s.indexOf(ch, i + 1); if (i < 0) { break; } s = s.substr(0, i) + repl + s.substr(i + 1); } return s; }; VT100.prototype.htmlEscape = function(s) { return this.replaceChar(this.replaceChar(this.replaceChar(this.replaceChar( s, '&', '&amp;'), '<', '&lt;'), '"', '&quot;'), ' ', '\u00A0'); }; VT100.prototype.getTextContent = function(elem) { return elem.textContent || (typeof elem.textContent == 'undefined' ? elem.innerText : ''); }; VT100.prototype.setTextContentRaw = function(elem, s) { // Updating the content of an element is an expensive operation. It actually // pays off to first check whether the element is still unchanged. if (typeof elem.textContent == 'undefined') { if (elem.innerText != s) { try { elem.innerText = s; } catch (e) { // Very old versions of IE do not allow setting innerText. Instead, // remove all children, by setting innerHTML and then set the text // using DOM methods. elem.innerHTML = ''; elem.appendChild(document.createTextNode( this.replaceChar(s, ' ', '\u00A0'))); } } } else { if (elem.textContent != s) { elem.textContent = s; } } }; VT100.prototype.setTextContent = function(elem, s) { // Check if we find any URLs in the text. If so, automatically convert them // to links. if (this.urlRE && this.urlRE.test(s)) { var inner = ''; for (;;) { var consumed = 0; if (RegExp.leftContext != null) { inner += this.htmlEscape(RegExp.leftContext); consumed += RegExp.leftContext.length; } var url = this.htmlEscape(RegExp.lastMatch); var fullUrl = url; // If no protocol was specified, try to guess a reasonable one. if (url.indexOf('http://') < 0 && url.indexOf('https://') < 0 && url.indexOf('ftp://') < 0 && url.indexOf('mailto:') < 0) { var slash = url.indexOf('/'); var at = url.indexOf('@'); var question = url.indexOf('?'); if (at > 0 && (at < question || question < 0) && (slash < 0 || (question > 0 && slash > question))) { fullUrl = 'mailto:' + url; } else { fullUrl = (url.indexOf('ftp.') == 0 ? 'ftp://' : 'http://') + url; } } inner += '<a target="vt100Link" href="' + fullUrl + '">' + url + '</a>'; consumed += RegExp.lastMatch.length; s = s.substr(consumed); if (!this.urlRE.test(s)) { if (RegExp.rightContext != null) { inner += this.htmlEscape(RegExp.rightContext); } break; } } elem.innerHTML = inner; return; } this.setTextContentRaw(elem, s); }; VT100.prototype.insertBlankLine = function(y, color, style) { // Insert a blank line a position y. This method ignores the scrollback // buffer. The caller has to add the length of the scrollback buffer to // the position, if necessary. // If the position is larger than the number of current lines, this // method just adds a new line right after the last existing one. It does // not add any missing lines in between. It is the caller's responsibility // to do so. if (!color) { color = 'ansi0 bgAnsi15'; } if (!style) { style = ''; } var line; if (color != 'ansi0 bgAnsi15' && !style) { line = document.createElement('pre'); this.setTextContent(line, '\n'); } else { line = document.createElement('div'); var span = document.createElement('span'); span.style.cssText = style; span.className = color; this.setTextContent(span, this.spaces(this.terminalWidth)); line.appendChild(span); } line.style.height = this.cursorHeight + 'px'; var console = this.console[this.currentScreen]; if (console.childNodes.length > y) { console.insertBefore(line, console.childNodes[y]); } else { console.appendChild(line); } }; VT100.prototype.updateWidth = function() { this.terminalWidth = Math.floor(this.console[this.currentScreen].offsetWidth/ this.cursorWidth*this.scale); return this.terminalWidth; }; VT100.prototype.updateHeight = function() { // We want to be able to display either a terminal window that fills the // entire browser window, or a terminal window that is contained in a // <div> which is embededded somewhere in the web page. if (this.isEmbedded) { // Embedded terminal. Use size of the containing <div> (id="vt100"). this.terminalHeight = Math.floor((this.container.clientHeight-1) / this.cursorHeight); } else { // Use the full browser window. this.terminalHeight = Math.floor(((window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight)-1)/ this.cursorHeight); } return this.terminalHeight; }; VT100.prototype.updateNumScrollbackLines = function() { var scrollback = Math.floor( this.console[this.currentScreen].offsetHeight / this.cursorHeight) - this.terminalHeight; this.numScrollbackLines = scrollback < 0 ? 0 : scrollback; return this.numScrollbackLines; }; VT100.prototype.truncateLines = function(width) { if (width < 0) { width = 0; } for (var line = this.console[this.currentScreen].firstChild; line; line = line.nextSibling) { if (line.tagName == 'DIV') { var x = 0; // Traverse current line and truncate it once we saw "width" characters for (var span = line.firstChild; span; span = span.nextSibling) { var s = this.getTextContent(span); var l = s.length; if (x + l > width) { this.setTextContent(span, s.substr(0, width - x)); while (span.nextSibling) { line.removeChild(line.lastChild); } break; } x += l; } // Prune white space from the end of the current line var span = line.lastChild; while (span && span.className == 'ansi0 bgAnsi15' && !span.style.cssText.length) { // Scan backwards looking for first non-space character var s = this.getTextContent(span); for (var i = s.length; i--; ) { if (s.charAt(i) != ' ' && s.charAt(i) != '\u00A0') { if (i+1 != s.length) { this.setTextContent(s.substr(0, i+1)); } span = null; break; } } if (span) { var sibling = span; span = span.previousSibling; if (span) { // Remove blank <span>'s from end of line line.removeChild(sibling); } else { // Remove entire line (i.e. <div>), if empty var blank = document.createElement('pre'); blank.style.height = this.cursorHeight + 'px'; this.setTextContent(blank, '\n'); line.parentNode.replaceChild(blank, line); } } } } } }; VT100.prototype.putString = function(x, y, text, color, style) { if (!color) { color = 'ansi0 bgAnsi15'; } if (!style) { style = ''; } var yIdx = y + this.numScrollbackLines; var line; var sibling; var s; var span; var xPos = 0; var console = this.console[this.currentScreen]; if (!text.length && (yIdx >= console.childNodes.length || console.childNodes[yIdx].tagName != 'DIV')) { // Positioning cursor to a blank location span = null; } else { // Create missing blank lines at end of page while (console.childNodes.length <= yIdx) { // In order to simplify lookups, we want to make sure that each line // is represented by exactly one element (and possibly a whole bunch of // children). // For non-blank lines, we can create a <div> containing one or more // <span>s. For blank lines, this fails as browsers tend to optimize them // away. But fortunately, a <pre> tag containing a newline character // appears to work for all browsers (a &nbsp; would also work, but then // copying from the browser window would insert superfluous spaces into // the clipboard). this.insertBlankLine(yIdx); } line = console.childNodes[yIdx]; // If necessary, promote blank '\n' line to a <div> tag if (line.tagName != 'DIV') { var div = document.createElement('div'); div.style.height = this.cursorHeight + 'px'; div.innerHTML = '<span></span>'; console.replaceChild(div, line); line = div; } // Scan through list of <span>'s until we find the one where our text // starts span = line.firstChild; var len; while (span.nextSibling && xPos < x) { len = this.getTextContent(span).length; if (xPos + len > x) { break; } xPos += len; span = span.nextSibling; } if (text.length) { // If current <span> is not long enough, pad with spaces or add new // span s = this.getTextContent(span); var oldColor = span.className; var oldStyle = span.style.cssText; if (xPos + s.length < x) { if (oldColor != 'ansi0 bgAnsi15' || oldStyle != '') { span = document.createElement('span'); line.appendChild(span); span.className = 'ansi0 bgAnsi15'; span.style.cssText = ''; oldColor = 'ansi0 bgAnsi15'; oldStyle = ''; xPos += s.length; s = ''; } do { s += ' '; } while (xPos + s.length < x); } // If styles do not match, create a new <span> var del = text.length - s.length + x - xPos; if (oldColor != color || (oldStyle != style && (oldStyle || style))) { if (xPos == x) { // Replacing text at beginning of existing <span> if (text.length >= s.length) { // New text is equal or longer than existing text s = text; } else { // Insert new <span> before the current one, then remove leading // part of existing <span>, adjust style of new <span>, and finally // set its contents sibling = document.createElement('span'); line.insertBefore(sibling, span); this.setTextContent(span, s.substr(text.length)); span = sibling; s = text; } } else { // Replacing text some way into the existing <span> var remainder = s.substr(x + text.length - xPos); this.setTextContent(span, s.substr(0, x - xPos)); xPos = x; sibling = document.createElement('span'); if (span.nextSibling) { line.insertBefore(sibling, span.nextSibling); span = sibling; if (remainder.length) { sibling = document.createElement('span'); sibling.className = oldColor; sibling.style.cssText = oldStyle; this.setTextContent(sibling, remainder); line.insertBefore(sibling, span.nextSibling); } } else { line.appendChild(sibling); span = sibling; if (remainder.length) { sibling = document.createElement('span'); sibling.className = oldColor; sibling.style.cssText = oldStyle; this.setTextContent(sibling, remainder); line.appendChild(sibling); } } s = text; } span.className = color; span.style.cssText = style; } else { // Overwrite (partial) <span> with new text s = s.substr(0, x - xPos) + text + s.substr(x + text.length - xPos); } this.setTextContent(span, s); // Delete all subsequent <span>'s that have just been overwritten sibling = span.nextSibling; while (del > 0 && sibling) { s = this.getTextContent(sibling); len = s.length; if (len <= del) { line.removeChild(sibling); del -= len; sibling = span.nextSibling; } else { this.setTextContent(sibling, s.substr(del)); break; } } // Merge <span> with next sibling, if styles are identical if (sibling && span.className == sibling.className && span.style.cssText == sibling.style.cssText) { this.setTextContent(span, this.getTextContent(span) + this.getTextContent(sibling)); line.removeChild(sibling); } } } // Position cursor this.cursorX = x + text.length; if (this.cursorX >= this.terminalWidth) { this.cursorX = this.terminalWidth - 1; if (this.cursorX < 0) { this.cursorX = 0; } } var pixelX = -1; var pixelY = -1; if (!this.cursor.style.visibility) { var idx = this.cursorX - xPos; if (span) { // If we are in a non-empty line, take the cursor Y position from the // other elements in this line. If dealing with broken, non-proportional // fonts, this is likely to yield better results. pixelY = span.offsetTop + span.offsetParent.offsetTop; s = this.getTextContent(span); var nxtIdx = idx - s.length; if (nxtIdx < 0) { this.setTextContent(this.cursor, s.charAt(idx)); pixelX = span.offsetLeft + idx*span.offsetWidth / s.length; } else { if (nxtIdx == 0) { pixelX = span.offsetLeft + span.offsetWidth; } if (span.nextSibling) { s = this.getTextContent(span.nextSibling); this.setTextContent(this.cursor, s.charAt(nxtIdx)); if (pixelX < 0) { pixelX = span.nextSibling.offsetLeft + nxtIdx*span.offsetWidth / s.length; } } else { this.setTextContent(this.cursor, ' '); } } } else { this.setTextContent(this.cursor, ' '); } } if (pixelX >= 0) { this.cursor.style.left = (pixelX + (this.isIE ? 1 : 0))/ this.scale + 'px'; } else { this.setTextContent(this.space, this.spaces(this.cursorX)); this.cursor.style.left = (this.space.offsetWidth + console.offsetLeft)/this.scale + 'px'; } this.cursorY = yIdx - this.numScrollbackLines; if (pixelY >= 0) { this.cursor.style.top = pixelY + 'px'; } else { this.cursor.style.top = yIdx*this.cursorHeight + console.offsetTop + 'px'; } if (text.length) { // Merge <span> with previous sibling, if styles are identical if ((sibling = span.previousSibling) && span.className == sibling.className && span.style.cssText == sibling.style.cssText) { this.setTextContent(span, this.getTextContent(sibling) + this.getTextContent(span)); line.removeChild(sibling); } // Prune white space from the end of the current line span = line.lastChild; while (span && span.className == 'ansi0 bgAnsi15' && !span.style.cssText.length) { // Scan backwards looking for first non-space character s = this.getTextContent(span); for (var i = s.length; i--; ) { if (s.charAt(i) != ' ' && s.charAt(i) != '\u00A0') { if (i+1 != s.length) { this.setTextContent(s.substr(0, i+1)); } span = null; break; } } if (span) { sibling = span; span = span.previousSibling; if (span) { // Remove blank <span>'s from end of line line.removeChild(sibling); } else { // Remove entire line (i.e. <div>), if empty var blank = document.createElement('pre'); blank.style.height = this.cursorHeight + 'px'; this.setTextContent(blank, '\n'); line.parentNode.replaceChild(blank, line); } } } } }; VT100.prototype.gotoXY = function(x, y) { if (x >= this.terminalWidth) { x = this.terminalWidth - 1; } if (x < 0) { x = 0; } var minY, maxY; if (this.offsetMode) { minY = this.top; maxY = this.bottom; } else { minY = 0; maxY = this.terminalHeight; } if (y >= maxY) { y = maxY - 1; } if (y < minY) { y = minY; } this.putString(x, y, '', undefined); this.needWrap = false; }; VT100.prototype.gotoXaY = function(x, y) { this.gotoXY(x, this.offsetMode ? (this.top + y) : y); }; VT100.prototype.refreshInvertedState = function() { if (this.isInverted) { this.scrollable.className += ' inverted'; } else { this.scrollable.className = this.scrollable.className. replace(/ *inverted/, ''); } }; VT100.prototype.enableAlternateScreen = function(state) { // Don't do anything, if we are already on the desired screen if ((state ? 1 : 0) == this.currentScreen) { // Calling the resizer is not actually necessary. But it is a good way // of resetting state that might have gotten corrupted. this.resizer(); return; } // We save the full state of the normal screen, when we switch away from it. // But for the alternate screen, no saving is necessary. We always reset // it when we switch to it. if (state) { this.saveCursor(); } // Display new screen, and initialize state (the resizer does that for us). this.currentScreen = state ? 1 : 0; this.console[1-this.currentScreen].style.display = 'none'; this.console[this.currentScreen].style.display = ''; // Select appropriate character pitch. var transform = this.getTransformName(); if (transform) { if (state) { // Upon enabling the alternate screen, we switch to 80 column mode. But // upon returning to the regular screen, we restore the mode that was // in effect previously. this.console[1].style[transform] = ''; } var style = this.console[this.currentScreen].style[transform]; this.cursor.style[transform] = style; this.space.style[transform] = style; this.scale = style == '' ? 1.0:1.65; if (transform == 'filter') { this.console[this.currentScreen].style.width = style == '' ? '165%':''; } } this.resizer(); // If we switched to the alternate screen, reset it completely. Otherwise, // restore the saved state. if (state) { this.gotoXY(0, 0); this.clearRegion(0, 0, this.terminalWidth, this.terminalHeight); } else { this.restoreCursor(); } }; VT100.prototype.hideCursor = function() { var hidden = this.cursor.style.visibility == 'hidden'; if (!hidden) { this.cursor.style.visibility = 'hidden'; return true; } return false; }; VT100.prototype.showCursor = function(x, y) { if (this.cursor.style.visibility) { this.cursor.style.visibility = ''; this.putString(x == undefined ? this.cursorX : x, y == undefined ? this.cursorY : y, '', undefined); return true; } return false; }; VT100.prototype.scrollBack = function() { var i = this.scrollable.scrollTop - this.scrollable.clientHeight; this.scrollable.scrollTop = i < 0 ? 0 : i; }; VT100.prototype.scrollFore = function() { var i = this.scrollable.scrollTop + this.scrollable.clientHeight; this.scrollable.scrollTop = i > this.numScrollbackLines * this.cursorHeight + 1 ? this.numScrollbackLines * this.cursorHeight + 1 : i; }; VT100.prototype.spaces = function(i) { var s = ''; while (i-- > 0) { s += ' '; } return s; }; VT100.prototype.clearRegion = function(x, y, w, h, color, style) { w += x; if (x < 0) { x = 0; } if (w > this.terminalWidth) { w = this.terminalWidth; } if ((w -= x) <= 0) { return; } h += y; if (y < 0) { y = 0; } if (h > this.terminalHeight) { h = this.terminalHeight; } if ((h -= y) <= 0) { return; } // Special case the situation where we clear the entire screen, and we do // not have a scrollback buffer. In that case, we should just remove all // child nodes. if (!this.numScrollbackLines && w == this.terminalWidth && h == this.terminalHeight && (color == undefined || color == 'ansi0 bgAnsi15') && !style) { var console = this.console[this.currentScreen]; while (console.lastChild) { console.removeChild(console.lastChild); } this.putString(this.cursorX, this.cursorY, '', undefined); } else { var hidden = this.hideCursor(); var cx = this.cursorX; var cy = this.cursorY; var s = this.spaces(w); for (var i = y+h; i-- > y; ) { this.putString(x, i, s, color, style); } hidden ? this.showCursor(cx, cy) : this.putString(cx, cy, '', undefined); } }; VT100.prototype.copyLineSegment = function(dX, dY, sX, sY, w) { var text = [ ]; var className = [ ]; var style = [ ]; var console = this.console[this.currentScreen]; if (sY >= console.childNodes.length) { text[0] = this.spaces(w); className[0] = undefined; style[0] = undefined; } else { var line = console.childNodes[sY]; if (line.tagName != 'DIV' || !line.childNodes.length) { text[0] = this.spaces(w); className[0] = undefined; style[0] = undefined; } else { var x = 0; for (var span = line.firstChild; span && w > 0; span = span.nextSibling){ var s = this.getTextContent(span); var len = s.length; if (x + len > sX) { var o = sX > x ? sX - x : 0; text[text.length] = s.substr(o, w); className[className.length] = span.className; style[style.length] = span.style.cssText; w -= len - o; } x += len; } if (w > 0) { text[text.length] = this.spaces(w); className[className.length] = undefined; style[style.length] = undefined; } } } var hidden = this.hideCursor(); var cx = this.cursorX; var cy = this.cursorY; for (var i = 0; i < text.length; i++) { var color; if (className[i]) { color = className[i]; } else { color = 'ansi0 bgAnsi15'; } this.putString(dX, dY - this.numScrollbackLines, text[i], color, style[i]); dX += text[i].length; } hidden ? this.showCursor(cx, cy) : this.putString(cx, cy, '', undefined); }; VT100.prototype.scrollRegion = function(x, y, w, h, incX, incY, color, style) { var left = incX < 0 ? -incX : 0; var right = incX > 0 ? incX : 0; var up = incY < 0 ? -incY : 0; var down = incY > 0 ? incY : 0; // Clip region against terminal size var dontScroll = null; w += x; if (x < left) { x = left; } if (w > this.terminalWidth - right) { w = this.terminalWidth - right; } if ((w -= x) <= 0) { dontScroll = 1; } h += y; if (y < up) { y = up; } if (h > this.terminalHeight - down) { h = this.terminalHeight - down; } if ((h -= y) < 0) { dontScroll = 1; } if (!dontScroll) { if (style && style.indexOf('underline')) { // Different terminal emulators disagree on the attributes that // are used for scrolling. The consensus seems to be, never to // fill with underlined spaces. N.B. this is different from the // cases when the user blanks a region. User-initiated blanking // always fills with all of the current attributes. style = style.replace(/text-decoration:underline;/, ''); } // Compute current scroll position var scrollPos = this.numScrollbackLines - (this.scrollable.scrollTop-1) / this.cursorHeight; // Determine original cursor position. Hide cursor temporarily to avoid // visual artifacts. var hidden = this.hideCursor(); var cx = this.cursorX; var cy = this.cursorY; var console = this.console[this.currentScreen]; if (!incX && !x && w == this.terminalWidth) { // Scrolling entire lines if (incY < 0) { // Scrolling up if (!this.currentScreen && y == -incY && h == this.terminalHeight + incY) { // Scrolling up with adding to the scrollback buffer. This is only // possible if there are at least as many lines in the console, // as the terminal is high while (console.childNodes.length < this.terminalHeight) { this.insertBlankLine(this.terminalHeight); } // Add new lines at bottom in order to force scrolling for (var i = 0; i < y; i++) { this.insertBlankLine(console.childNodes.length, color, style); } // Adjust the number of lines in the scrollback buffer by // removing excess entries. this.updateNumScrollbackLines(); while (this.numScrollbackLines > (this.currentScreen ? 0 : this.maxScrollbackLines)) { console.removeChild(console.firstChild); this.numScrollbackLines--; } // Mark lines in the scrollback buffer, so that they do not get // printed. for (var i = this.numScrollbackLines, j = -incY; i-- > 0 && j-- > 0; ) { console.childNodes[i].className = 'scrollback'; } } else { // Scrolling up without adding to the scrollback buffer. for (var i = -incY; i-- > 0 && console.childNodes.length > this.numScrollbackLines + y + incY; ) { console.removeChild(console.childNodes[ this.numScrollbackLines + y + incY]); } // If we used to have a scrollback buffer, then we must make sure // that we add back blank lines at the bottom of the terminal. // Similarly, if we are scrolling in the middle of the screen, // we must add blank lines to ensure that the bottom of the screen // does not move up. if (this.numScrollbackLines > 0 || console.childNodes.length > this.numScrollbackLines+y+h+incY) { for (var i = -incY; i-- > 0; ) { this.insertBlankLine(this.numScrollbackLines + y + h + incY, color, style); } } } } else { // Scrolling down for (var i = incY; i-- > 0 && console.childNodes.length > this.numScrollbackLines + y + h; ) { console.removeChild(console.childNodes[this.numScrollbackLines+y+h]); } for (var i = incY; i--; ) { this.insertBlankLine(this.numScrollbackLines + y, color, style); } } } else { // Scrolling partial lines if (incY <= 0) { // Scrolling up or horizontally within a line for (var i = y + this.numScrollbackLines; i < y + this.numScrollbackLines + h; i++) { this.copyLineSegment(x + incX, i + incY, x, i, w); } } else { // Scrolling down for (var i = y + this.numScrollbackLines + h; i-- > y + this.numScrollbackLines; ) { this.copyLineSegment(x + incX, i + incY, x, i, w); } } // Clear blank regions if (incX > 0) { this.clearRegion(x, y, incX, h, color, style); } else if (incX < 0) { this.clearRegion(x + w + incX, y, -incX, h, color, style); } if (incY > 0) { this.clearRegion(x, y, w, incY, color, style); } else if (incY < 0) { this.clearRegion(x, y + h + incY, w, -incY, color, style); } } // Reset scroll position this.scrollable.scrollTop = (this.numScrollbackLines-scrollPos) * this.cursorHeight + 1; // Move cursor back to its original position hidden ? this.showCursor(cx, cy) : this.putString(cx, cy, '', undefined); } }; VT100.prototype.copy = function(selection) { if (selection == undefined) { selection = this.selection(); } this.internalClipboard = undefined; if (selection.length) { try { // IE this.cliphelper.value = selection; this.cliphelper.select(); this.cliphelper.createTextRange().execCommand('copy'); } catch (e) { this.internalClipboard = selection; } this.cliphelper.value = ''; } }; VT100.prototype.copyLast = function() { // Opening the context menu can remove the selection. We try to prevent this // from happening, but that is not possible for all browsers. So, instead, // we compute the selection before showing the menu. this.copy(this.lastSelection); }; VT100.prototype.pasteFnc = function() { var clipboard = undefined; if (this.internalClipboard != undefined) { clipboard = this.internalClipboard; } else { try { this.cliphelper.value = ''; this.cliphelper.createTextRange().execCommand('paste'); clipboard = this.cliphelper.value; } catch (e) { } } this.cliphelper.value = ''; if (clipboard && this.menu.style.visibility == 'hidden') { return function() { this.keysPressed('' + clipboard); }; } else { return undefined; } }; VT100.prototype.pasteBrowserFnc = function() { var clipboard = prompt("Paste into this box:",""); if (clipboard != undefined) { return this.keysPressed('' + clipboard); } }; VT100.prototype.toggleUTF = function() { this.utfEnabled = !this.utfEnabled; // We always persist the last value that the user selected. Not necessarily // the last value that a random program requested. this.utfPreferred = this.utfEnabled; }; VT100.prototype.toggleBell = function() { this.visualBell = !this.visualBell; }; VT100.prototype.toggleSoftKeyboard = function() { this.softKeyboard = !this.softKeyboard; this.keyboardImage.style.visibility = this.softKeyboard ? 'visible' : ''; }; VT100.prototype.deselectKeys = function(elem) { if (elem && elem.className == 'selected') { elem.className = ''; } for (elem = elem.firstChild; elem; elem = elem.nextSibling) { this.deselectKeys(elem); } }; VT100.prototype.showSoftKeyboard = function() { // Make sure no key is currently selected this.lastSelectedKey = undefined; this.deselectKeys(this.keyboard); this.isShift = false; this.showShiftState(false); this.isCtrl = false; this.showCtrlState(false); this.isAlt = false; this.showAltState(false); this.keyboard.style.left = '0px'; this.keyboard.style.top = '0px'; this.keyboard.style.width = this.container.offsetWidth + 'px'; this.keyboard.style.height = this.container.offsetHeight + 'px'; this.keyboard.style.visibility = 'hidden'; this.keyboard.style.display = ''; var kbd = this.keyboard.firstChild; var scale = 1.0; var transform = this.getTransformName(); if (transform) { kbd.style[transform] = ''; if (kbd.offsetWidth > 0.9 * this.container.offsetWidth) { scale = (kbd.offsetWidth/ this.container.offsetWidth)/0.9; } if (kbd.offsetHeight > 0.9 * this.container.offsetHeight) { scale = Math.max((kbd.offsetHeight/ this.container.offsetHeight)/0.9); } var style = this.getTransformStyle(transform, scale > 1.0 ? scale : undefined); kbd.style[transform] = style; } if (transform == 'filter') { scale = 1.0; } kbd.style.left = ((this.container.offsetWidth - kbd.offsetWidth/scale)/2) + 'px'; kbd.style.top = ((this.container.offsetHeight - kbd.offsetHeight/scale)/2) + 'px'; this.keyboard.style.visibility = 'visible'; }; VT100.prototype.hideSoftKeyboard = function() { this.keyboard.style.display = 'none'; }; VT100.prototype.toggleCursorBlinking = function() { this.blinkingCursor = !this.blinkingCursor; }; VT100.prototype.about = function() { alert("VT100 Terminal Emulator " + "2.10 (revision 239)" + "\nCopyright 2008-2010 by Markus Gutschke\n" + "For more information check http://shellinabox.com"); }; VT100.prototype.hideContextMenu = function() { this.menu.style.visibility = 'hidden'; this.menu.style.top = '-100px'; this.menu.style.left = '-100px'; this.menu.style.width = '0px'; this.menu.style.height = '0px'; }; VT100.prototype.extendContextMenu = function(entries, actions) { }; VT100.prototype.showContextMenu = function(x, y) { this.menu.innerHTML = '<table class="popup" ' + 'cellpadding="0" cellspacing="0">' + '<tr><td>' + '<ul id="menuentries">' + '<li id="beginclipboard">Copy</li>' + '<li id="endclipboard">Paste</li>' + '<li id="browserclipboard">Paste from browser</li>' + '<hr />' + '<li id="reset">Reset</li>' + '<hr />' + '<li id="beginconfig">' + (this.utfEnabled ? '<img src="enabled.gif" />' : '') + 'Unicode</li>' + '<li>' + (this.visualBell ? '<img src="enabled.gif" />' : '') + 'Visual Bell</li>'+ '<li>' + (this.softKeyboard ? '<img src="enabled.gif" />' : '') + 'Onscreen Keyboard</li>' + '<li id="endconfig">' + (this.blinkingCursor ? '<img src="enabled.gif" />' : '') + 'Blinking Cursor</li>'+ (this.usercss.firstChild ? '<hr id="beginusercss" />' + this.usercss.innerHTML + '<hr id="endusercss" />' : '<hr />') + '<li id="about">About...</li>' + '</ul>' + '</td></tr>' + '</table>'; var popup = this.menu.firstChild; var menuentries = this.getChildById(popup, 'menuentries'); // Determine menu entries that should be disabled this.lastSelection = this.selection(); if (!this.lastSelection.length) { menuentries.firstChild.className = 'disabled'; } var p = this.pasteFnc(); if (!p) { menuentries.childNodes[1].className = 'disabled'; } // Actions for default items var actions = [ this.copyLast, p, this.pasteBrowserFnc, this.reset, this.toggleUTF, this.toggleBell, this.toggleSoftKeyboard, this.toggleCursorBlinking ]; // Actions for user CSS styles (if any) for (var i = 0; i < this.usercssActions.length; ++i) { actions[actions.length] = this.usercssActions[i]; } actions[actions.length] = this.about; // Allow subclasses to dynamically add entries to the context menu this.extendContextMenu(menuentries, actions); // Hook up event listeners for (var node = menuentries.firstChild, i = 0; node; node = node.nextSibling) { if (node.tagName == 'LI') { if (node.className != 'disabled') { this.addListener(node, 'mouseover', function(vt100, node) { return function() { node.className = 'hover'; } }(this, node)); this.addListener(node, 'mouseout', function(vt100, node) { return function() { node.className = ''; } }(this, node)); this.addListener(node, 'mousedown', function(vt100, action) { return function(event) { vt100.hideContextMenu(); action.call(vt100); vt100.storeUserSettings(); return vt100.cancelEvent(event || window.event); } }(this, actions[i])); this.addListener(node, 'mouseup', function(vt100) { return function(event) { return vt100.cancelEvent(event || window.event); } }(this)); this.addListener(node, 'mouseclick', function(vt100) { return function(event) { return vt100.cancelEvent(event || window.event); } }()); } i++; } } // Position menu next to the mouse pointer this.menu.style.left = '0px'; this.menu.style.top = '0px'; this.menu.style.width = this.container.offsetWidth + 'px'; this.menu.style.height = this.container.offsetHeight + 'px'; popup.style.left = '0px'; popup.style.top = '0px'; var margin = 2; if (x + popup.clientWidth >= this.container.offsetWidth - margin) { x = this.container.offsetWidth-popup.clientWidth - margin - 1; } if (x < margin) { x = margin; } if (y + popup.clientHeight >= this.container.offsetHeight - margin) { y = this.container.offsetHeight-popup.clientHeight - margin - 1; } if (y < margin) { y = margin; } popup.style.left = x + 'px'; popup.style.top = y + 'px'; // Block all other interactions with the terminal emulator this.addListener(this.menu, 'click', function(vt100) { return function() { vt100.hideContextMenu(); } }(this)); // Show the menu this.menu.style.visibility = ''; }; VT100.prototype.keysPressed = function(ch) { for (var i = 0; i < ch.length; i++) { var c = ch.charCodeAt(i); this.vt100(c >= 7 && c <= 15 || c == 24 || c == 26 || c == 27 || c >= 32 ? String.fromCharCode(c) : '<' + c + '>'); } }; VT100.prototype.applyModifiers = function(ch, event) { if (ch) { if (event.ctrlKey) { if (ch >= 32 && ch <= 127) { // For historic reasons, some control characters are treated specially switch (ch) { case /* 3 */ 51: ch = 27; break; case /* 4 */ 52: ch = 28; break; case /* 5 */ 53: ch = 29; break; case /* 6 */ 54: ch = 30; break; case /* 7 */ 55: ch = 31; break; case /* 8 */ 56: ch = 127; break; case /* ? */ 63: ch = 127; break; default: ch &= 31; break; } } } return String.fromCharCode(ch); } else { return undefined; } }; VT100.prototype.handleKey = function(event) { // this.vt100('H: c=' + event.charCode + ', k=' + event.keyCode + // (event.shiftKey || event.ctrlKey || event.altKey || // event.metaKey ? ', ' + // (event.shiftKey ? 'S' : '') + (event.ctrlKey ? 'C' : '') + // (event.altKey ? 'A' : '') + (event.metaKey ? 'M' : '') : '') + // '\r\n'); var ch, key; if (typeof event.charCode != 'undefined') { // non-IE keypress events have a translated charCode value. Also, our // fake events generated when receiving keydown events include this data // on all browsers. ch = event.charCode; key = event.keyCode; } else { // When sending a keypress event, IE includes the translated character // code in the keyCode field. ch = event.keyCode; key = undefined; } // Apply modifier keys (ctrl and shift) if (ch) { key = undefined; } ch = this.applyModifiers(ch, event); // By this point, "ch" is either defined and contains the character code, or // it is undefined and "key" defines the code of a function key if (ch != undefined) { this.scrollable.scrollTop = this.numScrollbackLines * this.cursorHeight + 1; } else { if ((event.altKey || event.metaKey) && !event.shiftKey && !event.ctrlKey) { // Many programs have difficulties dealing with parametrized escape // sequences for function keys. Thus, if ALT is the only modifier // key, return Emacs-style keycodes for commonly used keys. switch (key) { case 33: /* Page Up */ ch = '\u001B<'; break; case 34: /* Page Down */ ch = '\u001B>'; break; case 37: /* Left */ ch = '\u001Bb'; break; case 38: /* Up */ ch = '\u001Bp'; break; case 39: /* Right */ ch = '\u001Bf'; break; case 40: /* Down */ ch = '\u001Bn'; break; case 46: /* Delete */ ch = '\u001Bd'; break; default: break; } } else if (event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey) { switch (key) { case 33: /* Page Up */ this.scrollBack(); return; case 34: /* Page Down */ this.scrollFore(); return; default: break; } } if (ch == undefined) { switch (key) { case 8: /* Backspace */ ch = '\u007f'; break; case 9: /* Tab */ ch = '\u0009'; break; case 10: /* Return */ ch = '\u000A'; break; case 13: /* Enter */ ch = this.crLfMode ? '\r\n' : '\r'; break; case 16: /* Shift */ return; case 17: /* Ctrl */ return; case 18: /* Alt */ return; case 19: /* Break */ return; case 20: /* Caps Lock */ return; case 27: /* Escape */ ch = '\u001B'; break; case 33: /* Page Up */ ch = '\u001B[5~'; break; case 34: /* Page Down */ ch = '\u001B[6~'; break; case 35: /* End */ ch = '\u001BOF'; break; case 36: /* Home */ ch = '\u001BOH'; break; case 37: /* Left */ ch = this.cursorKeyMode ? '\u001BOD' : '\u001B[D'; break; case 38: /* Up */ ch = this.cursorKeyMode ? '\u001BOA' : '\u001B[A'; break; case 39: /* Right */ ch = this.cursorKeyMode ? '\u001BOC' : '\u001B[C'; break; case 40: /* Down */ ch = this.cursorKeyMode ? '\u001BOB' : '\u001B[B'; break; case 45: /* Insert */ ch = '\u001B[2~'; break; case 46: /* Delete */ ch = '\u001B[3~'; break; case 91: /* Left Window */ return; case 92: /* Right Window */ return; case 93: /* Select */ return; case 96: /* 0 */ ch = this.applyModifiers(48, event); break; case 97: /* 1 */ ch = this.applyModifiers(49, event); break; case 98: /* 2 */ ch = this.applyModifiers(50, event); break; case 99: /* 3 */ ch = this.applyModifiers(51, event); break; case 100: /* 4 */ ch = this.applyModifiers(52, event); break; case 101: /* 5 */ ch = this.applyModifiers(53, event); break; case 102: /* 6 */ ch = this.applyModifiers(54, event); break; case 103: /* 7 */ ch = this.applyModifiers(55, event); break; case 104: /* 8 */ ch = this.applyModifiers(56, event); break; case 105: /* 9 */ ch = this.applyModifiers(58, event); break; case 106: /* * */ ch = this.applyModifiers(42, event); break; case 107: /* + */ ch = this.applyModifiers(43, event); break; case 109: /* - */ ch = this.applyModifiers(45, event); break; case 110: /* . */ ch = this.applyModifiers(46, event); break; case 111: /* / */ ch = this.applyModifiers(47, event); break; case 112: /* F1 */ ch = '\u001BOP'; break; case 113: /* F2 */ ch = '\u001BOQ'; break; case 114: /* F3 */ ch = '\u001BOR'; break; case 115: /* F4 */ ch = '\u001BOS'; break; case 116: /* F5 */ ch = '\u001B[15~'; break; case 117: /* F6 */ ch = '\u001B[17~'; break; case 118: /* F7 */ ch = '\u001B[18~'; break; case 119: /* F8 */ ch = '\u001B[19~'; break; case 120: /* F9 */ ch = '\u001B[20~'; break; case 121: /* F10 */ ch = '\u001B[21~'; break; case 122: /* F11 */ ch = '\u001B[23~'; break; case 123: /* F12 */ ch = '\u001B[24~'; break; case 144: /* Num Lock */ return; case 145: /* Scroll Lock */ return; case 186: /* ; */ ch = this.applyModifiers(59, event); break; case 187: /* = */ ch = this.applyModifiers(61, event); break; case 188: /* , */ ch = this.applyModifiers(44, event); break; case 189: /* - */ ch = this.applyModifiers(45, event); break; case 190: /* . */ ch = this.applyModifiers(46, event); break; case 191: /* / */ ch = this.applyModifiers(47, event); break; // Conflicts with dead key " on Swiss keyboards //case 192: /* ` */ ch = this.applyModifiers(96, event); break; // Conflicts with dead key " on Swiss keyboards //case 219: /* [ */ ch = this.applyModifiers(91, event); break; case 220: /* \ */ ch = this.applyModifiers(92, event); break; // Conflicts with dead key ^ and ` on Swiss keaboards // ^ and " on French keyboards //case 221: /* ] */ ch = this.applyModifiers(93, event); break; case 222: /* ' */ ch = this.applyModifiers(39, event); break; default: return; } this.scrollable.scrollTop = this.numScrollbackLines * this.cursorHeight + 1; } } // "ch" now contains the sequence of keycodes to send. But we might still // have to apply the effects of modifier keys. if (event.shiftKey || event.ctrlKey || event.altKey || event.metaKey) { var start, digit, part1, part2; if ((start = ch.substr(0, 2)) == '\u001B[') { for (part1 = start; part1.length < ch.length && (digit = ch.charCodeAt(part1.length)) >= 48 && digit <= 57; ) { part1 = ch.substr(0, part1.length + 1); } part2 = ch.substr(part1.length); if (part1.length > 2) { part1 += ';'; } } else if (start == '\u001BO') { part1 = start; part2 = ch.substr(2); } if (part1 != undefined) { ch = part1 + ((event.shiftKey ? 1 : 0) + (event.altKey|event.metaKey ? 2 : 0) + (event.ctrlKey ? 4 : 0)) + part2; } else if (ch.length == 1 && (event.altKey || event.metaKey)) { ch = '\u001B' + ch; } } if (this.menu.style.visibility == 'hidden') { // this.vt100('R: c='); // for (var i = 0; i < ch.length; i++) // this.vt100((i != 0 ? ', ' : '') + ch.charCodeAt(i)); // this.vt100('\r\n'); this.keysPressed(ch); } }; VT100.prototype.inspect = function(o, d) { if (d == undefined) { d = 0; } var rc = ''; if (typeof o == 'object' && ++d < 2) { rc = '[\r\n'; for (i in o) { rc += this.spaces(d * 2) + i + ' -> '; try { rc += this.inspect(o[i], d); } catch (e) { rc += '?' + '?' + '?\r\n'; } } rc += ']\r\n'; } else { rc += ('' + o).replace(/\n/g, ' ').replace(/ +/g,' ') + '\r\n'; } return rc; }; VT100.prototype.checkComposedKeys = function(event) { // Composed keys (at least on Linux) do not generate normal events. // Instead, they get entered into the text field. We normally catch // this on the next keyup event. var s = this.input.value; if (s.length) { this.input.value = ''; if (this.menu.style.visibility == 'hidden') { this.keysPressed(s); } } }; VT100.prototype.fixEvent = function(event) { // Some browsers report AltGR as a combination of ALT and CTRL. As AltGr // is used as a second-level selector, clear the modifier bits before // handling the event. if (event.ctrlKey && event.altKey) { var fake = [ ]; fake.charCode = event.charCode; fake.keyCode = event.keyCode; fake.ctrlKey = false; fake.shiftKey = event.shiftKey; fake.altKey = false; fake.metaKey = event.metaKey; return fake; } // Some browsers fail to translate keys, if both shift and alt/meta is // pressed at the same time. We try to translate those cases, but that // only works for US keyboard layouts. if (event.shiftKey) { var u = undefined; var s = undefined; switch (this.lastNormalKeyDownEvent.keyCode) { case 39: /* ' -> " */ u = 39; s = 34; break; case 44: /* , -> < */ u = 44; s = 60; break; case 45: /* - -> _ */ u = 45; s = 95; break; case 46: /* . -> > */ u = 46; s = 62; break; case 47: /* / -> ? */ u = 47; s = 63; break; case 48: /* 0 -> ) */ u = 48; s = 41; break; case 49: /* 1 -> ! */ u = 49; s = 33; break; case 50: /* 2 -> @ */ u = 50; s = 64; break; case 51: /* 3 -> # */ u = 51; s = 35; break; case 52: /* 4 -> $ */ u = 52; s = 36; break; case 53: /* 5 -> % */ u = 53; s = 37; break; case 54: /* 6 -> ^ */ u = 54; s = 94; break; case 55: /* 7 -> & */ u = 55; s = 38; break; case 56: /* 8 -> * */ u = 56; s = 42; break; case 57: /* 9 -> ( */ u = 57; s = 40; break; case 59: /* ; -> : */ u = 59; s = 58; break; case 61: /* = -> + */ u = 61; s = 43; break; case 91: /* [ -> { */ u = 91; s = 123; break; case 92: /* \ -> | */ u = 92; s = 124; break; case 93: /* ] -> } */ u = 93; s = 125; break; case 96: /* ` -> ~ */ u = 96; s = 126; break; case 109: /* - -> _ */ u = 45; s = 95; break; case 111: /* / -> ? */ u = 47; s = 63; break; case 186: /* ; -> : */ u = 59; s = 58; break; case 187: /* = -> + */ u = 61; s = 43; break; case 188: /* , -> < */ u = 44; s = 60; break; case 189: /* - -> _ */ u = 45; s = 95; break; case 190: /* . -> > */ u = 46; s = 62; break; case 191: /* / -> ? */ u = 47; s = 63; break; case 192: /* ` -> ~ */ u = 96; s = 126; break; case 219: /* [ -> { */ u = 91; s = 123; break; case 220: /* \ -> | */ u = 92; s = 124; break; case 221: /* ] -> } */ u = 93; s = 125; break; case 222: /* ' -> " */ u = 39; s = 34; break; default: break; } if (s && (event.charCode == u || event.charCode == 0)) { var fake = [ ]; fake.charCode = s; fake.keyCode = event.keyCode; fake.ctrlKey = event.ctrlKey; fake.shiftKey = event.shiftKey; fake.altKey = event.altKey; fake.metaKey = event.metaKey; return fake; } } return event; }; VT100.prototype.keyDown = function(event) { // this.vt100('D: c=' + event.charCode + ', k=' + event.keyCode + // (event.shiftKey || event.ctrlKey || event.altKey || // event.metaKey ? ', ' + // (event.shiftKey ? 'S' : '') + (event.ctrlKey ? 'C' : '') + // (event.altKey ? 'A' : '') + (event.metaKey ? 'M' : '') : '') + // '\r\n'); this.checkComposedKeys(event); this.lastKeyPressedEvent = undefined; this.lastKeyDownEvent = undefined; this.lastNormalKeyDownEvent = event; // Swiss keyboard conflicts: // [ 59 // ] 192 // ' 219 (dead key) // { 220 // ~ 221 (dead key) // } 223 // French keyoard conflicts: // ~ 50 (dead key) // } 107 var asciiKey = event.keyCode == 32 || event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode >= 65 && event.keyCode <= 90; var alphNumKey = asciiKey || event.keyCode == 59 || event.keyCode >= 96 && event.keyCode <= 105 || event.keyCode == 107 || event.keyCode == 192 || event.keyCode >= 219 && event.keyCode <= 221 || event.keyCode == 223 || event.keyCode == 226; var normalKey = alphNumKey || event.keyCode == 61 || event.keyCode == 106 || event.keyCode >= 109 && event.keyCode <= 111 || event.keyCode >= 186 && event.keyCode <= 191 || event.keyCode == 222 || event.keyCode == 252; try { if (navigator.appName == 'Konqueror') { normalKey |= event.keyCode < 128; } } catch (e) { } // We normally prefer to look at keypress events, as they perform the // translation from keyCode to charCode. This is important, as the // translation is locale-dependent. // But for some keys, we must intercept them during the keydown event, // as they would otherwise get interpreted by the browser. // Even, when doing all of this, there are some keys that we can never // intercept. This applies to some of the menu navigation keys in IE. // In fact, we see them, but we cannot stop IE from seeing them, too. if ((event.charCode || event.keyCode) && ((alphNumKey && (event.ctrlKey || event.altKey || event.metaKey) && !event.shiftKey && // Some browsers signal AltGR as both CTRL and ALT. Do not try to // interpret this sequence ourselves, as some keyboard layouts use // it for second-level layouts. !(event.ctrlKey && event.altKey)) || this.catchModifiersEarly && normalKey && !alphNumKey && (event.ctrlKey || event.altKey || event.metaKey) || !normalKey)) { this.lastKeyDownEvent = event; var fake = [ ]; fake.ctrlKey = event.ctrlKey; fake.shiftKey = event.shiftKey; fake.altKey = event.altKey; fake.metaKey = event.metaKey; if (asciiKey) { fake.charCode = event.keyCode; fake.keyCode = 0; } else { fake.charCode = 0; fake.keyCode = event.keyCode; if (!alphNumKey && event.shiftKey) { fake = this.fixEvent(fake); } } this.handleKey(fake); this.lastNormalKeyDownEvent = undefined; try { // For non-IE browsers event.stopPropagation(); event.preventDefault(); } catch (e) { } try { // For IE event.cancelBubble = true; event.returnValue = false; event.keyCode = 0; } catch (e) { } return false; } return true; }; VT100.prototype.keyPressed = function(event) { // this.vt100('P: c=' + event.charCode + ', k=' + event.keyCode + // (event.shiftKey || event.ctrlKey || event.altKey || // event.metaKey ? ', ' + // (event.shiftKey ? 'S' : '') + (event.ctrlKey ? 'C' : '') + // (event.altKey ? 'A' : '') + (event.metaKey ? 'M' : '') : '') + // '\r\n'); if (this.lastKeyDownEvent) { // If we already processed the key on keydown, do not process it // again here. Ideally, the browser should not even have generated a // keypress event in this case. But that does not appear to always work. this.lastKeyDownEvent = undefined; } else { this.handleKey(event.altKey || event.metaKey ? this.fixEvent(event) : event); } try { // For non-IE browsers event.preventDefault(); } catch (e) { } try { // For IE event.cancelBubble = true; event.returnValue = false; event.keyCode = 0; } catch (e) { } this.lastNormalKeyDownEvent = undefined; this.lastKeyPressedEvent = event; return false; }; VT100.prototype.keyUp = function(event) { // this.vt100('U: c=' + event.charCode + ', k=' + event.keyCode + // (event.shiftKey || event.ctrlKey || event.altKey || // event.metaKey ? ', ' + // (event.shiftKey ? 'S' : '') + (event.ctrlKey ? 'C' : '') + // (event.altKey ? 'A' : '') + (event.metaKey ? 'M' : '') : '') + // '\r\n'); if (this.lastKeyPressedEvent) { // The compose key on Linux occasionally confuses the browser and keeps // inserting bogus characters into the input field, even if just a regular // key has been pressed. Detect this case and drop the bogus characters. (event.target || event.srcElement).value = ''; } else { // This is usually were we notice that a key has been composed and // thus failed to generate normal events. this.checkComposedKeys(event); // Some browsers don't report keypress events if ctrl or alt is pressed // for non-alphanumerical keys. Patch things up for now, but in the // future we will catch these keys earlier (in the keydown handler). if (this.lastNormalKeyDownEvent) { // this.vt100('ENABLING EARLY CATCHING OF MODIFIER KEYS\r\n'); this.catchModifiersEarly = true; var asciiKey = event.keyCode == 32 || // Conflicts with dead key ~ (code 50) on French keyboards //event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode >= 48 && event.keyCode <= 49 || event.keyCode >= 51 && event.keyCode <= 57 || event.keyCode >= 65 && event.keyCode <= 90; var alphNumKey = asciiKey || event.keyCode == 50 || event.keyCode >= 96 && event.keyCode <= 105; var normalKey = alphNumKey || event.keyCode == 59 || event.keyCode == 61 || event.keyCode == 106 || event.keyCode == 107 || event.keyCode >= 109 && event.keyCode <= 111 || event.keyCode >= 186 && event.keyCode <= 192 || event.keyCode >= 219 && event.keyCode <= 223 || event.keyCode == 252; var fake = [ ]; fake.ctrlKey = event.ctrlKey; fake.shiftKey = event.shiftKey; fake.altKey = event.altKey; fake.metaKey = event.metaKey; if (asciiKey) { fake.charCode = event.keyCode; fake.keyCode = 0; } else { fake.charCode = 0; fake.keyCode = event.keyCode; if (!alphNumKey && (event.ctrlKey || event.altKey || event.metaKey)) { fake = this.fixEvent(fake); } } this.lastNormalKeyDownEvent = undefined; this.handleKey(fake); } } try { // For IE event.cancelBubble = true; event.returnValue = false; event.keyCode = 0; } catch (e) { } this.lastKeyDownEvent = undefined; this.lastKeyPressedEvent = undefined; return false; }; VT100.prototype.animateCursor = function(inactive) { if (!this.cursorInterval) { this.cursorInterval = setInterval( function(vt100) { return function() { vt100.animateCursor(); // Use this opportunity to check whether the user entered a composed // key, or whether somebody pasted text into the textfield. vt100.checkComposedKeys(); } }(this), 500); } if (inactive != undefined || this.cursor.className != 'inactive') { if (inactive) { this.cursor.className = 'inactive'; } else { if (this.blinkingCursor) { this.cursor.className = this.cursor.className == 'bright' ? 'dim' : 'bright'; } else { this.cursor.className = 'bright'; } } } }; VT100.prototype.blurCursor = function() { this.animateCursor(true); }; VT100.prototype.focusCursor = function() { this.animateCursor(false); }; VT100.prototype.flashScreen = function() { this.isInverted = !this.isInverted; this.refreshInvertedState(); this.isInverted = !this.isInverted; setTimeout(function(vt100) { return function() { vt100.refreshInvertedState(); }; }(this), 100); }; VT100.prototype.beep = function() { if (this.visualBell) { this.flashScreen(); } else { try { this.beeper.Play(); } catch (e) { try { this.beeper.src = 'beep.wav'; } catch (e) { } } } }; VT100.prototype.bs = function() { if (this.cursorX > 0) { this.gotoXY(this.cursorX - 1, this.cursorY); this.needWrap = false; } }; VT100.prototype.ht = function(count) { if (count == undefined) { count = 1; } var cx = this.cursorX; while (count-- > 0) { while (cx++ < this.terminalWidth) { var tabState = this.userTabStop[cx]; if (tabState == false) { // Explicitly cleared tab stop continue; } else if (tabState) { // Explicitly set tab stop break; } else { // Default tab stop at each eighth column if (cx % 8 == 0) { break; } } } } if (cx > this.terminalWidth - 1) { cx = this.terminalWidth - 1; } if (cx != this.cursorX) { this.gotoXY(cx, this.cursorY); } }; VT100.prototype.rt = function(count) { if (count == undefined) { count = 1 ; } var cx = this.cursorX; while (count-- > 0) { while (cx-- > 0) { var tabState = this.userTabStop[cx]; if (tabState == false) { // Explicitly cleared tab stop continue; } else if (tabState) { // Explicitly set tab stop break; } else { // Default tab stop at each eighth column if (cx % 8 == 0) { break; } } } } if (cx < 0) { cx = 0; } if (cx != this.cursorX) { this.gotoXY(cx, this.cursorY); } }; VT100.prototype.cr = function() { this.gotoXY(0, this.cursorY); this.needWrap = false; }; VT100.prototype.lf = function(count) { if (count == undefined) { count = 1; } else { if (count > this.terminalHeight) { count = this.terminalHeight; } if (count < 1) { count = 1; } } while (count-- > 0) { if (this.cursorY == this.bottom - 1) { this.scrollRegion(0, this.top + 1, this.terminalWidth, this.bottom - this.top - 1, 0, -1, this.color, this.style); offset = undefined; } else if (this.cursorY < this.terminalHeight - 1) { this.gotoXY(this.cursorX, this.cursorY + 1); } } }; VT100.prototype.ri = function(count) { if (count == undefined) { count = 1; } else { if (count > this.terminalHeight) { count = this.terminalHeight; } if (count < 1) { count = 1; } } while (count-- > 0) { if (this.cursorY == this.top) { this.scrollRegion(0, this.top, this.terminalWidth, this.bottom - this.top - 1, 0, 1, this.color, this.style); } else if (this.cursorY > 0) { this.gotoXY(this.cursorX, this.cursorY - 1); } } this.needWrap = false; }; VT100.prototype.respondID = function() { this.respondString += '\u001B[?6c'; }; VT100.prototype.respondSecondaryDA = function() { this.respondString += '\u001B[>0;0;0c'; }; VT100.prototype.updateStyle = function() { this.style = ''; if (this.attr & 0x0200 /* ATTR_UNDERLINE */) { this.style = 'text-decoration: underline;'; } var bg = (this.attr >> 4) & 0xF; var fg = this.attr & 0xF; if (this.attr & 0x0100 /* ATTR_REVERSE */) { var tmp = bg; bg = fg; fg = tmp; } if ((this.attr & (0x0100 /* ATTR_REVERSE */ | 0x0400 /* ATTR_DIM */)) == 0x0400 /* ATTR_DIM */) { fg = 8; // Dark grey } else if (this.attr & 0x0800 /* ATTR_BRIGHT */) { fg |= 8; this.style = 'font-weight: bold;'; } if (this.attr & 0x1000 /* ATTR_BLINK */) { this.style = 'text-decoration: blink;'; } this.color = 'ansi' + fg + ' bgAnsi' + bg; }; VT100.prototype.setAttrColors = function(attr) { if (attr != this.attr) { this.attr = attr; this.updateStyle(); } }; VT100.prototype.saveCursor = function() { this.savedX[this.currentScreen] = this.cursorX; this.savedY[this.currentScreen] = this.cursorY; this.savedAttr[this.currentScreen] = this.attr; this.savedUseGMap = this.useGMap; for (var i = 0; i < 4; i++) { this.savedGMap[i] = this.GMap[i]; } this.savedValid[this.currentScreen] = true; }; VT100.prototype.restoreCursor = function() { if (!this.savedValid[this.currentScreen]) { return; } this.attr = this.savedAttr[this.currentScreen]; this.updateStyle(); this.useGMap = this.savedUseGMap; for (var i = 0; i < 4; i++) { this.GMap[i] = this.savedGMap[i]; } this.translate = this.GMap[this.useGMap]; this.needWrap = false; this.gotoXY(this.savedX[this.currentScreen], this.savedY[this.currentScreen]); }; VT100.prototype.getTransformName = function() { var styles = [ 'transform', 'WebkitTransform', 'MozTransform', 'filter' ]; for (var i = 0; i < styles.length; ++i) { if (typeof this.console[0].style[styles[i]] != 'undefined') { return styles[i]; } } return undefined; }; VT100.prototype.getTransformStyle = function(transform, scale) { return scale && scale != 1.0 ? transform == 'filter' ? 'progid:DXImageTransform.Microsoft.Matrix(' + 'M11=' + (1.0/scale) + ',M12=0,M21=0,M22=1,' + "sizingMethod='auto expand')" : 'translateX(-50%) ' + 'scaleX(' + (1.0/scale) + ') ' + 'translateX(50%)' : ''; }; VT100.prototype.set80_132Mode = function(state) { var transform = this.getTransformName(); if (transform) { if ((this.console[this.currentScreen].style[transform] != '') == state) { return; } var style = state ? this.getTransformStyle(transform, 1.65):''; this.console[this.currentScreen].style[transform] = style; this.cursor.style[transform] = style; this.space.style[transform] = style; this.scale = state ? 1.65 : 1.0; if (transform == 'filter') { this.console[this.currentScreen].style.width = state ? '165%' : ''; } this.resizer(); } }; VT100.prototype.setMode = function(state) { for (var i = 0; i <= this.npar; i++) { if (this.isQuestionMark) { switch (this.par[i]) { case 1: this.cursorKeyMode = state; break; case 3: this.set80_132Mode(state); break; case 5: this.isInverted = state; this.refreshInvertedState(); break; case 6: this.offsetMode = state; break; case 7: this.autoWrapMode = state; break; case 1000: case 9: this.mouseReporting = state; break; case 25: this.cursorNeedsShowing = state; if (state) { this.showCursor(); } else { this.hideCursor(); } break; case 1047: case 1049: case 47: this.enableAlternateScreen(state); break; default: break; } } else { switch (this.par[i]) { case 3: this.dispCtrl = state; break; case 4: this.insertMode = state; break; case 20:this.crLfMode = state; break; default: break; } } } }; VT100.prototype.statusReport = function() { // Ready and operational. this.respondString += '\u001B[0n'; }; VT100.prototype.cursorReport = function() { this.respondString += '\u001B[' + (this.cursorY + (this.offsetMode ? this.top + 1 : 1)) + ';' + (this.cursorX + 1) + 'R'; }; VT100.prototype.setCursorAttr = function(setAttr, xorAttr) { // Changing of cursor color is not implemented. }; VT100.prototype.openPrinterWindow = function() { var rc = true; try { if (!this.printWin || this.printWin.closed) { this.printWin = window.open('', 'print-output', 'width=800,height=600,directories=no,location=no,menubar=yes,' + 'status=no,toolbar=no,titlebar=yes,scrollbars=yes,resizable=yes'); this.printWin.document.body.innerHTML = '<link rel="stylesheet" href="' + document.location.protocol + '//' + document.location.host + document.location.pathname.replace(/[^/]*$/, '') + 'print-styles.css" type="text/css">\n' + '<div id="options"><input id="autoprint" type="checkbox"' + (this.autoprint ? ' checked' : '') + '>' + 'Automatically, print page(s) when job is ready' + '</input></div>\n' + '<div id="spacer"><input type="checkbox">&nbsp;</input></div>' + '<pre id="print"></pre>\n'; var autoprint = this.printWin.document.getElementById('autoprint'); this.addListener(autoprint, 'click', (function(vt100, autoprint) { return function() { vt100.autoprint = autoprint.checked; vt100.storeUserSettings(); return false; }; })(this, autoprint)); this.printWin.document.title = 'ShellInABox Printer Output'; } } catch (e) { // Maybe, a popup blocker prevented us from working. Better catch the // exception, so that we won't break the entire terminal session. The // user probably needs to disable the blocker first before retrying the // operation. rc = false; } rc &= this.printWin && !this.printWin.closed && (this.printWin.innerWidth || this.printWin.document.documentElement.clientWidth || this.printWin.document.body.clientWidth) > 1; if (!rc && this.printing == 100) { // Different popup blockers work differently. We try to detect a couple // of common methods. And then we retry again a brief amount later, as // false positives are otherwise possible. If we are sure that there is // a popup blocker in effect, we alert the user to it. This is helpful // as some popup blockers have minimal or no UI, and the user might not // notice that they are missing the popup. In any case, we only show at // most one message per print job. this.printing = true; setTimeout((function(win) { return function() { if (!win || win.closed || (win.innerWidth || win.document.documentElement.clientWidth || win.document.body.clientWidth) <= 1) { alert('Attempted to print, but a popup blocker ' + 'prevented the printer window from opening'); } }; })(this.printWin), 2000); } return rc; }; VT100.prototype.sendToPrinter = function(s) { this.openPrinterWindow(); try { var doc = this.printWin.document; var print = doc.getElementById('print'); if (print.lastChild && print.lastChild.nodeName == '#text') { print.lastChild.textContent += this.replaceChar(s, ' ', '\u00A0'); } else { print.appendChild(doc.createTextNode(this.replaceChar(s, ' ','\u00A0'))); } } catch (e) { // There probably was a more aggressive popup blocker that prevented us // from accessing the printer windows. } }; VT100.prototype.sendControlToPrinter = function(ch) { // We get called whenever doControl() is active. But for the printer, we // only implement a basic line printer that doesn't understand most of // the escape sequences of the VT100 terminal. In fact, the only escape // sequence that we really need to recognize is '^[[5i' for turning the // printer off. try { switch (ch) { case 9: // HT this.openPrinterWindow(); var doc = this.printWin.document; var print = doc.getElementById('print'); var chars = print.lastChild && print.lastChild.nodeName == '#text' ? print.lastChild.textContent.length : 0; this.sendToPrinter(this.spaces(8 - (chars % 8))); break; case 10: // CR break; case 12: // FF this.openPrinterWindow(); var pageBreak = this.printWin.document.createElement('div'); pageBreak.className = 'pagebreak'; pageBreak.innerHTML = '<hr />'; this.printWin.document.getElementById('print').appendChild(pageBreak); break; case 13: // LF this.openPrinterWindow(); var lineBreak = this.printWin.document.createElement('br'); this.printWin.document.getElementById('print').appendChild(lineBreak); break; case 27: // ESC this.isEsc = 1 /* ESesc */; break; default: switch (this.isEsc) { case 1 /* ESesc */: this.isEsc = 0 /* ESnormal */; switch (ch) { case 0x5B /*[*/: this.isEsc = 2 /* ESsquare */; break; default: break; } break; case 2 /* ESsquare */: this.npar = 0; this.par = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; this.isEsc = 3 /* ESgetpars */; this.isQuestionMark = ch == 0x3F /*?*/; if (this.isQuestionMark) { break; } // Fall through case 3 /* ESgetpars */: if (ch == 0x3B /*;*/) { this.npar++; break; } else if (ch >= 0x30 /*0*/ && ch <= 0x39 /*9*/) { var par = this.par[this.npar]; if (par == undefined) { par = 0; } this.par[this.npar] = 10*par + (ch & 0xF); break; } else { this.isEsc = 4 /* ESgotpars */; } // Fall through case 4 /* ESgotpars */: this.isEsc = 0 /* ESnormal */; if (this.isQuestionMark) { break; } switch (ch) { case 0x69 /*i*/: this.csii(this.par[0]); break; default: break; } break; default: this.isEsc = 0 /* ESnormal */; break; } break; } } catch (e) { // There probably was a more aggressive popup blocker that prevented us // from accessing the printer windows. } }; VT100.prototype.csiAt = function(number) { // Insert spaces if (number == 0) { number = 1; } if (number > this.terminalWidth - this.cursorX) { number = this.terminalWidth - this.cursorX; } this.scrollRegion(this.cursorX, this.cursorY, this.terminalWidth - this.cursorX - number, 1, number, 0, this.color, this.style); this.needWrap = false; }; VT100.prototype.csii = function(number) { // Printer control switch (number) { case 0: // Print Screen window.print(); break; case 4: // Stop printing try { if (this.printing && this.printWin && !this.printWin.closed) { var print = this.printWin.document.getElementById('print'); while (print.lastChild && print.lastChild.tagName == 'DIV' && print.lastChild.className == 'pagebreak') { // Remove trailing blank pages print.removeChild(print.lastChild); } if (this.autoprint) { this.printWin.print(); } } } catch (e) { } this.printing = false; break; case 5: // Start printing if (!this.printing && this.printWin && !this.printWin.closed) { this.printWin.document.getElementById('print').innerHTML = ''; } this.printing = 100; break; default: break; } }; VT100.prototype.csiJ = function(number) { switch (number) { case 0: // Erase from cursor to end of display this.clearRegion(this.cursorX, this.cursorY, this.terminalWidth - this.cursorX, 1, this.color, this.style); if (this.cursorY < this.terminalHeight-2) { this.clearRegion(0, this.cursorY+1, this.terminalWidth, this.terminalHeight-this.cursorY-1, this.color, this.style); } break; case 1: // Erase from start to cursor if (this.cursorY > 0) { this.clearRegion(0, 0, this.terminalWidth, this.cursorY, this.color, this.style); } this.clearRegion(0, this.cursorY, this.cursorX + 1, 1, this.color, this.style); break; case 2: // Erase whole display this.clearRegion(0, 0, this.terminalWidth, this.terminalHeight, this.color, this.style); break; default: return; } needWrap = false; }; VT100.prototype.csiK = function(number) { switch (number) { case 0: // Erase from cursor to end of line this.clearRegion(this.cursorX, this.cursorY, this.terminalWidth - this.cursorX, 1, this.color, this.style); break; case 1: // Erase from start of line to cursor this.clearRegion(0, this.cursorY, this.cursorX + 1, 1, this.color, this.style); break; case 2: // Erase whole line this.clearRegion(0, this.cursorY, this.terminalWidth, 1, this.color, this.style); break; default: return; } needWrap = false; }; VT100.prototype.csiL = function(number) { // Open line by inserting blank line(s) if (this.cursorY >= this.bottom) { return; } if (number == 0) { number = 1; } if (number > this.bottom - this.cursorY) { number = this.bottom - this.cursorY; } this.scrollRegion(0, this.cursorY, this.terminalWidth, this.bottom - this.cursorY - number, 0, number, this.color, this.style); needWrap = false; }; VT100.prototype.csiM = function(number) { // Delete line(s), scrolling up the bottom of the screen. if (this.cursorY >= this.bottom) { return; } if (number == 0) { number = 1; } if (number > this.bottom - this.cursorY) { number = bottom - cursorY; } this.scrollRegion(0, this.cursorY + number, this.terminalWidth, this.bottom - this.cursorY - number, 0, -number, this.color, this.style); needWrap = false; }; VT100.prototype.csim = function() { for (var i = 0; i <= this.npar; i++) { switch (this.par[i]) { case 0: this.attr = 0x00F0 /* ATTR_DEFAULT */; break; case 1: this.attr = (this.attr & ~0x0400 /* ATTR_DIM */)|0x0800 /* ATTR_BRIGHT */; break; case 2: this.attr = (this.attr & ~0x0800 /* ATTR_BRIGHT */)|0x0400 /* ATTR_DIM */; break; case 4: this.attr |= 0x0200 /* ATTR_UNDERLINE */; break; case 5: this.attr |= 0x1000 /* ATTR_BLINK */; break; case 7: this.attr |= 0x0100 /* ATTR_REVERSE */; break; case 10: this.translate = this.GMap[this.useGMap]; this.dispCtrl = false; this.toggleMeta = false; break; case 11: this.translate = this.CodePage437Map; this.dispCtrl = true; this.toggleMeta = false; break; case 12: this.translate = this.CodePage437Map; this.dispCtrl = true; this.toggleMeta = true; break; case 21: case 22: this.attr &= ~(0x0800 /* ATTR_BRIGHT */|0x0400 /* ATTR_DIM */); break; case 24: this.attr &= ~ 0x0200 /* ATTR_UNDERLINE */; break; case 25: this.attr &= ~ 0x1000 /* ATTR_BLINK */; break; case 27: this.attr &= ~ 0x0100 /* ATTR_REVERSE */; break; case 38: this.attr = (this.attr & ~(0x0400 /* ATTR_DIM */|0x0800 /* ATTR_BRIGHT */|0x0F))| 0x0200 /* ATTR_UNDERLINE */; break; case 39: this.attr &= ~(0x0400 /* ATTR_DIM */|0x0800 /* ATTR_BRIGHT */|0x0200 /* ATTR_UNDERLINE */|0x0F); break; case 49: this.attr |= 0xF0; break; default: if (this.par[i] >= 30 && this.par[i] <= 37) { var fg = this.par[i] - 30; this.attr = (this.attr & ~0x0F) | fg; } else if (this.par[i] >= 40 && this.par[i] <= 47) { var bg = this.par[i] - 40; this.attr = (this.attr & ~0xF0) | (bg << 4); } break; } } this.updateStyle(); }; VT100.prototype.csiP = function(number) { // Delete character(s) following cursor if (number == 0) { number = 1; } if (number > this.terminalWidth - this.cursorX) { number = this.terminalWidth - this.cursorX; } this.scrollRegion(this.cursorX + number, this.cursorY, this.terminalWidth - this.cursorX - number, 1, -number, 0, this.color, this.style); needWrap = false; }; VT100.prototype.csiX = function(number) { // Clear characters following cursor if (number == 0) { number++; } if (number > this.terminalWidth - this.cursorX) { number = this.terminalWidth - this.cursorX; } this.clearRegion(this.cursorX, this.cursorY, number, 1, this.color, this.style); needWrap = false; }; VT100.prototype.settermCommand = function() { // Setterm commands are not implemented }; VT100.prototype.doControl = function(ch) { if (this.printing) { this.sendControlToPrinter(ch); return ''; } var lineBuf = ''; switch (ch) { case 0x00: /* ignored */ break; case 0x08: this.bs(); break; case 0x09: this.ht(); break; case 0x0A: case 0x0B: case 0x0C: case 0x84: this.lf(); if (!this.crLfMode) break; case 0x0D: this.cr(); break; case 0x85: this.cr(); this.lf(); break; case 0x0E: this.useGMap = 1; this.translate = this.GMap[1]; this.dispCtrl = true; break; case 0x0F: this.useGMap = 0; this.translate = this.GMap[0]; this.dispCtrl = false; break; case 0x18: case 0x1A: this.isEsc = 0 /* ESnormal */; break; case 0x1B: this.isEsc = 1 /* ESesc */; break; case 0x7F: /* ignored */ break; case 0x88: this.userTabStop[this.cursorX] = true; break; case 0x8D: this.ri(); break; case 0x8E: this.isEsc = 18 /* ESss2 */; break; case 0x8F: this.isEsc = 19 /* ESss3 */; break; case 0x9A: this.respondID(); break; case 0x9B: this.isEsc = 2 /* ESsquare */; break; case 0x07: if (this.isEsc != 17 /* EStitle */) { this.beep(); break; } /* fall thru */ default: switch (this.isEsc) { case 1 /* ESesc */: this.isEsc = 0 /* ESnormal */; switch (ch) { /*%*/ case 0x25: this.isEsc = 13 /* ESpercent */; break; /*(*/ case 0x28: this.isEsc = 8 /* ESsetG0 */; break; /*-*/ case 0x2D: /*)*/ case 0x29: this.isEsc = 9 /* ESsetG1 */; break; /*.*/ case 0x2E: /***/ case 0x2A: this.isEsc = 10 /* ESsetG2 */; break; /*/*/ case 0x2F: /*+*/ case 0x2B: this.isEsc = 11 /* ESsetG3 */; break; /*#*/ case 0x23: this.isEsc = 7 /* EShash */; break; /*7*/ case 0x37: this.saveCursor(); break; /*8*/ case 0x38: this.restoreCursor(); break; /*>*/ case 0x3E: this.applKeyMode = false; break; /*=*/ case 0x3D: this.applKeyMode = true; break; /*D*/ case 0x44: this.lf(); break; /*E*/ case 0x45: this.cr(); this.lf(); break; /*M*/ case 0x4D: this.ri(); break; /*N*/ case 0x4E: this.isEsc = 18 /* ESss2 */; break; /*O*/ case 0x4F: this.isEsc = 19 /* ESss3 */; break; /*H*/ case 0x48: this.userTabStop[this.cursorX] = true; break; /*Z*/ case 0x5A: this.respondID(); break; /*[*/ case 0x5B: this.isEsc = 2 /* ESsquare */; break; /*]*/ case 0x5D: this.isEsc = 15 /* ESnonstd */; break; /*c*/ case 0x63: this.reset(); break; /*g*/ case 0x67: this.flashScreen(); break; default: break; } break; case 15 /* ESnonstd */: switch (ch) { /*0*/ case 0x30: /*1*/ case 0x31: /*2*/ case 0x32: this.isEsc = 17 /* EStitle */; this.titleString = ''; break; /*P*/ case 0x50: this.npar = 0; this.par = [ 0, 0, 0, 0, 0, 0, 0 ]; this.isEsc = 16 /* ESpalette */; break; /*R*/ case 0x52: // Palette support is not implemented this.isEsc = 0 /* ESnormal */; break; default: this.isEsc = 0 /* ESnormal */; break; } break; case 16 /* ESpalette */: if ((ch >= 0x30 /*0*/ && ch <= 0x39 /*9*/) || (ch >= 0x41 /*A*/ && ch <= 0x46 /*F*/) || (ch >= 0x61 /*a*/ && ch <= 0x66 /*f*/)) { this.par[this.npar++] = ch > 0x39 /*9*/ ? (ch & 0xDF) - 55 : (ch & 0xF); if (this.npar == 7) { // Palette support is not implemented this.isEsc = 0 /* ESnormal */; } } else { this.isEsc = 0 /* ESnormal */; } break; case 2 /* ESsquare */: this.npar = 0; this.par = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; this.isEsc = 3 /* ESgetpars */; /*[*/ if (ch == 0x5B) { // Function key this.isEsc = 6 /* ESfunckey */; break; } else { /*?*/ this.isQuestionMark = ch == 0x3F; if (this.isQuestionMark) { break; } } // Fall through case 5 /* ESdeviceattr */: case 3 /* ESgetpars */: /*;*/ if (ch == 0x3B) { this.npar++; break; } else if (ch >= 0x30 /*0*/ && ch <= 0x39 /*9*/) { var par = this.par[this.npar]; if (par == undefined) { par = 0; } this.par[this.npar] = 10*par + (ch & 0xF); break; } else if (this.isEsc == 5 /* ESdeviceattr */) { switch (ch) { /*c*/ case 0x63: if (this.par[0] == 0) this.respondSecondaryDA(); break; /*m*/ case 0x6D: /* (re)set key modifier resource values */ break; /*n*/ case 0x6E: /* disable key modifier resource values */ break; /*p*/ case 0x70: /* set pointer mode resource value */ break; default: break; } this.isEsc = 0 /* ESnormal */; break; } else { this.isEsc = 4 /* ESgotpars */; } // Fall through case 4 /* ESgotpars */: this.isEsc = 0 /* ESnormal */; if (this.isQuestionMark) { switch (ch) { /*h*/ case 0x68: this.setMode(true); break; /*l*/ case 0x6C: this.setMode(false); break; /*c*/ case 0x63: this.setCursorAttr(this.par[2], this.par[1]); break; default: break; } this.isQuestionMark = false; break; } switch (ch) { /*!*/ case 0x21: this.isEsc = 12 /* ESbang */; break; /*>*/ case 0x3E: if (!this.npar) this.isEsc = 5 /* ESdeviceattr */; break; /*G*/ case 0x47: /*`*/ case 0x60: this.gotoXY(this.par[0] - 1, this.cursorY); break; /*A*/ case 0x41: this.gotoXY(this.cursorX, this.cursorY - (this.par[0] ? this.par[0] : 1)); break; /*B*/ case 0x42: /*e*/ case 0x65: this.gotoXY(this.cursorX, this.cursorY + (this.par[0] ? this.par[0] : 1)); break; /*C*/ case 0x43: /*a*/ case 0x61: this.gotoXY(this.cursorX + (this.par[0] ? this.par[0] : 1), this.cursorY); break; /*D*/ case 0x44: this.gotoXY(this.cursorX - (this.par[0] ? this.par[0] : 1), this.cursorY); break; /*E*/ case 0x45: this.gotoXY(0, this.cursorY + (this.par[0] ? this.par[0] :1)); break; /*F*/ case 0x46: this.gotoXY(0, this.cursorY - (this.par[0] ? this.par[0] :1)); break; /*d*/ case 0x64: this.gotoXaY(this.cursorX, this.par[0] - 1); break; /*H*/ case 0x48: /*f*/ case 0x66: this.gotoXaY(this.par[1] - 1, this.par[0] - 1); break; /*I*/ case 0x49: this.ht(this.par[0] ? this.par[0] : 1); break; /*@*/ case 0x40: this.csiAt(this.par[0]); break; /*i*/ case 0x69: this.csii(this.par[0]); break; /*J*/ case 0x4A: this.csiJ(this.par[0]); break; /*K*/ case 0x4B: this.csiK(this.par[0]); break; /*L*/ case 0x4C: this.csiL(this.par[0]); break; /*M*/ case 0x4D: this.csiM(this.par[0]); break; /*m*/ case 0x6D: this.csim(); break; /*P*/ case 0x50: this.csiP(this.par[0]); break; /*X*/ case 0x58: this.csiX(this.par[0]); break; /*S*/ case 0x53: this.lf(this.par[0] ? this.par[0] : 1); break; /*T*/ case 0x54: this.ri(this.par[0] ? this.par[0] : 1); break; /*c*/ case 0x63: if (!this.par[0]) this.respondID(); break; /*g*/ case 0x67: if (this.par[0] == 0) { this.userTabStop[this.cursorX] = false; } else if (this.par[0] == 2 || this.par[0] == 3) { this.userTabStop = [ ]; for (var i = 0; i < this.terminalWidth; i++) { this.userTabStop[i] = false; } } break; /*h*/ case 0x68: this.setMode(true); break; /*l*/ case 0x6C: this.setMode(false); break; /*n*/ case 0x6E: switch (this.par[0]) { case 5: this.statusReport(); break; case 6: this.cursorReport(); break; default: break; } break; /*q*/ case 0x71: // LED control not implemented break; /*r*/ case 0x72: var t = this.par[0] ? this.par[0] : 1; var b = this.par[1] ? this.par[1] : this.terminalHeight; if (t < b && b <= this.terminalHeight) { this.top = t - 1; this.bottom= b; this.gotoXaY(0, 0); } break; /*b*/ case 0x62: var c = this.par[0] ? this.par[0] : 1; if (c > this.terminalWidth * this.terminalHeight) { c = this.terminalWidth * this.terminalHeight; } while (c-- > 0) { lineBuf += this.lastCharacter; } break; /*s*/ case 0x73: this.saveCursor(); break; /*u*/ case 0x75: this.restoreCursor(); break; /*Z*/ case 0x5A: this.rt(this.par[0] ? this.par[0] : 1); break; /*]*/ case 0x5D: this.settermCommand(); break; default: break; } break; case 12 /* ESbang */: if (ch == 'p') { this.reset(); } this.isEsc = 0 /* ESnormal */; break; case 13 /* ESpercent */: this.isEsc = 0 /* ESnormal */; switch (ch) { /*@*/ case 0x40: this.utfEnabled = false; break; /*G*/ case 0x47: /*8*/ case 0x38: this.utfEnabled = true; break; default: break; } break; case 6 /* ESfunckey */: this.isEsc = 0 /* ESnormal */; break; case 7 /* EShash */: this.isEsc = 0 /* ESnormal */; /*8*/ if (ch == 0x38) { // Screen alignment test not implemented } break; case 8 /* ESsetG0 */: case 9 /* ESsetG1 */: case 10 /* ESsetG2 */: case 11 /* ESsetG3 */: var g = this.isEsc - 8 /* ESsetG0 */; this.isEsc = 0 /* ESnormal */; switch (ch) { /*0*/ case 0x30: this.GMap[g] = this.VT100GraphicsMap; break; /*A*/ case 0x42: /*B*/ case 0x42: this.GMap[g] = this.Latin1Map; break; /*U*/ case 0x55: this.GMap[g] = this.CodePage437Map; break; /*K*/ case 0x4B: this.GMap[g] = this.DirectToFontMap; break; default: break; } if (this.useGMap == g) { this.translate = this.GMap[g]; } break; case 17 /* EStitle */: if (ch == 0x07) { if (this.titleString && this.titleString.charAt(0) == ';') { this.titleString = this.titleString.substr(1); if (this.titleString != '') { this.titleString += ' - '; } this.titleString += 'Shell In A Box' } try { window.document.title = this.titleString; } catch (e) { } this.isEsc = 0 /* ESnormal */; } else { this.titleString += String.fromCharCode(ch); } break; case 18 /* ESss2 */: case 19 /* ESss3 */: if (ch < 256) { ch = this.GMap[this.isEsc - 18 /* ESss2 */ + 2] [this.toggleMeta ? (ch | 0x80) : ch]; if ((ch & 0xFF00) == 0xF000) { ch = ch & 0xFF; } else if (ch == 0xFEFF || (ch >= 0x200A && ch <= 0x200F)) { this.isEsc = 0 /* ESnormal */; break; } } this.lastCharacter = String.fromCharCode(ch); lineBuf += this.lastCharacter; this.isEsc = 0 /* ESnormal */; break; default: this.isEsc = 0 /* ESnormal */; break; } break; } return lineBuf; }; VT100.prototype.renderString = function(s, showCursor) { if (this.printing) { this.sendToPrinter(s); if (showCursor) { this.showCursor(); } return; } // We try to minimize the number of DOM operations by coalescing individual // characters into strings. This is a significant performance improvement. var incX = s.length; if (incX > this.terminalWidth - this.cursorX) { incX = this.terminalWidth - this.cursorX; if (incX <= 0) { return; } s = s.substr(0, incX - 1) + s.charAt(s.length - 1); } if (showCursor) { // Minimize the number of calls to putString(), by avoiding a direct // call to this.showCursor() this.cursor.style.visibility = ''; } this.putString(this.cursorX, this.cursorY, s, this.color, this.style); }; VT100.prototype.vt100 = function(s) { this.cursorNeedsShowing = this.hideCursor(); this.respondString = ''; var lineBuf = ''; for (var i = 0; i < s.length; i++) { var ch = s.charCodeAt(i); if (this.utfEnabled) { // Decode UTF8 encoded character if (ch > 0x7F) { if (this.utfCount > 0 && (ch & 0xC0) == 0x80) { this.utfChar = (this.utfChar << 6) | (ch & 0x3F); if (--this.utfCount <= 0) { if (this.utfChar > 0xFFFF || this.utfChar < 0) { ch = 0xFFFD; } else { ch = this.utfChar; } } else { continue; } } else { if ((ch & 0xE0) == 0xC0) { this.utfCount = 1; this.utfChar = ch & 0x1F; } else if ((ch & 0xF0) == 0xE0) { this.utfCount = 2; this.utfChar = ch & 0x0F; } else if ((ch & 0xF8) == 0xF0) { this.utfCount = 3; this.utfChar = ch & 0x07; } else if ((ch & 0xFC) == 0xF8) { this.utfCount = 4; this.utfChar = ch & 0x03; } else if ((ch & 0xFE) == 0xFC) { this.utfCount = 5; this.utfChar = ch & 0x01; } else { this.utfCount = 0; } continue; } } else { this.utfCount = 0; } } var isNormalCharacter = (ch >= 32 && ch <= 127 || ch >= 160 || this.utfEnabled && ch >= 128 || !(this.dispCtrl ? this.ctrlAlways : this.ctrlAction)[ch & 0x1F]) && (ch != 0x7F || this.dispCtrl); if (isNormalCharacter && this.isEsc == 0 /* ESnormal */) { if (ch < 256) { ch = this.translate[this.toggleMeta ? (ch | 0x80) : ch]; } if ((ch & 0xFF00) == 0xF000) { ch = ch & 0xFF; } else if (ch == 0xFEFF || (ch >= 0x200A && ch <= 0x200F)) { continue; } if (!this.printing) { if (this.needWrap || this.insertMode) { if (lineBuf) { this.renderString(lineBuf); lineBuf = ''; } } if (this.needWrap) { this.cr(); this.lf(); } if (this.insertMode) { this.scrollRegion(this.cursorX, this.cursorY, this.terminalWidth - this.cursorX - 1, 1, 1, 0, this.color, this.style); } } this.lastCharacter = String.fromCharCode(ch); lineBuf += this.lastCharacter; if (!this.printing && this.cursorX + lineBuf.length >= this.terminalWidth) { this.needWrap = this.autoWrapMode; } } else { if (lineBuf) { this.renderString(lineBuf); lineBuf = ''; } var expand = this.doControl(ch); if (expand.length) { var r = this.respondString; this.respondString= r + this.vt100(expand); } } } if (lineBuf) { this.renderString(lineBuf, this.cursorNeedsShowing); } else if (this.cursorNeedsShowing) { this.showCursor(); } return this.respondString; }; VT100.prototype.Latin1Map = [ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x007F, 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x008D, 0x008E, 0x008F, 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E, 0x009F, 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF ]; VT100.prototype.VT100GraphicsMap = [ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x2192, 0x2190, 0x2191, 0x2193, 0x002F, 0x2588, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x00A0, 0x25C6, 0x2592, 0x2409, 0x240C, 0x240D, 0x240A, 0x00B0, 0x00B1, 0x2591, 0x240B, 0x2518, 0x2510, 0x250C, 0x2514, 0x253C, 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251C, 0x2524, 0x2534, 0x252C, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00B7, 0x007F, 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x008D, 0x008E, 0x008F, 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E, 0x009F, 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF ]; VT100.prototype.CodePage437Map = [ 0x0000, 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, 0x25B6, 0x25C0, 0x2195, 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x2302, 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 ]; VT100.prototype.DirectToFontMap = [ 0xF000, 0xF001, 0xF002, 0xF003, 0xF004, 0xF005, 0xF006, 0xF007, 0xF008, 0xF009, 0xF00A, 0xF00B, 0xF00C, 0xF00D, 0xF00E, 0xF00F, 0xF010, 0xF011, 0xF012, 0xF013, 0xF014, 0xF015, 0xF016, 0xF017, 0xF018, 0xF019, 0xF01A, 0xF01B, 0xF01C, 0xF01D, 0xF01E, 0xF01F, 0xF020, 0xF021, 0xF022, 0xF023, 0xF024, 0xF025, 0xF026, 0xF027, 0xF028, 0xF029, 0xF02A, 0xF02B, 0xF02C, 0xF02D, 0xF02E, 0xF02F, 0xF030, 0xF031, 0xF032, 0xF033, 0xF034, 0xF035, 0xF036, 0xF037, 0xF038, 0xF039, 0xF03A, 0xF03B, 0xF03C, 0xF03D, 0xF03E, 0xF03F, 0xF040, 0xF041, 0xF042, 0xF043, 0xF044, 0xF045, 0xF046, 0xF047, 0xF048, 0xF049, 0xF04A, 0xF04B, 0xF04C, 0xF04D, 0xF04E, 0xF04F, 0xF050, 0xF051, 0xF052, 0xF053, 0xF054, 0xF055, 0xF056, 0xF057, 0xF058, 0xF059, 0xF05A, 0xF05B, 0xF05C, 0xF05D, 0xF05E, 0xF05F, 0xF060, 0xF061, 0xF062, 0xF063, 0xF064, 0xF065, 0xF066, 0xF067, 0xF068, 0xF069, 0xF06A, 0xF06B, 0xF06C, 0xF06D, 0xF06E, 0xF06F, 0xF070, 0xF071, 0xF072, 0xF073, 0xF074, 0xF075, 0xF076, 0xF077, 0xF078, 0xF079, 0xF07A, 0xF07B, 0xF07C, 0xF07D, 0xF07E, 0xF07F, 0xF080, 0xF081, 0xF082, 0xF083, 0xF084, 0xF085, 0xF086, 0xF087, 0xF088, 0xF089, 0xF08A, 0xF08B, 0xF08C, 0xF08D, 0xF08E, 0xF08F, 0xF090, 0xF091, 0xF092, 0xF093, 0xF094, 0xF095, 0xF096, 0xF097, 0xF098, 0xF099, 0xF09A, 0xF09B, 0xF09C, 0xF09D, 0xF09E, 0xF09F, 0xF0A0, 0xF0A1, 0xF0A2, 0xF0A3, 0xF0A4, 0xF0A5, 0xF0A6, 0xF0A7, 0xF0A8, 0xF0A9, 0xF0AA, 0xF0AB, 0xF0AC, 0xF0AD, 0xF0AE, 0xF0AF, 0xF0B0, 0xF0B1, 0xF0B2, 0xF0B3, 0xF0B4, 0xF0B5, 0xF0B6, 0xF0B7, 0xF0B8, 0xF0B9, 0xF0BA, 0xF0BB, 0xF0BC, 0xF0BD, 0xF0BE, 0xF0BF, 0xF0C0, 0xF0C1, 0xF0C2, 0xF0C3, 0xF0C4, 0xF0C5, 0xF0C6, 0xF0C7, 0xF0C8, 0xF0C9, 0xF0CA, 0xF0CB, 0xF0CC, 0xF0CD, 0xF0CE, 0xF0CF, 0xF0D0, 0xF0D1, 0xF0D2, 0xF0D3, 0xF0D4, 0xF0D5, 0xF0D6, 0xF0D7, 0xF0D8, 0xF0D9, 0xF0DA, 0xF0DB, 0xF0DC, 0xF0DD, 0xF0DE, 0xF0DF, 0xF0E0, 0xF0E1, 0xF0E2, 0xF0E3, 0xF0E4, 0xF0E5, 0xF0E6, 0xF0E7, 0xF0E8, 0xF0E9, 0xF0EA, 0xF0EB, 0xF0EC, 0xF0ED, 0xF0EE, 0xF0EF, 0xF0F0, 0xF0F1, 0xF0F2, 0xF0F3, 0xF0F4, 0xF0F5, 0xF0F6, 0xF0F7, 0xF0F8, 0xF0F9, 0xF0FA, 0xF0FB, 0xF0FC, 0xF0FD, 0xF0FE, 0xF0FF ]; VT100.prototype.ctrlAction = [ true, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, true, false, true, true, false, false, false, false ]; VT100.prototype.ctrlAlways = [ true, false, false, false, false, false, false, false, true, false, true, false, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false ];
JavaScript
// ShellInABox.js -- Use XMLHttpRequest to provide an AJAX terminal emulator. // Copyright (C) 2008-2010 Markus Gutschke <markus@shellinabox.com> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // In addition to these license terms, the author grants the following // additional rights: // // If you modify this program, or any covered work, by linking or // combining it with the OpenSSL project's OpenSSL library (or a // modified version of that library), containing parts covered by the // terms of the OpenSSL or SSLeay licenses, the author // grants you additional permission to convey the resulting work. // Corresponding Source for a non-source form of such a combination // shall include the source code for the parts of OpenSSL used as well // as that of the covered work. // // You may at your option choose to remove this additional permission from // the work, or from any part of it. // // It is possible to build this program in a way that it loads OpenSSL // libraries at run-time. If doing so, the following notices are required // by the OpenSSL and SSLeay licenses: // // This product includes software developed by the OpenSSL Project // for use in the OpenSSL Toolkit. (http://www.openssl.org/) // // This product includes cryptographic software written by Eric Young // (eay@cryptsoft.com) // // // The most up-to-date version of this program is always available from // http://shellinabox.com // // // Notes: // // The author believes that for the purposes of this license, you meet the // requirements for publishing the source code, if your web server publishes // the source in unmodified form (i.e. with licensing information, comments, // formatting, and identifier names intact). If there are technical reasons // that require you to make changes to the source code when serving the // JavaScript (e.g to remove pre-processor directives from the source), these // changes should be done in a reversible fashion. // // The author does not consider websites that reference this script in // unmodified form, and web servers that serve this script in unmodified form // to be derived works. As such, they are believed to be outside of the // scope of this license and not subject to the rights or restrictions of the // GNU General Public License. // // If in doubt, consult a legal professional familiar with the laws that // apply in your country. // #define XHR_UNITIALIZED 0 // #define XHR_OPEN 1 // #define XHR_SENT 2 // #define XHR_RECEIVING 3 // #define XHR_LOADED 4 // IE does not define XMLHttpRequest by default, so we provide a suitable // wrapper. if (typeof XMLHttpRequest == 'undefined') { XMLHttpRequest = function() { try { return new ActiveXObject('Msxml2.XMLHTTP.6.0');} catch (e) { } try { return new ActiveXObject('Msxml2.XMLHTTP.3.0');} catch (e) { } try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { } try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { } throw new Error(''); }; } function extend(subClass, baseClass) { function inheritance() { } inheritance.prototype = baseClass.prototype; subClass.prototype = new inheritance(); subClass.prototype.constructor = subClass; subClass.prototype.superClass = baseClass.prototype; }; function ShellInABox(url, container) { if (url == undefined) { this.rooturl = document.location.href; this.url = document.location.href.replace(/[?#].*/, ''); } else { this.rooturl = url; this.url = url; } if (document.location.hash != '') { var hash = decodeURIComponent(document.location.hash). replace(/^#/, ''); this.nextUrl = hash.replace(/,.*/, ''); this.session = hash.replace(/[^,]*,/, ''); } else { this.nextUrl = this.url; this.session = null; } this.pendingKeys = ''; this.keysInFlight = false; this.connected = false; this.superClass.constructor.call(this, container); // We have to initiate the first XMLHttpRequest from a timer. Otherwise, // Chrome never realizes that the page has loaded. setTimeout(function(shellInABox) { return function() { shellInABox.sendRequest(); }; }(this), 1); }; extend(ShellInABox, VT100); ShellInABox.prototype.sessionClosed = function() { try { this.connected = false; if (this.session) { this.session = undefined; if (this.cursorX > 0) { this.vt100('\r\n'); } this.vt100('Session closed.'); } this.showReconnect(true); } catch (e) { } }; ShellInABox.prototype.reconnect = function() { this.showReconnect(false); if (!this.session) { if (document.location.hash != '') { // A shellinaboxd daemon launched from a CGI only allows a single // session. In order to reconnect, we must reload the frame definition // and obtain a new port number. As this is a different origin, we // need to get enclosing page to help us. parent.location = this.nextUrl; } else { if (this.url != this.nextUrl) { document.location.replace(this.nextUrl); } else { this.pendingKeys = ''; this.keysInFlight = false; this.reset(true); this.sendRequest(); } } } return false; }; ShellInABox.prototype.sendRequest = function(request) { if (request == undefined) { request = new XMLHttpRequest(); } request.open('POST', this.url + '?', true); request.setRequestHeader('Cache-Control', 'no-cache'); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8'); var content = 'width=' + this.terminalWidth + '&height=' + this.terminalHeight + (this.session ? '&session=' + encodeURIComponent(this.session) : '&rooturl='+ encodeURIComponent(this.rooturl)); request.setRequestHeader('Content-Length', content.length); request.onreadystatechange = function(shellInABox) { return function() { try { return shellInABox.onReadyStateChange(request); } catch (e) { shellInABox.sessionClosed(); } } }(this); request.send(content); }; ShellInABox.prototype.onReadyStateChange = function(request) { if (request.readyState == 4 /* XHR_LOADED */) { if (request.status == 200) { this.connected = true; var response = eval('(' + request.responseText + ')'); if (response.data) { this.vt100(response.data); } if (!response.session || this.session && this.session != response.session) { this.sessionClosed(); } else { this.session = response.session; this.sendRequest(request); } } else if (request.status == 0) { // Time Out this.sendRequest(request); } else { this.sessionClosed(); } } }; ShellInABox.prototype.sendKeys = function(keys) { if (!this.connected) { return; } if (this.keysInFlight || this.session == undefined) { this.pendingKeys += keys; } else { this.keysInFlight = true; keys = this.pendingKeys + keys; this.pendingKeys = ''; var request = new XMLHttpRequest(); request.open('POST', this.url + '?', true); request.setRequestHeader('Cache-Control', 'no-cache'); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8'); var content = 'width=' + this.terminalWidth + '&height=' + this.terminalHeight + '&session=' +encodeURIComponent(this.session)+ '&keys=' + encodeURIComponent(keys); request.setRequestHeader('Content-Length', content.length); request.onreadystatechange = function(shellInABox) { return function() { try { return shellInABox.keyPressReadyStateChange(request); } catch (e) { } } }(this); request.send(content); } }; ShellInABox.prototype.keyPressReadyStateChange = function(request) { if (request.readyState == 4 /* XHR_LOADED */) { this.keysInFlight = false; if (this.pendingKeys) { this.sendKeys(''); } } }; ShellInABox.prototype.keysPressed = function(ch) { var hex = '0123456789ABCDEF'; var s = ''; for (var i = 0; i < ch.length; i++) { var c = ch.charCodeAt(i); if (c < 128) { s += hex.charAt(c >> 4) + hex.charAt(c & 0xF); } else if (c < 0x800) { s += hex.charAt(0xC + (c >> 10) ) + hex.charAt( (c >> 6) & 0xF ) + hex.charAt(0x8 + ((c >> 4) & 0x3)) + hex.charAt( c & 0xF ); } else if (c < 0x10000) { s += 'E' + hex.charAt( (c >> 12) ) + hex.charAt(0x8 + ((c >> 10) & 0x3)) + hex.charAt( (c >> 6) & 0xF ) + hex.charAt(0x8 + ((c >> 4) & 0x3)) + hex.charAt( c & 0xF ); } else if (c < 0x110000) { s += 'F' + hex.charAt( (c >> 18) ) + hex.charAt(0x8 + ((c >> 16) & 0x3)) + hex.charAt( (c >> 12) & 0xF ) + hex.charAt(0x8 + ((c >> 10) & 0x3)) + hex.charAt( (c >> 6) & 0xF ) + hex.charAt(0x8 + ((c >> 4) & 0x3)) + hex.charAt( c & 0xF ); } } this.sendKeys(s); }; ShellInABox.prototype.resized = function(w, h) { // Do not send a resize request until we are fully initialized. if (this.session) { // sendKeys() always transmits the current terminal size. So, flush all // pending keys. this.sendKeys(''); } }; ShellInABox.prototype.toggleSSL = function() { if (document.location.hash != '') { if (this.nextUrl.match(/\?plain$/)) { this.nextUrl = this.nextUrl.replace(/\?plain$/, ''); } else { this.nextUrl = this.nextUrl.replace(/[?#].*/, '') + '?plain'; } if (!this.session) { parent.location = this.nextUrl; } } else { this.nextUrl = this.nextUrl.match(/^https:/) ? this.nextUrl.replace(/^https:/, 'http:').replace(/\/*$/, '/plain') : this.nextUrl.replace(/^http/, 'https').replace(/\/*plain$/, ''); } if (this.nextUrl.match(/^[:]*:\/\/[^/]*$/)) { this.nextUrl += '/'; } if (this.session && this.nextUrl != this.url) { alert('This change will take effect the next time you login.'); } }; ShellInABox.prototype.extendContextMenu = function(entries, actions) { // Modify the entries and actions in place, adding any locally defined // menu entries. var oldActions = [ ]; for (var i = 0; i < actions.length; i++) { oldActions[i] = actions[i]; } for (var node = entries.firstChild, i = 0, j = 0; node; node = node.nextSibling) { if (node.tagName == 'LI') { actions[i++] = oldActions[j++]; if (node.id == "endconfig") { node.id = ''; if (typeof serverSupportsSSL != 'undefined' && serverSupportsSSL && !(typeof disableSSLMenu != 'undefined' && disableSSLMenu)) { // If the server supports both SSL and plain text connections, // provide a menu entry to switch between the two. var newNode = document.createElement('li'); var isSecure; if (document.location.hash != '') { isSecure = !this.nextUrl.match(/\?plain$/); } else { isSecure = this.nextUrl.match(/^https:/); } newNode.innerHTML = (isSecure ? '&#10004; ' : '') + 'Secure'; if (node.nextSibling) { entries.insertBefore(newNode, node.nextSibling); } else { entries.appendChild(newNode); } actions[i++] = this.toggleSSL; node = newNode; } node.id = 'endconfig'; } } } }; ShellInABox.prototype.about = function() { alert("Shell In A Box version " + "2.10 (revision 239)" + "\nCopyright 2008-2010 by Markus Gutschke\n" + "For more information check http://shellinabox.com" + (typeof serverSupportsSSL != 'undefined' && serverSupportsSSL ? "\n\n" + "This product includes software developed by the OpenSSL Project\n" + "for use in the OpenSSL Toolkit. (http://www.openssl.org/)\n" + "\n" + "This product includes cryptographic software written by " + "Eric Young\n(eay@cryptsoft.com)" : "")); };
JavaScript
jQuery(document).ready(function(){ // Country event jQuery('#User_country_id').bind('change', function(){ $('User_country_id').getForm().sendPhpr( 'onUpdateStatesList', { loadIndicator: {show: false} } ) }); });
JavaScript
var url_modified = false; jQuery(document).ready(function($){ var page_title_field = $('#Cms_Page_name'); if (page_title_field.length > 0 && $('#new_flag').length > 0) { page_title_field.bind('keyup', function() { update_url_title(page_title_field) }); page_title_field.bind('change', function() { update_url_title(page_title_field) }); page_title_field.bind('paste', function() { update_url_title(page_title_field) }); } if ($('#new_flag').length > 0) { var url_element = $('#Cms_Page_url'); url_element.bind('change', function(){ url_modified = true; }); } function update_url_title(field_element) { if (!url_modified) { $('#Cms_Page_url').val('/' + convert_text_to_url(field_element.val())); $('#Cms_Page_url').trigger('modified'); } } });
JavaScript
function menus_selected() { return $('listCms_Menus_index_list_body').getElements('tr td.checkbox input').some(function(element){return element.checked}); } function delete_selected() { if (!menus_selected()) { alert('Please select layouts to delete.'); return false; } $('listCms_Menus_index_list_body').getForm().sendPhpr( 'index_onDeleteSelected', { confirm: 'Do you really want to delete selected menu(s)?', loadIndicator: {show: false}, onBeforePost: LightLoadingIndicator.show.pass('Loading...'), onComplete: LightLoadingIndicator.hide, onAfterUpdate: update_scrollable_toolbars, update: 'templates_page_content' } ); return false; } jQuery(document).ready(function() { make_items_sortable(); }); function updateItemList() { cancelPopup(); $('item_list').getForm().sendPhpr( 'onUpdateItemList', { update: 'item_list', loadIndicator: { show: true, element: 'item_list', hideOnSuccess: true, injectInElement: true, src: 'phproad/resources/images/form_load_30x30.gif' }, onSuccess: make_items_sortable } ) } function make_items_sortable(session_key) { if (!$('item_list')) return; jQuery($('item_list')).css('visibility', 'visible'); var list = jQuery($('item_list')).find('ol.nestedsortable'); list.nestedSortable({ disableNesting: 'no-nest', forcePlaceholderSize: true, handle: 'div', helper: 'clone', items: 'li', opacity: .6, placeholder: 'placeholder', revert: 250, tabSize: 25, tolerance: 'pointer', toleranceElement: '> div', update: function(event, ui) { list.find('li').removeClass('even').filter(':odd').addClass('even'); // Get the new sort order var sorted_item_ids = list.find('li').map(function() { return jQuery(this).attr('item_id').match(/(?:.+)[-=_](.+)/); }).get().join(','); $('item_list').getForm().sendPhpr('onSetItemOrders', { loadIndicator: {show: false}, onBeforePost: LightLoadingIndicator.show.pass('Loading...'), onComplete: LightLoadingIndicator.hide, extraFields: { sort_order: sorted_item_ids, nesting_order: list.nestedSortable('serialize', {'attribute':'item_id'}) } }); } }); } function delete_item(item_id) { return $('item_list').getForm().sendPhpr('onDeleteItem', { confirm: 'Do you really want to delete this menu item? Any child items will be kept.', onFailure: popupAjaxError, update: 'item_list', extraFields: { item_id: item_id }, loadIndicator: { show: true, element: 'item_list', hideOnSuccess: true, injectInElement: true, src: 'phproad/resources/images/form_load_30x30.gif' } }); } /* * jQuery UI Nested Sortable * v 1.3.4 / 28 apr 2011 * http://mjsarfatti.com/sandbox/nestedSortable * * Depends: * jquery.ui.sortable.js 1.8+ * * License CC BY-SA 3.0 * Copyright 2010-2011, Manuele J Sarfatti */ (function(a){a.widget("ui.nestedSortable",a.extend({},a.ui.sortable.prototype,{options:{tabSize:20,disableNesting:"ui-nestedSortable-no-nesting",errorClass:"ui-nestedSortable-error",listType:"ol",maxLevels:0,revertOnError:1},_create:function(){this.element.data("sortable",this.element.data("nestedSortable"));return a.ui.sortable.prototype._create.apply(this,arguments)},destroy:function(){this.element.removeData("nestedSortable").unbind(".nestedSortable");return a.ui.sortable.prototype.destroy.apply(this,arguments)},_mouseDrag:function(d){this.position=this._generatePosition(d);this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs){this.lastPositionAbs=this.positionAbs}if(this.options.scroll){var f=this.options,e=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if((this.overflowOffset.top+this.scrollParent[0].offsetHeight)-d.pageY<f.scrollSensitivity){this.scrollParent[0].scrollTop=e=this.scrollParent[0].scrollTop+f.scrollSpeed}else{if(d.pageY-this.overflowOffset.top<f.scrollSensitivity){this.scrollParent[0].scrollTop=e=this.scrollParent[0].scrollTop-f.scrollSpeed}}if((this.overflowOffset.left+this.scrollParent[0].offsetWidth)-d.pageX<f.scrollSensitivity){this.scrollParent[0].scrollLeft=e=this.scrollParent[0].scrollLeft+f.scrollSpeed}else{if(d.pageX-this.overflowOffset.left<f.scrollSensitivity){this.scrollParent[0].scrollLeft=e=this.scrollParent[0].scrollLeft-f.scrollSpeed}}}else{if(d.pageY-a(document).scrollTop()<f.scrollSensitivity){e=a(document).scrollTop(a(document).scrollTop()-f.scrollSpeed)}else{if(a(window).height()-(d.pageY-a(document).scrollTop())<f.scrollSensitivity){e=a(document).scrollTop(a(document).scrollTop()+f.scrollSpeed)}}if(d.pageX-a(document).scrollLeft()<f.scrollSensitivity){e=a(document).scrollLeft(a(document).scrollLeft()-f.scrollSpeed)}else{if(a(window).width()-(d.pageX-a(document).scrollLeft())<f.scrollSensitivity){e=a(document).scrollLeft(a(document).scrollLeft()+f.scrollSpeed)}}}if(e!==false&&a.ui.ddmanager&&!f.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,d)}}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}for(var l=this.items.length-1;l>=0;l--){var m=this.items[l],g=m.item[0],c=this._intersectsWithPointer(m);if(!c){continue}if(g!=this.currentItem[0]&&this.placeholder[c==1?"next":"prev"]()[0]!=g&&!a.contains(this.placeholder[0],g)&&(this.options.type=="semi-dynamic"?!a.contains(this.element[0],g):true)){a(g).mouseenter();this.direction=c==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(m)){a(g).mouseleave();this._rearrange(d,m)}else{break}this._clearEmpty(g);this._trigger("change",d,this._uiHash());break}}var h=(this.placeholder[0].parentNode.parentNode&&a(this.placeholder[0].parentNode.parentNode).closest(".ui-sortable").length)?a(this.placeholder[0].parentNode.parentNode):null,b=this._getLevel(this.placeholder),j=this._getChildLevels(this.helper),k=this.placeholder[0].previousSibling?a(this.placeholder[0].previousSibling):null;if(k!=null){while(k[0].nodeName.toLowerCase()!="li"||k[0]==this.currentItem[0]){if(k[0].previousSibling){k=a(k[0].previousSibling)}else{k=null;break}}}newList=document.createElement(f.listType);this.beyondMaxLevels=0;if(h!=null&&this.positionAbs.left<h.offset().left){h.after(this.placeholder[0]);this._clearEmpty(h[0]);this._trigger("change",d,this._uiHash())}else{if(k!=null&&this.positionAbs.left>k.offset().left+f.tabSize){this._isAllowed(k,b+j+1);if(!k.children(f.listType).length){k[0].appendChild(newList)}k.children(f.listType)[0].appendChild(this.placeholder[0]);this._trigger("change",d,this._uiHash())}else{this._isAllowed(h,b+j)}}this._contactContainers(d);if(a.ui.ddmanager){a.ui.ddmanager.drag(this,d)}this._trigger("sort",d,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(e,f){if(this.beyondMaxLevels){this.placeholder.removeClass(this.options.errorClass);if(this.options.revertOnError){if(this.domPosition.prev){a(this.domPosition.prev).after(this.placeholder)}else{a(this.domPosition.parent).prepend(this.placeholder)}this._trigger("revert",e,this._uiHash())}else{var c=this.placeholder.parent().closest(this.options.items);for(var b=this.beyondMaxLevels-1;b>0;b--){c=c.parent().closest(this.options.items)}c.after(this.placeholder);this._trigger("change",e,this._uiHash())}}for(var b=this.items.length-1;b>=0;b--){var d=this.items[b].item[0];this._clearEmpty(d)}a.ui.sortable.prototype._mouseStop.apply(this,arguments)},serialize:function(d){var b=this._getItemsAsjQuery(d&&d.connected),c=[];d=d||{};a(b).each(function(){var f=(a(d.item||this).attr(d.attribute||"id")||"").match(d.expression||(/(.+)[-=_](.+)/)),e=(a(d.item||this).parent(d.listType).parent("li").attr(d.attribute||"id")||"").match(d.expression||(/(.+)[-=_](.+)/));if(f){c.push(((d.key||f[1])+"["+(d.key&&d.expression?f[1]:f[2])+"]")+"="+(e?(d.key&&d.expression?e[1]:e[2]):"root"))}});if(!c.length&&d.key){c.push(d.key+"=")}return c.join("&")},toHierarchy:function(e){e=e||{};var c=e.startDepthCount||0,d=[];a(this.element).children("li").each(function(){var f=b(a(this));d.push(f)});return d;function b(f){var h=(a(f).attr(e.attribute||"id")||"").match(e.expression||(/(.+)[-=_](.+)/));if(h){var g={id:h[2]};if(a(f).children(e.listType).children("li").length>0){g.children=[];a(f).children(e.listType).children("li").each(function(){var i=b(a(this));g.children.push(i)})}return g}}},toArray:function(f){f=f||{};var b=f.startDepthCount||0,c=[],d=2;c.push({item_id:"root",parent_id:"none",depth:b,left:"1",right:(a("li",this.element).length+1)*2});a(this.element).children("li").each(function(){d=e(this,b+1,d)});c=c.sort(function(h,g){return(h.left-g.left)});return c;function e(j,l,k){var i=k+1,m,h;if(a(j).children(f.listType).children("li").length>0){l++;a(j).children(f.listType).children("li").each(function(){i=e(a(this),l,i)});l--}m=(a(j).attr(f.attribute||"id")).match(f.expression||(/(.+)[-=_](.+)/));if(l===b+1){h="root"}else{var g=(a(j).parent(f.listType).parent("li").attr(f.attribute||"id")).match(f.expression||(/(.+)[-=_](.+)/));h=g[2]}if(m){c.push({item_id:m[2],parent_id:h,depth:l,left:k,right:i})}k=i+1;return k}},_clearEmpty:function(b){var c=a(b).children(this.options.listType);if(c.length&&!c.children().length){c.remove()}},_getLevel:function(b){var d=1;if(this.options.listType){var c=b.closest(this.options.listType);while(!c.is(".ui-sortable")){d++;c=c.parent().closest(this.options.listType)}}return d},_getChildLevels:function(d,f){var c=this,e=this.options,b=0;f=f||0;a(d).children(e.listType).children(e.items).each(function(g,h){b=Math.max(c._getChildLevels(h,f+1),b)});return f?b+1:b},_isAllowed:function(b,c){var d=this.options;if(b==null||!(b.hasClass(d.disableNesting))){if(d.maxLevels<c&&d.maxLevels!=0){this.placeholder.addClass(d.errorClass);this.beyondMaxLevels=c-d.maxLevels}else{this.placeholder.removeClass(d.errorClass);this.beyondMaxLevels=0}}else{this.placeholder.addClass(d.errorClass);if(d.maxLevels<c&&d.maxLevels!=0){this.beyondMaxLevels=c-d.maxLevels}else{this.beyondMaxLevels=1}}}}));a.ui.nestedSortable.prototype.options=a.extend({},a.ui.sortable.prototype.options,a.ui.nestedSortable.prototype.options)})(jQuery);
JavaScript
// Set these vars on the controller pages var cms_name_field = null; var cms_file_name_field = null; var cms_file_name_modified = false; var cms_page = false; jQuery(document).ready(function($){ if ( cms_name_field && ($(cms_name_field).length > 0) && ($('#new_flag').length > 0) && ($(cms_file_name_field).length > 0) ) { var element = $(cms_name_field); $(cms_file_name_field).bind('change', function(){ cms_file_name_modified = true; }); element.bind('keyup', function() { update_file_name(element); }); element.bind('change', function() { update_file_name(element); }); element.bind('modified', function() { update_file_name(element); }); } }); function update_file_name(name_field) { if (cms_file_name_modified) return; var text = name_field.val(); text = text.replace(/[^a-z0-9:_]/gi, '_'); text = text.replace(/:/g, ';'); text = text.replace(/__/g, '_'); text = text.replace(/__/g, '_'); text = text.replace(/^_/g, ''); if (text.match(/_$/)) text = text.substr(0, text.length-1); if (!text.length && cms_page) text = 'home'; jQuery(cms_file_name_field).val(text.toLowerCase()); }
JavaScript
function themes_selected() { return $('listCms_Themes_index_list_body').getElements('tr td.checkbox input').some(function(element){return element.checked}); } function delete_selected() { if (!themes_selected()) { alert('Please select theme(s) to delete.'); return false; } $('listCms_Themes_index_list_body').getForm().sendPhpr( 'index_ondelete_selected', { confirm: 'Do you really want to delete selected theme(s)? This will delete all theme templates, pages, partials and asset files.', loadIndicator: {show: false}, onBeforePost: LightLoadingIndicator.show.pass('Loading...'), onComplete: LightLoadingIndicator.hide, update: 'themes_page_content', onAfterUpdate: update_scrollable_toolbars } ); return false; } function duplicate_theme() { var selected = $('listCms_Themes_index_list_body').getElements('tr td.checkbox input').filter(function(element){return element.checked}); if (!selected.length) { alert('Please select a theme to duplicate.'); return false; } if (selected.length > 1) { alert('Please select a single theme to duplicate.'); return false; } new PopupForm('index_onshow_duplicate_theme_form', {ajaxFields: $('listformCms_Themes_index_list')}); return false; } function enable_selected() { if (!themes_selected()) { alert('Please select theme(s) to enable.'); return false; } $('listCms_Themes_index_list_body').getForm().sendPhpr( 'index_onenable_selected', { loadIndicator: {show: false}, onBeforePost: LightLoadingIndicator.show.pass('Loading...'), onComplete: LightLoadingIndicator.hide, update: 'themes_page_content', onAfterUpdate: update_scrollable_toolbars } ); return false; } function disable_selected() { if (!themes_selected()) { alert('Please select theme(s) to disable.'); return false; } $('listCms_Themes_index_list_body').getForm().sendPhpr( 'index_ondisable_selected', { loadIndicator: {show: false}, onBeforePost: LightLoadingIndicator.show.pass('Loading...'), onComplete: LightLoadingIndicator.hide, update: 'themes_page_content', onAfterUpdate: update_scrollable_toolbars } ); return false; } function refresh_theme_list() { $('listCms_Themes_index_list_body').getForm().sendPhpr('index_onRefresh', { loadIndicator: {show: false}, onBeforePost: LightLoadingIndicator.show.pass('Loading...'), onComplete: LightLoadingIndicator.hide, update: 'themes_page_content', onAfterUpdate: function() { update_scrollable_toolbars(); } }); }
JavaScript
/** * Helpers */ function root_url(url) { if (typeof root_dir === 'undefined' || !root_dir) return url; if (url.substr(0,1) == '/') url = url.substr(1); return root_dir + url; } function asset_url(url) { if (typeof asset_dir === 'undefined' || !asset_dir) return url; if (url.substr(0,1) == '/') url = url.substr(1); return root_url(asset_dir + url); } function var_dump(obj, alert) { var out = ''; for (var i in obj) { out += i + ": " + obj[i] + "\n"; } if (alert) alert(out); else jQuery('<pre />').html(out).appendTo(jQuery('body')); };
JavaScript
jQuery(document).ready(function($) { var gateway_field = $('#Sms_Config_class_name'); if (gateway_field.length > 0) { gateway_field.live('change', function() { $('#Sms_Config_class_name').get(0).getForm().sendPhpr( 'index_onUpdateGatewayType', { loadIndicator: { show: false }, onBeforePost: LightLoadingIndicator.show.pass('Loading settings...'), onComplete: LightLoadingIndicator.hide } ) }); } });
JavaScript
var formTabManager = null; var url_modified = false; function save_code() { $('form_element').sendPhpr('onSave', { prepareFunction: function(){phprTriggerSave();}, extraFields: {redirect: 0}, loadIndicator: {show: false}, onBeforePost: LightLoadingIndicator.show.pass('Saving...'), onComplete: LightLoadingIndicator.hide, onFailure: popupAjaxError, update: 'multi'}); return false; } window.addEvent('domready', function(){ $(document.getElement('html')).bindKeys({ 'meta+s, ctrl+s': save_code }); var title_field = $('Blog_Post_title'); if (title_field && $('new_record_flag')) { title_field.addEvent('keyup', update_url_title.pass(title_field)); title_field.addEvent('change', update_url_title.pass(title_field)); title_field.addEvent('paste', update_url_title.pass(title_field)); } if ($('new_record_flag')) { var url_element = $('Blog_Post_url_title'); url_element.addEvent('change', function(){url_modified=true;}); } }); function update_url_title(field_element) { if (!url_modified) $('Blog_Post_url_title').value = convert_text_to_url(field_element.value); }
JavaScript
function update_comment_status(element, comment_id, confirm_str, status_code) { return $(element).getForm().sendPhpr('preview_onSetCommentStatus', {update: 'comment_list', confirm: confirm_str, 'extraFields': {'id': comment_id, 'status': status_code}, onFailure: popupAjaxError, loadIndicator: {show: false}, onBeforePost: LightLoadingIndicator.show.pass('Updating...'), onComplete: LightLoadingIndicator.hide}); }
JavaScript
var url_modified = false; function update_url_title(field_element) { if (!url_modified) $('Blog_Category_url_name').value = convert_text_to_url(field_element.value); } window.addEvent('domready', function(){ var title_field = $('Blog_Category_name'); if (title_field && $('new_record_flag')) { title_field.addEvent('keyup', update_url_title.pass(title_field)); title_field.addEvent('change', update_url_title.pass(title_field)); title_field.addEvent('paste', update_url_title.pass(title_field)); } if ($('new_record_flag')) { var url_element = $('Blog_Category_url_name'); url_element.addEvent('change', function(){url_modified=true;}); } });
JavaScript
jQuery(document).ready(function(){ jQuery('#Service_Provider_country_id').bind('change', function(){ $('Service_Provider_country_id').getForm().sendPhpr( 'onUpdateStatesList', { loadIndicator: {show: false} } ) }); });
JavaScript
jQuery(document).ready(function(){ jQuery('#Service_Request_country_id').bind('change', function(){ $('Service_Request_country_id').getForm().sendPhpr( 'onUpdateStatesList', { loadIndicator: {show: false} } ) }); });
JavaScript
function make_providers_sortable() { if ($('group_providers_list')) { $('group_providers_list').makeListSortable('onSetOrders', 'provider_order', 'provider_id', 'sort_handle'); $('group_providers_list').addEvent('dragComplete', fix_orders); } } function fix_orders(sortable_list_orders) { $('group_providers_list').getChildren().each(function(element, index){ var order_input = element.getElement('input.provider_order'); if (order_input) { if (index <= sortable_list_orders.length-1) order_input.value = sortable_list_orders[index]; } if (index % 2) element.addClass('even'); else element.removeClass('even'); }) } window.addEvent('domready', function(){ if ($('group_providers_list')) make_providers_sortable(); })
JavaScript
function bind_action_event() { var action_select = jQuery('#Payment_Fee_action_class_name'); if (action_select.length > 0) { action_select.not('.fee_binded').addClass('fee_binded').bind('change', function(){ action_select.get(0).getForm().sendPhpr('on_update_action', { loadIndicator: { hideOnSuccess: true }, update: 'multi', onAfterUpdate: bind_action_event }) }); } var event_select = jQuery('#Payment_Fee_event_class_name'); if (event_select.length > 0) { event_select.not('.fee_binded').addClass('fee_binded').bind('change', function(){ event_select.get(0).getForm().sendPhpr('on_update_action', { loadIndicator: { hideOnSuccess: true }, update: 'multi', onAfterUpdate: bind_action_event }) }); } } jQuery(document).ready(function($) { bind_action_event(); });
JavaScript
window.addEvent('phpr_recordfinder_update', function() { $('Payment_Invoice_user_id').getForm().sendPhpr('on_user_change', { loadIndicator: {show: false}, update:'multi' }); }) jQuery(document).ready(function(){ jQuery('#Payment_Invoice_billing_country_id').bind('change', function(){ $('Payment_Invoice_billing_country_id').getForm().sendPhpr( 'on_update_state_list', { loadIndicator: {show: false} } ) }); });
JavaScript
jQuery(document).ready(function($) { fee_bind_sort(); }); function fee_after_drag() { var list = jQuery('#fee_list'); var items = list.find('> li'); var last_index = items.length - 1; items.each(function(index, val) { var item = jQuery(this); item.css('z-index', 1000 + last_index - index); if (index == 0) item.removeClass('last').addClass('first'); if (index == last_index) item.removeClass('first').addClass('last'); if (index != last_index && index != 0) item.removeClass('first').removeClass('last'); }); } function fee_toggle(element, fee_id) { var new_status_value = jQuery(element).closest('li').hasClass('collapsed'); $(element).getForm().sendPhpr('on_set_fee_collapse_status', { loadIndicator: {show: false}, extraFields: {'new_status': (new_status_value) ? 0 : 1, 'fee_id': fee_id} }); if (new_status_value) jQuery(element).closest('li').removeClass('collapsed'); else jQuery(element).closest('li').addClass('collapsed'); return false; } function fee_bind_sort() { if (jQuery('#fee_list').length > 0) { var fee_list = jQuery('#fee_list').get(0); fee_list.makeListSortable('on_set_fee_orders', 'fee_order', 'fee_id', 'drag_handle'); fee_list.addEvent('dragComplete', fee_after_drag); } } function fee_delete(element, fee_id) { $(element).getForm().sendPhpr('on_delete_fee', { confirm: 'Do you really want to delete this fee?', onBeforePost: LightLoadingIndicator.show.pass('Loading...'), onComplete: LightLoadingIndicator.hide, update: 'fee_list_container', loadIndicator: {show: false}, onFailure: popupAjaxError, extraFields: {'fee_id': fee_id}, onAfterUpdate: fee_bind_sort }); return false; }
JavaScript
var UnloadManagerClass = new Class({ data_changed_flag: false, unload_message: 'Form data was changed.', verbose: false, initialize: function() { window.addEvent('domready', this.bind_inputs.bind(this)); window.addEvent('phpr_codeeditor_changed', this.data_changed.bind(this, 'editarea')); window.addEvent('phpreditoradded', this.bind_html_editors.bind(this)); window.addEvent('phpreditorreloaded', this.bind_html_editors.bind(this)); window.onbeforeunload = this.handle_unload; if (Browser.Engine.trident) $(document).addEvent('keypress', this.handle_keys.bindWithEvent(this, this) ); else $(window).addEvent('keypress', this.handle_keys.bindWithEvent(this, this) ); }, handle_keys: function(event) { var ev = new Event(event); if ( !(((ev.code >= 65 && ev.code <= 90) || (ev.code >= 48 && ev.code <= 57)) && !event.control && !event.meta && !event.alt) ) return true; if (ev.target) { if (ev.target.tagName != 'TEXTAREA' && ev.target.tagName != 'INPUT' && ev.target.tagName != 'SELECT') return true; } if (this.verbose) { console.log('Key pressed...' + ev.code); console.log(ev.target.tagName); } this.data_changed(); return true; }, bind_inputs: function() { $(document.body).getElements('input').each(function(input){ if (input.type == 'radio' || input.type == 'checkbox') input.addEvent('click', this.data_changed.bind(this)); }, this); $(document.body).getElements('select').each(function(input){ input.addEvent('change', this.data_changed.bind(this)); }, this); }, bind_html_editors: function(editor_id) { var editor = tinyMCE.get(editor_id); if (editor) editor.onChange.add(this.data_changed.bind(this)); else { tinyMCE.onAddEditor.add(function(mgr,ed) { if (ed.id == editor_id) { ed.onChange.add(UnloadManager.data_changed.bind(UnloadManager)); } }); } }, data_changed: function(src) { if (this.verbose) console.log('Something changed...'); this.data_changed_flag = true; }, handle_unload: function() { if ($('phpr_lock_mode')) return; try { if (tinymce && tinymce.EditorManager.activeEditor) tinymce.EditorManager.activeEditor.execCommand('mceEndTyping', false, null); } catch(e){} if (UnloadManager.data_changed_flag) return UnloadManager.unload_message; }, reset_changes: function() { try { if (tinymce && tinymce.EditorManager.activeEditor) tinymce.EditorManager.activeEditor.execCommand('mceEndTyping', false, null); } catch(e){} if (this.verbose) console.log('Changes cancelled...'); this.data_changed_flag = false; } }); var UnloadManager = new UnloadManagerClass();
JavaScript
jQuery(document).ready(function($){ $("#main_nav ul ul").not('li.current ul').hide(); $("#main_nav > ul > li > a").each(function() { var submenu = $(this).parent().find('ul'); if ((submenu).length > 0) { $(this).append('<span class="expand"></span>'); $(this).click(function() { $(this).parent().find('ul').slideToggle(); return false; }); } }); $('#user_menu').hover(function(){ $(this).addClass('active'); }, function(){ $(this).removeClass('active'); }); });
JavaScript
jQuery(document).ready(function($) { if ($('#login').length > 0) $('#login').focus(); $(".fieldContainer input").focus(function(){ $(this).addClass('active'); }); $(".fieldContainer input").blur(function(){ $(this).removeClass('active'); }); });
JavaScript
/* * Initialize tips */ window.addEvent('domready', function(){ init_tooltips(); }); function init_tooltips() { (function( $ ){ if ($.fn.tipsy !== undefined) { $('a.tooltip, span.tooltip, li.tooltip').tipsy({ live: true, delayIn: 500, html: true, gravity: $.fn.tipsy.autoWE }); } })(jQuery); } function update_tooltips() { init_tooltips(); } function hide_tooltips() { (function( $ ){ $('a.tooltip, span.tooltip').each(function(index, e){ $(e).tipsy('hide'); }); })(jQuery); } /* * Form styling */ function backend_style_forms() { jQuery('select').each(function(){ if (!this.hasClass('no-styling')) { var options = {}, self = this, select = jQuery(this); if (this.options.length > 0 && this.options[0].value == "") { var placeholder = jQuery(this.options[0]).text(); placeholder = placeholder.replace('<', '- ').replace('>', ' -').replace("'", "\'"); select.attr('data-placeholder', placeholder); jQuery(this.options[0]).text(''); options.allow_single_deselect = true; } select.unbind('.chosen-handler'); select.bind('change.chosen-handler', function(){ $(this).fireEvent('change'); }); select.chosen(options); } }); jQuery('input[type=checkbox]').each(function(){ if (!this.styled) { this.styled = true; var self = $(this), replacement = new Element('div', {'class': 'checkbox', 'tabindex': 0}), handle_click = function() { /* * Update the checkbox state and execute the checbox onclick and onchange handlers */ self.checked = !self.checked; if (self.onclick !== undefined && self.onclick) self.onclick(); if (self.onchange !== undefined && self.onchange) self.onchange(); /* * Fire MooTools events. */ self.fireEvent('click'); self.fireEvent('change'); }, update_replacement_status = function() { if (self.checked) replacement.addClass('checked'); else replacement.removeClass('checked'); }; self.addClass('hidden'); if (this.checked) replacement.addClass('checked'); if (this.disabled) replacement.addClass('disabled'); replacement.addEvent('keydown', function(ev){ if (!replacement.hasClass('disabled')) { var event = new Event(ev); if (event.code == 32 || event.code == 13) { if (!ev.control) { handle_click(); ev.stopPropagation(); return false; } } } }); self.addEvent('change', function(){ if (replacement.hasClass('disabled')) return; update_replacement_status(); }); self.addEvent('change_status', function(){ update_replacement_status(); }); self.addEvent('enable', function(){ replacement.removeClass('disabled'); }); self.addEvent('disable', function(){ replacement.addClass('disabled'); }); replacement.addEvent('click', function(ev) { if (!replacement.hasClass('disabled')) { handle_click(); var event = new Event(ev); ev.stopPropagation(); return false; } }); jQuery(replacement).bind('dblclick', function(ev){ ev.stopPropagation(); return false; }); replacement.inject(self, 'before'); } }); }; Element.implement({ cb_check: function() { this.cb_update_state(true); }, cb_uncheck: function() { this.cb_update_state(false); }, cb_update_state: function(state) { this.checked = state; this.fireEvent('change_status'); jQuery(this).trigger('change'); /* * Do not trigger the click handler, because it can * result in recursion. However it could be needed * in some cases and can be solved with an optional * parameter. */ }, cb_enable: function() { this.fireEvent('enable'); }, cb_disable: function() { this.fireEvent('disable'); }, cb_update_enabled_state: function(state) { if (state) this.cb_enable(); else this.cb_disable(); }, select_update: function() { jQuery(this).trigger("liszt:updated"); }, select_focus: function() { var el = jQuery(this).parent().find('a.chzn-single'); if (el.length > 0) el[0].focus(); } }); window.addEvent('domready', function(){ backend_style_forms(); window.addEvent('onAfterAjaxUpdateGlobal', backend_style_forms); }); /* * Define backend-wide load indicator and AJAX request defaults */ Element.implement({ getLoadingIndicatorDefaults: function() { return { overlayClass: 'formOverlay', pos_x: 'center', pos_y: 'center', src: phpr_url('/resources/images/form_load_70x70.gif'), injectInElement: false, noImage: false, z_index: 9999, absolutePosition: true, injectPosition: 'bottom', hideElement: true }; } }); Request.Phpr.implement({ getRequestDefaults: function() { return { loadIndicator: { element: 'FormElement', show: true, hideOnSuccess: false }, onFailure: this.highlightError.bind(this), onSuccess: this.hideError.bind(this), errorHighlight: { backgroundFromColor: '#f00', backgroundToColor: '#ffffcc' }, onAfterError: this.highlightFormError.bind(this), hideErrorOnSuccess: true }; }, hideError: function() { if (!this.options.hideErrorOnSuccess) return; if (!this.options.loadIndicator.hideOnSuccess) return; var element = null; if (this.options.errorHighlight.element != null) element = $(this.options.errorHighlight.element); else { if (this.dataObj && $type(this.dataObj) == 'element') element = $(this.dataObj).getElement('.formFlash'); } if (!element) return; element.innerHTML = ''; var parent_form = element.selectParent('form'); if (parent_form) { $(parent_form).getElements('ul.formElements li.field').each(function(el){ el.removeClass('error'); }); } }, highlightFormError: function() { $(document.body).getElements('ul.formElements li.field').each(function(el){ el.removeClass('error'); }); var el = $(window.phprErrorField); if (!el) return; var parentLi = el.getParent('li.field'); if (parentLi) parentLi.addClass('error'); } }); /* * Light loading indicator */ var LightLoadingIndicator = new Class({ active_request_num: 0, loading_indicator_element: null, Binds: ['show', 'hide'], show: function(message) { this.active_request_num++; this.create_loading_indicator(message); }, hide: function() { this.active_request_num--; if (this.active_request_num == 0) this.remove_loading_indicator(); }, create_loading_indicator: function(message) { if (this.loading_indicator_element) return; this.loading_indicator_element = new Element('p', {'class': 'light_loading_indicator'}).inject(document.body, 'top'); this.loading_indicator_element.innerHTML = '<span>'+message+'</span>'; }, remove_loading_indicator: function() { if (this.loading_indicator_element) this.loading_indicator_element.destroy(); this.loading_indicator_element = null; } }); LightLoadingIndicator = new LightLoadingIndicator(); /* * Tabs classes */ var TabManager = new Class({ Extends: TabManagerBase, tabClick: function(tab, page, tabIndex) { this.tabs.each(function(tabElement){tabElement.removeClass('active')}); tab.addClass('active'); for (var i = 0; i < this.pages.length; i++) { if ( i != tabIndex ) this.pages[i].hide(); } this.pages[tabIndex].show(); } }); /* * Scrollable form tabs */ var Backend_ScrollabeTabbar = new Class({ tabbar: null, scroll_offset: 15, Binds: ['scroll_tabs_right', 'scroll_tabs_left', 'stop_scrolling', 'resize_toolbar'], initialize: function(tabbar) { this.attach(tabbar); }, attach: function(tabbar) { this.tabbar = $(tabbar); this.scroll_area = this.tabbar.getElement('ul'); this.scroll_area.scrollLeft = 0; this.scroll_left = this.tabbar.getElement('.left'); this.scroll_right = this.tabbar.getElement('.right'); this.scroll_right.addEvent('mouseenter', this.scroll_tabs_right); this.scroll_left.addEvent('mouseenter', this.scroll_tabs_left); this.scroll_right.addEvent('mouseleave', this.stop_scrolling); this.scroll_left.addEvent('mouseleave', this.stop_scrolling); this._update(); }, detach: function() { this.scroll_right.removeEvent('mouseenter', this.scroll_tabs_right); this.scroll_left.removeEvent('mouseenter', this.scroll_tabs_left); this.scroll_right.removeEvent('mouseleave', this.stop_scrolling); this.scroll_left.removeEvent('mouseleave', this.stop_scrolling); }, scroll_tabs_right: function() { this.start_scrolling(this.scroll_offset); }, scroll_tabs_left: function() { this.start_scrolling(this.scroll_offset*-1); }, start_scrolling: function(offset) { this.scroll_interval_id = this.scroll.periodical(30, this, offset); this.prev_offset = this.scroll_area.scrollLeft; }, scroll: function(offset) { this.scroll_area.scrollLeft = this.scroll_area.scrollLeft + offset; if (this.scroll_area.scrollLeft === this.prev_offset) { if (offset > 0) this.scroll_right.addClass('scroll-disabled'); else this.scroll_left.addClass('scroll-disabled'); } else { if (offset > 0) this.scroll_left.removeClass('scroll-disabled'); else this.scroll_right.removeClass('scroll-disabled'); } this.prev_offset = this.scroll_area.scrollLeft; }, stop_scrolling: function() { if (this.scroll_interval_id) { $clear(this.scroll_interval_id); this.scroll_interval_id = 0; } }, _update: function() { var tabs_width = this._get_tabs_width(); if (tabs_width > this.scroll_area.getSize().x) { this.tabbar.addClass('scroll-active'); } else { this.tabbar.removeClass('scroll-active'); } }, _get_tabs_width: function() { var result = 0; this.scroll_area.getElements('li').each(function(li){ result += li.getSize().x+1; }) return result; } }); /* * Scrollable toolbars */ var backend_scrollable_toolbars = []; var backend_scrollable_toolbar_offsets = []; var Backend_ScrollabeToolbar = new Class({ toolbar: null, toolbar_scroll_area: null, toolbar_scroll_content: null, toolbar_scroll_controls: null, scrollable_content_width: null, extra_element: null, scroll_left: null, scroll_right: null, scroll_button_width: 18, scroll_interval_id: 0, scroll_offset: 15, offset_index: 0, Binds: ['scroll_toolbar_left', 'scroll_toolbar_right', 'stop_scrolling', 'resize_toolbar'], initialize: function(toolbar) { this.attach(toolbar); backend_scrollable_toolbars.push(this); this.offset_index = backend_scrollable_toolbars.length-1; var initial_offset = backend_scrollable_toolbar_offsets[this.offset_index] ? backend_scrollable_toolbar_offsets[this.offset_index] : 0; this.set_scroll(initial_offset); }, attach: function(toolbar) { this.toolbar = $(toolbar); this.toolbar_scroll_area = this.toolbar.getElement('.scroll_area'); this.toolbar_scroll_controls = this.toolbar.getElement('.scroll_controls'); if (this.toolbar.getChildren().length > 1) this.extra_element = $(this.toolbar.getChildren()[1]); this.toolbar_scroll_content = this.toolbar.getElement('.toolbar'); this.scrollable_content_width = this.toolbar_scroll_content.getSize().x; this.scroll_left = this.toolbar.getElement('.scroll_left'); this.scroll_right = this.toolbar.getElement('.scroll_right'); this.resize_toolbar(); this.scroll_right.addEvent('mouseenter', this.scroll_toolbar_right); this.scroll_left.addEvent('mouseenter', this.scroll_toolbar_left); this.scroll_right.addEvent('mouseleave', this.stop_scrolling); this.scroll_left.addEvent('mouseleave', this.stop_scrolling); window.addEvent('resize', this.resize_toolbar); }, detach: function() { this.scroll_right.removeEvent('mouseenter', this.scroll_toolbar_right); this.scroll_left.removeEvent('mouseenter', this.scroll_toolbar_left); this.scroll_right.removeEvent('mouseleave', this.stop_scrolling); this.scroll_left.removeEvent('mouseleave', this.stop_scrolling); window.removeEvent('resize', this.resize_toolbar); }, resize_toolbar: function() { var full_width = this.toolbar.getSize().x; var extra_element_width = this.extra_element ? (this.extra_element.getSize().x + 20) : 0; var toolbar_no_buttons_width = full_width - extra_element_width; var scroll_buttons_visible = this.scrollable_content_width > toolbar_no_buttons_width; var buttons_width = scroll_buttons_visible ? this.scroll_button_width*2 : 0; var toolbar_width = toolbar_no_buttons_width - buttons_width; this.toolbar_scroll_area.setStyle('width', (toolbar_width - (scroll_buttons_visible ? 3 : 0)) + 'px'); this.toolbar_scroll_controls.setStyle('width', toolbar_no_buttons_width + 'px'); if (this.scrollable_content_width > toolbar_width) { this.toolbar.addClass('scroll_enabled'); this.scroll_left.show(); this.scroll_right.show(); } else { this.toolbar.removeClass('scroll_enabled'); this.scroll_left.hide(); this.scroll_right.hide(); this.toolbar_scroll_area.scrollLeft = 0; } this.update_scroll_buttons(); }, update_scroll_buttons: function() { if (this.scroll_right_visible()) this.scroll_right.removeClass('disabled') else this.scroll_right.addClass('disabled'); if (this.scroll_left_visible()) this.scroll_left.removeClass('disabled') else this.scroll_left.addClass('disabled'); }, scroll_right_visible: function() { var toolbar_width = this.toolbar_scroll_content.getSize().x; var scrollarea_width = this.toolbar_scroll_area.getSize().x; var max_scroll_offset = toolbar_width - scrollarea_width; return toolbar_width > scrollarea_width && this.toolbar_scroll_area.scrollLeft < max_scroll_offset; }, scroll_left_visible: function() { return this.toolbar_scroll_area.scrollLeft > 0; }, scroll_toolbar_right: function() { this.start_scrolling(this.scroll_offset); }, scroll_toolbar_left: function() { this.start_scrolling(this.scroll_offset*-1); }, start_scrolling: function(offset) { this.scroll_interval_id = this.scroll.periodical(30, this, offset); }, scroll: function(offset) { this.toolbar_scroll_area.scrollLeft = this.toolbar_scroll_area.scrollLeft + offset; this.update_scroll_buttons(); backend_scrollable_toolbar_offsets[this.offset_index] = this.toolbar_scroll_area.scrollLeft; }, stop_scrolling: function() { if (this.scroll_interval_id) { $clear(this.scroll_interval_id); this.scroll_interval_id = 0; } }, set_scroll: function(scroll) { this.toolbar_scroll_area.scrollLeft = scroll; this.update_scroll_buttons(); backend_scrollable_toolbar_offsets[this.offset_index] = this.toolbar_scroll_area.scrollLeft; } }); function init_scrollable_toolbars() { $$('.scrollable_control_panel').each(function(toolbar){ new Backend_ScrollabeToolbar(toolbar); }) } function update_scrollable_toolbars() { backend_scrollable_toolbars.each(function(toolbar){ toolbar.detach(); }); backend_scrollable_toolbars = [] init_scrollable_toolbars(); } window.addEvent('domready', init_scrollable_toolbars);
JavaScript
var checkbox_states = { }; jQuery(document).ready(function(){ // Permissions update_permissions(); jQuery('#form_field_container_rightsAdmin_User input.checkbox').click(update_permissions); }); function update_permissions() { var is_admin_checkbox = jQuery('#form_field_container_rightsAdmin_User input.checkbox'); var is_admin = is_admin_checkbox.is(':checked'); if (is_admin) reset_permissions(); jQuery('#form_pagesAdmin_User li.permission_field input').each(function(){ var el = jQuery(this); var id = el.attr('id'); el.get(0).cb_update_enabled_state(!is_admin); if (id && el.hasClass('checkbox')) { if (is_admin) el.get(0).cb_check(); else if (checkbox_states[id] !== undefined) el.get(0).cb_update_state(checkbox_states[id]); } }); } function reset_permissions() { checkbox_states = { }; jQuery('#form_pagesAdmin_User li.permission_field input').each(function() { var el = jQuery(this); var id = el.attr('id'); if (id && el.hasClass('checkbox')) checkbox_states[id] = el.is(':checked'); }); }
JavaScript
/* * Tipsy */ jQuery(function(){ jQuery('.tips').tipsy({gravity: 's',html: true}); jQuery('.tips-right').tipsy({gravity: 'w',html: true}); jQuery('.tips-left').tipsy({gravity: 'e',html: true}); jQuery('.tips-bottom').tipsy({gravity: 'n',html: true}); }); /* * Commmon functions */ function convert_text_to_url(text) { var url_separator_char = '-'; if (typeof url_separator != 'undefined') url_separator_char = url_separator; var value = text.replace(/[^a-z0-9]/gi, url_separator_char); var p = new RegExp(url_separator_char+'+', 'g'); value = value.replace(p, url_separator_char); p = new RegExp(url_separator_char+'$', 'g'); if (value.match(p)) value = value.substr(0, value.length-1); return value.toLowerCase(); } function hide_hint(hint_name, close_element, hint_element) { if (hint_element === undefined) hint_element = $(close_element).selectParent('div.hint_container'); if (hint_element) hint_element.hide(); var form = hint_element.getForm(); return $(form).sendPhpr('hint_hide', { extraFields: { 'name': hint_name }, loadIndicator: {show: false} }); } jQuery.fn.extend({ admin_hide: function(){ jQuery(this).addClass('hidden'); }, admin_show: function(){ jQuery(this).removeClass('hidden'); } }); /* * Protected JSON stringify */ jQuery.extend({ stringify : function stringify(obj) { var t = typeof (obj); if (t != "object" || obj === null) { // simple data type if (t == "string") obj = '"' + obj + '"'; return String(obj); } else { // recurse array or object var n, v, json = [], arr = (obj && obj.constructor == Array); for (n in obj) { v = obj[n]; t = typeof(v); if (obj.hasOwnProperty(n)) { if (t == "string") v = '"' + v + '"'; else if (t == "object" && v !== null) v = jQuery.stringify(v); json.push((arr ? "" : '"' + n + '":') + String(v)); } } return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}"); } } });
JavaScript
function select_countries(select_type) { switch (select_type) { case 'all': jQuery('#listLocation_Countries_index_list_body tr td.checkbox input').each(function(){ jQuery(this).get(0).cb_check(); }); break; case 'none': jQuery('#listLocation_Countries_index_list_body tr td.checkbox input').each(function(){ jQuery(this).get(0).cb_uncheck(); }); break; case 'enabled': jQuery('#listLocation_Countries_index_list_body tr.country_enabled td.checkbox input').each(function(){ jQuery(this).get(0).cb_check(); }); break; case 'disabled': jQuery('#listLocation_Countries_index_list_body tr.country_disabled td.checkbox input').each(function(){ jQuery(this).get(0).cb_check(); }); break; } return false; } function enable_disable_selected() { if (jQuery('#listLocation_Countries_index_list_body tr td.checkbox input:checked') == 0) { alert('Please select countries to enable or disable.'); return false; } new PopupForm('index_onLoadEnableDisableCountriesForm', { ajaxFields: $('listLocation_Countries_index_list_body').getForm() }); return false; }
JavaScript
jQuery(document).ready(function($) { var reply_to_address_field = $('#Email_Template_reply_to_address'); if (reply_to_address_field.length > 0) { reply_to_address_field.attr('disabled', !$('#Email_Template_reply_to_mode_4').is(':checked')); $('#Email_Template_reply_to_mode, #Email_Template_reply_to_mode_2, #Email_Template_reply_to_mode_3, #Email_Template_reply_to_mode_4').click(function() { reply_to_address_field.attr('disabled', !$('#Email_Template_reply_to_mode_4').is(':checked')); }); } });
JavaScript
function set_authorization_status() { var smtp_auth_checked = !(jQuery('#Email_Config_smtp_authorization').is(':checked')); jQuery('#Email_Config_smtp_user').attr('disabled', smtp_auth_checked); jQuery('#Email_Config_smtp_password').attr('disabled', smtp_auth_checked); } function set_email_method() { var send_mode_value = jQuery('#Email_Config_send_mode').val(); switch (send_mode_value) { case 'smtp': jQuery('#tab_smtp').admin_show(); jQuery('#tab_sendmail').admin_hide(); break; case 'mail': jQuery('#tab_smtp').admin_hide(); jQuery('#tab_sendmail').admin_hide(); break; case 'sendmail': jQuery('#tab_sendmail').admin_show(); jQuery('#tab_smtp').admin_hide(); break; } } jQuery(document).ready(function($) { set_authorization_status(); set_email_method(); $('#Email_Config_smtp_authorization').bind('click', set_authorization_status); $('#Email_Config_send_mode').bind('change', set_email_method); });
JavaScript
/* Script: Slider.js Class for creating horizontal and vertical slider controls. License: MIT-style license. */ var Slider = new Class({ Implements: [Events, Options], options: {/* onChange: $empty, onComplete: $empty,*/ onTick: function(position){ if(this.options.snap) position = this.toPosition(this.step); this.knob.setStyle(this.property, position); }, snap: false, offset: 0, range: false, wheel: false, steps: 100, mode: 'horizontal' }, initialize: function(element, knob, options){ this.setOptions(options); this.element = $(element); this.knob = $(knob); this.previousChange = this.previousEnd = this.step = -1; this.element.addEvent('mousedown', this.clickedElement.bind(this)); if (this.options.wheel) this.element.addEvent('mousewheel', this.scrolledElement.bindWithEvent(this)); var offset, limit = {}, modifiers = {'x': false, 'y': false}; switch (this.options.mode){ case 'vertical': this.axis = 'y'; this.property = 'top'; offset = 'offsetHeight'; break; case 'horizontal': this.axis = 'x'; this.property = 'left'; offset = 'offsetWidth'; } this.half = this.knob[offset] / 2; this.full = this.element[offset] - this.knob[offset] + (this.options.offset * 2); this.min = $chk(this.options.range[0]) ? this.options.range[0] : 0; this.max = $chk(this.options.range[1]) ? this.options.range[1] : this.options.steps; this.range = this.max - this.min; this.steps = this.options.steps || this.full; this.stepSize = Math.abs(this.range) / this.steps; this.stepWidth = this.stepSize * this.full / Math.abs(this.range) ; this.knob.setStyle('position', 'relative').setStyle(this.property, - this.options.offset); modifiers[this.axis] = this.property; limit[this.axis] = [- this.options.offset, this.full - this.options.offset]; this.drag = new Drag(this.knob, { snap: 0, limit: limit, modifiers: modifiers, onDrag: this.draggedKnob.bind(this), onStart: this.draggedKnob.bind(this), onComplete: function(){ this.draggedKnob(); this.end(); }.bind(this) }); if (this.options.snap) { this.drag.options.grid = Math.ceil(this.stepWidth); this.drag.options.limit[this.axis][1] = this.full; } }, set: function(step){ if (!((this.range > 0) ^ (step < this.min))) step = this.min; if (!((this.range > 0) ^ (step > this.max))) step = this.max; this.step = Math.round(step); this.checkStep(); this.end(); this.fireEvent('tick', this.toPosition(this.step)); return this; }, clickedElement: function(event){ var dir = this.range < 0 ? -1 : 1; var position = event.page[this.axis] - this.element.getPosition()[this.axis] - this.half; position = position.limit(-this.options.offset, this.full -this.options.offset); this.step = Math.round(this.min + dir * this.toStep(position)); this.checkStep(); this.end(); this.fireEvent('tick', position); }, scrolledElement: function(event){ var mode = (this.options.mode == 'horizontal') ? (event.wheel < 0) : (event.wheel > 0); this.set(mode ? this.step - this.stepSize : this.step + this.stepSize); event.stop(); }, draggedKnob: function(){ var dir = this.range < 0 ? -1 : 1; var position = this.drag.value.now[this.axis]; position = position.limit(-this.options.offset, this.full -this.options.offset); this.step = Math.round(this.min + dir * this.toStep(position)); this.checkStep(); }, checkStep: function(){ if (this.previousChange != this.step){ this.previousChange = this.step; this.fireEvent('change', this.step); } }, end: function(){ if (this.previousEnd !== this.step){ this.previousEnd = this.step; this.fireEvent('complete', this.step + ''); } }, toStep: function(position){ var step = (position + this.options.offset) * this.stepSize / this.full * this.steps; return this.options.steps ? Math.round(step -= step % this.stepSize) : step; }, toPosition: function(step){ return (this.full * Math.abs(this.min - step)) / (this.steps * this.stepSize) - this.options.offset; } });
JavaScript
/* * URL functions */ function root_url(url) { if (typeof application_root_dir === 'undefined' || !application_root_dir) return url; if (url.substr(0,1) == '/') url = url.substr(1); return application_root_dir + url; } function phpr_url(url) { if (typeof phpr_root_dir === 'undefined' || !phpr_root_dir) return url; if (url.substr(0,1) == '/') url = url.substr(1); return phpr_root_dir + url; } /* * Phpr request */ Request.Phpr = new Class({ Extends: Request.HTML, loadIndicatorName: false, lockName: false, singleUpdateElement: false, options: { handler: false, extraFields: {}, loadIndicator: { show: false, hideOnSuccess: true }, lock: true, lockName: false, evalResponse: true, onAfterError: $empty, onBeforePost: $empty, treeUpdate: false, confirm: false, preCheckFunction: false, postCheckFunction: false, prepareFunction: $empty, execScriptsOnFailure: true, evalScriptsAfterUpdate: false, alert: false, noLoadingIndicator: false // front-end feature }, getRequestDefaults: function() { return { loadIndicator: { element: null }, onFailure: this.popupError.bind(this), errorHighlight: { element: null, backgroundFromColor: '#f00', backgroundToColor: '#ffffcc' } }; }, initialize: function(options) { this.parent($merge(this.getRequestDefaults(), options)); this.setHeader('PHPR-REMOTE-EVENT', 1); this.setHeader('PHPR-POSTBACK', 1); if (this.options.handler) this.setHeader('PHPR-EVENT-HANDLER', 'ev{'+this.options.handler+'}'); this.addEvent('onSuccess', this.updateMultiple.bind(this)); this.addEvent('onComplete', this.processComplete.bind(this)); }, post: function(data) { if (this.options.lock) { var lockName = this.options.lockName ? this.options.lockName : 'request' + this.options.handler + this.options.url; if (lockManager.get(lockName)) return; } if (this.options.preCheckFunction) { if (!this.options.preCheckFunction.call()) return; } if (this.options.alert) { alert(this.options.alert); return; } if (this.options.confirm) { if (!confirm(this.options.confirm)) return; } if (this.options.postCheckFunction) { if (!this.options.postCheckFunction.call()) return; } if (this.options.prepareFunction) this.options.prepareFunction.call(); if (this.options.lock) { var lockName = this.options.lockName ? this.options.lockName : 'request' + this.options.handler + this.options.url; lockManager.set(lockName); this.lockName = lockName; } this.dataObj = data; if (!this.options.data) { var dataArr = []; switch ($type(this.options.extraFields)){ case 'element': dataArr.push($(this.options.extraFields).toQueryString()); break; case 'object': case 'hash': dataArr.push(Hash.toQueryString(this.options.extraFields)); } switch ($type(data)){ case 'element': dataArr.push($(data).toQueryString()); break; case 'object': case 'hash': dataArr.push(Hash.toQueryString(data)); } this.options.data = dataArr.join('&'); } if (this.options.loadIndicator.show) { this.loadIndicatorName = 'request' + new Date().getTime(); $(this.options.loadIndicator.element).showLoadingIndicator(this.loadIndicatorName, this.options.loadIndicator); } this.fireEvent('beforePost', {}); if (MooTools.version >= "1.3") this.parent(this.options.data); else this.parent(); }, processComplete: function() { if (this.options.lock) lockManager.remove(this.lockName); }, success: function(text) { var options = this.options, response = this.response; response.html = text.phprStripScripts(function(script){ response.javascript = script; }); if (options.update && options.update != 'multi' && !(/window.location=/.test(response.javascript)) && $(options.update)) { if (this.options.treeUpdate) { var temp = this.processHTML(response.html); response.tree = temp.childNodes; if (options.filter) response.tree = response.elements.filter(options.filter); response.elements = temp.getElements('*'); $(options.update).empty().adopt(response.tree); } else $(options.update).set({html: response.html}); } this.fireEvent('beforeScriptEval', {}); if (options.evalScripts && !options.evalScriptsAfterUpdate) $exec(response.javascript); this.onSuccess(response.tree, response.elements, response.html, response.javascript); }, updateMultiple: function(responseTree, responseElements, responseHtml, responseJavascript) { this.fireEvent('onResult', [this, responseHtml], 20); if (this.options.loadIndicator.hideOnSuccess) this.hideLoadIndicator(); var updated_elements = []; if (!this.options.update || this.options.update == 'multi') { this.multiupdateData = new Hash(); var pattern = />>[^<>]*<</g; var Patches = responseHtml.match(pattern); if (!Patches) return; for ( var i=0; i < Patches.length; i++ ) { var index = responseHtml.indexOf(Patches[i]) + Patches[i].length; var updateHtml = (i < Patches.length-1) ? responseHtml.slice( index, responseHtml.indexOf(Patches[i+1]) ) : responseHtml.slice(index); var updateId = Patches[i].slice(2, Patches[i].length-2); if ( $(updateId) ) { $(updateId).set({html: updateHtml}); updated_elements.push(updateId); } } } if (this.options.evalScripts && this.options.evalScriptsAfterUpdate) $exec(this.response.javascript); $A(updated_elements).each(function(element_id){ window.fireEvent('onAfterAjaxUpdate', element_id); }); this.fireEvent('onAfterUpdate', [this, responseHtml], 20); window.fireEvent('onAfterAjaxUpdateGlobal'); }, isSuccess: function(){ return !this.xhr.responseText.test("@AJAX-ERROR@"); }, hideLoadIndicator: function() { if (this.options.loadIndicator.show) $(this.options.loadIndicator.element).hideLoadingIndicator(this.loadIndicatorName); }, onFailure: function() { this.hideLoadIndicator(); var javascript = null; text = this.xhr.responseText.phprStripScripts(function(script){javascript = script;}); this.fireEvent('complete').fireEvent('failure', {message: text.replace('@AJAX-ERROR@', ''), responseText: text, responseXML: text} ); if (this.options.execScriptsOnFailure) $exec(javascript); this.fireEvent('afterError', {}); }, popupError: function(xhr) { alert(xhr.responseText.replace('@AJAX-ERROR@', '')); }, highlightError: function(xhr) { var element = null; if (this.options.errorHighlight.element != null) element = $(this.options.errorHighlight.element); else { if (this.dataObj && $type(this.dataObj) == 'element') element = $(this.dataObj).getElement('.formFlash'); } if (!element) return; element.innerHTML = ''; var pElement = new Element('p', {'class': 'error'}); pElement.innerHTML = xhr.responseText.replace('@AJAX-ERROR@', ''); pElement.inject(element, 'top'); pElement.set('morph', {duration: 'long', transition: Fx.Transitions.Sine.easeOut}); if (this.options.errorHighlight.backgroundFromColor) { pElement.morph({ 'background-color': [this.options.errorHighlight.backgroundFromColor, this.options.errorHighlight.backgroundToColor] }); } /* * Re-align popup forms */ realignPopups(); } }); Element.implement({ sendPhpr: function(handlerName, options) { var action = $(this).get('action'); var defaultOptions = {url: action, handler: handlerName, loadIndicator: {element: this}}; new Request.Phpr($merge(defaultOptions, options)).post(this); return false; } }); function popupAjaxError(xhr) { alert(xhr.responseText.replace('@AJAX-ERROR@', '').replace(/(<([^>]+)>)/ig,"")); } /* * Class mutators */ Class.Mutators.Binds = function(self, methods) { $splat(methods).each(function(method){ var fn = self[method]; self[method] = function(){ return fn.apply(self, arguments); }; }); }; /* * Element extensions */ var CHotkeySelector = new Class({ ContainerElement: null, Key: null, Modifiers: null, Function: Class.Empty, initialize: function( ContainerId, Key, Modifiers, Function ) { this.Key = Key; this.Modifiers = Modifiers; this.Function = Function; if ( $type(ContainerId) == 'string' && ContainerId.length ) this.ContainerElement = $(ContainerId); } }); Element.implement({ activeSpinners: new Hash(), keyMap: false, boundKeys: false, getForm: function() { return this.findParent('form'); }, findParent: function(tagName) { var CurrentParent = this; while (CurrentParent != null && CurrentParent != document) { if ($(CurrentParent).get('tag') == tagName) return $(CurrentParent); CurrentParent = CurrentParent.parentNode; } return null; }, selectParent: function(selector) { var CurrentParent = this; while (CurrentParent != null && CurrentParent != document) { if ($(CurrentParent).match(selector)) return $(CurrentParent); CurrentParent = CurrentParent.parentNode; } return null; }, /* * Focus handling */ focusFirst: function() { for (var el=0; el < this.elements.length; el++) { var TagName = this.elements[el].tagName; if ( (((TagName == 'INPUT' && this.elements[el].type != 'hidden')) || TagName == 'SELECT' || TagName == 'BUTTON' || TagName == 'TEXTAREA') && !this.elements[el].disabled && $(this.elements[el]).isVisible() ) { this.elements[el].focus(); break; } } return true; }, focusField: function(field) { var fieldObj = $type(field) == 'string' ? $(field) : field; if (fieldObj && !fieldObj.disabled) { window.TabManagers.some(function(manager){ return manager.findElement(fieldObj.get('id')); }); if (fieldObj.isVisible()) fieldObj.focus(); } }, safe_focus: function() { try { this.focus(); } catch (e) {} }, /* * Visibility */ hide: function() { this.addClass('hidden'); }, show: function() { this.removeClass('hidden'); }, isVisible: function() { var CurrentParent = this; while (CurrentParent != null && CurrentParent != document) { if ($(CurrentParent).hasClass('Hidden') || $(CurrentParent).hasClass('hidden')) return false; CurrentParent = CurrentParent.parentNode; } return true; }, invisible: function() { this.addClass('invisible'); }, visible: function() { this.addClass('visible'); }, /* * Loading indicators */ getLoadingIndicatorDefaults: function() { return { overlayClass: null, pos_x: 'center', pos_y: 'center', src: null, injectInElement: false, noImage: false, z_index: 9999, absolutePosition: true, injectPosition: 'bottom', overlayOpacity: 1, hideElement: true }; }, showLoadingIndicator: function(name, options) { options = $merge(this.getLoadingIndicatorDefaults(), options ? options : {}); if (!$('content')) throw "showLoadingIndicator: Element with identifier 'content' is not found."; if (options.src == null && !options.noImage) throw "showLoadingIndicator: options.src is null"; var container = options.injectInElement ? this : $('content'); var position = options.absolutePosition ? 'absolute' : 'static'; var overlayElement = null; var imageElement = null; if (options.overlayClass) overlayElement = $(document.createElement('div')).set({ 'styles': { 'visibility': 'hidden', 'position': position, 'opacity': options.overlayOpacity, 'z-index': options.z_index}, 'class': options.overlayClass }).inject(container, options.injectPosition); if (!options.noImage) { imageElement = $(document.createElement('img')).set({ 'styles': { 'visibility': 'hidden', 'position': 'absolute', 'z-index': options.z_index+1}, 'src': options.src }).inject(container, options.injectPosition); } var eS = this.getCoordinates(); if (!options.noImage) var iS = imageElement.getCoordinates(); var top = options.injectInElement ? 0 : eS.top; var left = options.injectInElement ? 0 : eS.left; if (overlayElement) { overlayElement.set({ styles:{ 'width': eS.width, 'height': eS.height, 'top': top, 'left': left, 'visibility': 'visible' } }); } if (!options.noImage) { if (iS.width == 0) { var size_str = options.src.match(/[0-9]+x[0-9]+/); if (size_str) { var dim = options.src.match(/([0-9]+)x([0-9]+)/); iS.width = dim[1]; iS.height = dim[2]; } } imageElement.set({ 'styles': { 'left': function(){ switch (options.pos_x) { case 'center' : return eS.width/2 + left - iS.width/2; case 'left': return left; case 'right': return left + eS.width - iS.width; }}(), 'top': function(){ switch (options.pos_y) { case 'center' : return eS.height/2 + top - iS.height/2; case 'top': return top; case 'bottom': return top + eS.height - iS.height; }}(), 'visibility': 'visible' } }); } if (options.hideElement) this.setStyle( 'visibility', 'hidden' ); this.activeSpinners.set( name, {spinner: imageElement, overlay: overlayElement}); }, hideLoadingIndicator: function(name) { if ( this.activeSpinners.has(name) ) { var spinner = this.activeSpinners.get(name); if (spinner.spinner) spinner.spinner.destroy(); if (spinner.overlay) spinner.overlay.destroy(); this.activeSpinners.erase(name); if (!this.activeSpinners.getKeys.length) this.setStyle( 'visibility', 'visible' ); } }, /* * Key mapping */ bindKeys: function(keyMap) { if (Browser.Engine.trident) $(document).addEvent('keydown', this.handleKeys.bindWithEvent(this, this) ); else $(window).addEvent('keydown', this.handleKeys.bindWithEvent(this, this) ); this.keyMap = keyMap; this.rebindKeyMap(); }, unBindKeys: function() { if (window.ie) $(document).removeEvent('keydown', this.handleKeys ); else $(window).removeEvent('keydown', this.handleKeys ); }, rebindKeyMap: function() { if (this.keyMap) { this.boundKeys = []; for (var key in this.keyMap) { var mapElement = key; var containerElement = ''; if (key.test(/^[a-z0-9_]+:/i)) { var Parts = key.split(':'); mapElement = Parts[1].trim(); containerElement = Parts[0].trim(); } var keySets = mapElement.split(','); keySets.each(function(keySet) { keySets = keySet.trim(); var parts = keySet.split("+"); for (var i=0; i < parts.length; i++) parts[i] = parts[i].trim(); if (parts.length) { this.boundKeys.include( new CHotkeySelector( containerElement, parts.getLast(), parts.erase(parts.getLast()), this.keyMap[key]) ); } }, this); }; }; }, handleKeys: function(event, element) { var event = new Event(event); var is_modifier_found = false; if (element.boundKeys) { element.boundKeys.each(function(selector) { if (is_modifier_found) return; if ( selector.Key == event.key ) { var container = selector.ContainerElement ? selector.ContainerElement : element; if (container.hasChild(event.target) || event.target == element) { var ModifierFound = true; selector.Modifiers.each(function(Modifier){ if ( Modifier == 'alt' && !event.alt ) ModifierFound = false; if ( Modifier == 'meta' && !event.meta ) ModifierFound = false; if ( (Modifier == 'control' || Modifier == 'ctrl') && !event.control ) ModifierFound = false; if ( Modifier == 'shift' && !event.shift ) ModifierFound = false; }); if ( ModifierFound ) { is_modifier_found = true; event.stop(); event.preventDefault(); selector.Function(event); return; } } } }); }; }, toQueryString: function(){ var queryString = []; $(this).getElements('input, select, textarea').each(function(el){ if (!el.name || el.disabled) return; var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){ return opt.value; }) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value; $splat(value).each(function(val){ if (val || el.type != 'checkbox') queryString.push(el.name + '=' + encodeURIComponent(val)); }); }); return queryString.join('&'); }, fieldsToHash: function() { var result = {}; $(this).getElements('input, select, textarea').each(function(el){ if (!el.name || el.disabled) return; var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){ return opt.value; }) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value; $splat(value).each(function(val){ if (val || el.type != 'checkbox') result[el.name] = val; }); }); return result; }, insertTextAtCursor: function(text){ if (document.selection) { this.focus(); sel = document.selection.createRange(); sel.text = text + sel.text; this.focus(); } else if (this.selectionStart || this.selectionStart == '0') { var prevScrollTop = this.scrollTop; var startPos = this.selectionStart; this.value = this.value.substring(0, startPos) + text + this.value.substring(startPos, this.value.length); this.selectionStart = startPos + text.length; this.selectionEnd = this.selectionStart; this.scrollTop = prevScrollTop; this.focus.delay(20, this); } else this.value += text; }, addTextServices: function() { this.addEvent('keydown', function(e){ if (e.code == 9) { e.stop(); this.insertTextAtCursor("\t"); } }.bind(this)); }, getOffsetsIeFixed: function(){ /* * MooTools 1.2 code replaced with MooTools 1.2.3. It correctly calculates offsets for IE. */ if (this.getBoundingClientRect){ var bound = this.getBoundingClientRect(), html = $(this.getDocument().documentElement), scroll = html.getScroll(), isFixed = (fix_styleString(this, 'position') == 'fixed'); return { x: parseInt(bound.left, 10) + ((isFixed) ? 0 : scroll.x) - html.clientLeft, y: parseInt(bound.top, 10) + ((isFixed) ? 0 : scroll.y) - html.clientTop }; } var element = this, position = {x: 0, y: 0}; if (isBody(this)) return position; while (element && !fix_isBody(element)){ position.x += element.offsetLeft; position.y += element.offsetTop; if (Browser.Engine.gecko){ if (!borderBox(element)){ position.x += leftBorder(element); position.y += topBorder(element); } var parent = element.parentNode; if (parent && styleString(parent, 'overflow') != 'visible'){ position.x += leftBorder(parent); position.y += topBorder(parent); } } else if (element != this && Browser.Engine.webkit){ position.x += fix_leftBorder(element); position.y += fix_topBorder(element); } element = element.offsetParent; } if (Browser.Engine.gecko && !borderBox(this)){ position.x -= fix_leftBorder(this); position.y -= fix_topBorder(this); } return position; }, getPositionIeFixed: function(relative){ var offset = this.getOffsetsIeFixed(), scroll = this.getScrolls(); var position = {x: offset.x - scroll.x, y: offset.y - scroll.y}; var relativePosition = (relative && (relative = $(relative))) ? relative.getPositionIeFixed() : {x: 0, y: 0}; return {x: position.x - relativePosition.x, y: position.y - relativePosition.y}; }, getCoordinatesIeFixed: function(element){ if (!Browser.Engine.trident) return this.getCoordinates(element); var position = this.getPositionIeFixed(element), size = this.getSize(); var obj = {left: position.x, top: position.y, width: size.x, height: size.y}; obj.right = obj.left + obj.width; obj.bottom = obj.top + obj.height; return obj; }, getOffsetParentIeFixed: function(){ if (!Browser.Engine.trident) return this.getOffsetParent(); var element = this; if (fix_isBody(element)) return null; if (!Browser.Engine.trident) return element.offsetParent; while ((element = element.parentNode) && !fix_isBody(element)){ if (fix_styleString(element, 'position') != 'static') return element; } return null; } }); var fix_styleString = Element.getComputedStyle; function fix_isBody(element){ return (/^(?:body|html)$/i).test(element.tagName); }; function fix_styleNumber(element, style){ return fix_styleString(element, style).toInt() || 0; }; function fix_borderBox(element){ return fix_styleString(element, '-moz-box-sizing') == 'border-box'; }; function fix_topBorder(element){ return fix_styleNumber(element, 'border-top-width'); }; function fix_leftBorder(element){ return fix_styleNumber(element, 'border-left-width'); }; function fix_isBody(element){ return (/^(?:body|html)$/i).test(element.tagName); }; function fix_getCompatElement(element){ var doc = element.getDocument(); return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; }; Element.Events.keyescape = { base: 'keyup', condition: function(e) { return e.key == 'esc'; } }; if (MooTools.version < "1.3") { Fx.implement({ step: function(){ if (!this.options.transition) { this.parent(); } else { var time = $time(); if (time < this.time + this.options.duration){ var delta = this.options.transition((time - this.time) / this.options.duration); this.set(this.compute(this.from, this.to, delta)); } else { this.set(this.compute(this.from, this.to, 1)); this.complete(); } this.fireEvent('step', this.subject); } } }); } LockManager = new Class({ locks: false, initialize: function(name){ this.locks = new Hash(); }, set: function(name) { this.locks.set(name, 1); }, get: function(name) { return this.locks.has(name); }, remove: function(name) { this.locks.erase(name); } }); lockManager = new LockManager(); /* * Manage select boxes for IE */ function hideSelects() { if (Browser.Engine.trident && Browser.Engine.version <= 4) { $(document).getElements('select').each(function(element){ element.addClass('invisible'); }); } } function showSelects() { if (Browser.Engine.trident && Browser.Engine.version <= 4) $(document).getElements('select').each(function(element){ element.removeClass('invisible'); }); } /* * Some string fixes */ String.implement({ phprStripScripts: function(option){ var scripts = ''; var text = this.replace(/<script[^>]*>([^\b]*?)<\/script>/gi, function(){ scripts += arguments[1] + '\n'; return ''; }); if (option === true) $exec(scripts); else if ($type(option) == 'function') option(scripts, text); return text; }, htmlEscape: function(){ var value = this.replace("<", "&lt;"); value = value.replace(">", "&gt;"); return value.replace('"', "&quot;"); } }); /* * Save trigger function */ function phprTriggerSave() { window.fireEvent('phprformsave'); } /* * Tab managers */ window.TabManagers = []; var TabManagerBase = new Class({ Implements: [Options, Events], tabs: [], pages: [], tabs_element: null, current_page: null, options: { trackTab: true }, initialize: function(tabs, pages, options){ this.setOptions(options); this.tabs_element = $(tabs); $(tabs).getChildren().each(function(tab){ this.tabs.push(tab); tab.addEvent('click', this.onTabClick.bindWithEvent(this, tab)); }, this); $(pages).getChildren().each(function(page){ this.pages.push(page); }, this); window.TabManagers.push(this); window.fireEvent('onTabManagerAdded', this); var tabClicked = false; if (document.location.hash && this.options.trackTab) { var hashValue = document.location.hash.substring(1); this.pages.some(function(item, index){ if (item.id == hashValue) { this.onTabClick(null, this.tabs[index]); tabClicked = true; } }, this); } if (this.tabs.length && !tabClicked) this.onTabClick(null, this.tabs[0]); }, onTabClick: function(e, tab) { if (e && !this.options.trackTab) e.stop(); var tabIndex = this.tabs.indexOf(tab); if ( tabIndex == -1 ) return; this.tabClick(tab, this.pages[tabIndex], tabIndex); this.fireEvent('onTabClick', [this.tabs[tabIndex], this.pages[tabIndex]]); this.pages[tabIndex].fireEvent('onTabClick'); this.tabs[tabIndex].fireEvent('onTabClick'); this.current_page = this.pages[tabIndex]; realignPopups(); return false; }, tabClick: function(tab, page, tabIndex) { return null; }, findElement: function(elementId) { for (var i = 0; i < this.pages.length; i++) { var el = this.pages[i].getElement('#'+elementId); if (el) { this.onTabClick(null, this.tabs[i]); return true; } } return false; } }); Element.implement({ getTab: function() { var CurrentParent = this; while (CurrentParent != null && CurrentParent != document) { CurrentParent = $(CurrentParent); if (CurrentParent.get('tag') == 'li' && CurrentParent.parentNode !== null && $(CurrentParent.parentNode).hasClass('tabs_pages')) return $(CurrentParent); CurrentParent = CurrentParent.parentNode; } return null; } }); window.phprErrorField = null; /* * Edit area functions */ var phpr_field_initialized = new Hash(); var phpr_field_loaded = new Hash(); var phpr_active_code_editor = null; var phpr_code_editors = []; function init_code_editor(field_id, language, options) { return new AceWrapper(field_id, language, options); } function find_code_editor(field_id) { var result = phpr_code_editors.filter(function(obj){ if (obj.id == field_id) return obj; }); if (result.length) return result[0].editor; return null; } /* * Search control */ var SearchControlHandler = new Class({ Implements: [Options, Events], search_element: null, input_element: null, cancel_element: null, options: { default_text: 'search' }, initialize: function(search_element, options){ this.setOptions(options); this.search_element = $(search_element); this.input_element = this.search_element.getElement('input'); this.cancel_element = this.search_element.getElement('span.right'); this.input_element.addEvent('click', this.onFieldClick.bind(this)); this.cancel_element.addEvent('click', this.onCancelClick.bind(this)); this.input_element.addEvent('keydown', this.onFieldKeyDown.bind(this)); }, onFieldClick: function() { if (this.search_element.hasClass('inactive')) { this.search_element.removeClass('inactive'); this.input_element.set('value', ''); } }, onFieldKeyDown: function(event) { if (event.key == 'enter') { if (!this.input_element.value.trim().length) this.forceCancel(event); else this.fireEvent('send'); } else if (event.key == 'esc') this.forceCancel(event); }, forceCancel: function(event) { this.onCancelClick(); this.input_element.set('value', this.options.default_text); this.input_element.blur(); event.stop(); }, onCancelClick: function() { if (this.search_element.hasClass('inactive')) return; this.search_element.addClass('inactive'); this.input_element.set('value', this.options.default_text); this.fireEvent('cancel'); } }); /* * Collapsabele form areas */ function phpr_update_collapsible_status(trigger) { var parent = $(trigger).selectParent('div.form-collapsible-area'); if (parent.hasClass('collapsed')) { parent.removeClass('collapsed'); $(trigger).set('title', 'Hide'); } else { parent.addClass('collapsed'); $(trigger).set('title', 'Show'); } window.fireEvent('phpr_form_collapsible_updated'); } /* * Widgets framework */ function phpr_dispatch_widget_response_data(data) { jQuery(window).trigger('phpr_widget_response_data', data); } /* * MooTools 1.1 sortables */ var Sortables11 = new Class({ is_in_popup: false, options: { handles: false, onStart: Class.empty, onComplete: Class.empty, ghost: true, snap: 3, startDelay: 0, onDragStart: function(element, ghost){ ghost.setStyle('opacity', 0.7); element.setStyle('opacity', 0.7); }, onDragComplete: function(element, ghost){ element.setStyle('opacity', 1); ghost.destroy(); this.trash.destroy(); } }, initialize: function(list, options){ this.setOptions(options); this.list = $(list); this.elements = this.list.getChildren(); this.handles = (this.options.handles) ? $$(this.options.handles) : this.elements; this.bound = { 'start': [], 'moveGhost': this.moveGhost.bindWithEvent(this) }; for (var i = 0, l = this.handles.length; i < l; i++){ this.bound.start[i] = this.start.bindWithEvent(this, this.elements[i]); } this.attach(); if (this.options.initialize) this.options.initialize.call(this); this.bound.move = this.move.bindWithEvent(this); this.bound.end = this.end.bind(this); this.is_in_popup = this.list.selectParent('.popupForm'); }, attach: function(){ this.handles.each(function(handle, i){ handle.addEvent('mousedown', this.bound.start[i]); }, this); }, detach: function(){ this.handles.each(function(handle, i){ handle.removeEvent('mousedown', this.bound.start[i]); }, this); }, start_delayed: function(event, el) { this.active = el; this.coordinates = this.list.getCoordinates(); if (this.options.ghost){ var position = el.getPosition(); this.offset = event.page.y - position.y; this.trash = new Element('div').inject(document.body); this.ghost = el.clone().inject(this.trash).setStyles({ 'position': 'absolute', 'left': position.x, 'top': event.page.y - this.offset }); document.addEvent('mousemove', this.bound.moveGhost); this.fireEvent('onDragStart', [el, this.ghost]); } document.addEvent('mousemove', this.bound.move); document.addEvent('mouseup', this.bound.end); this.fireEvent('onStart', el); event.stop(); }, start: function(event, el){ if (!this.options.startDelay) this.start_delayed(event, el); else { var timer_d = this.start_delayed.delay(100, this, [event, el]); document.addEvent('mouseup', function(){ $clear(timer_d); }); } }, moveGhost: function(event){ var value = event.page.y - this.offset; value = value.limit(this.coordinates.top, this.coordinates.bottom - this.ghost.offsetHeight); this.ghost.setStyle('top', value); event.stop(); }, move: function(event){ this.active.active = true; this.previous = this.previous || event.page.y; this.now = event.page.y; var direction = ((this.previous - this.now) <= 0) ? 'down' : 'up'; var prev = this.active.getPrevious(); var next = this.active.getNext(); var scroll_tweak = this.is_in_popup ? window.getScroll().y : 0; var scroll = window.getScroll(); if (prev && direction == 'up'){ var prevPos = prev.getCoordinates(); if (event.page.y < (prevPos.bottom + scroll_tweak)) this.active.injectBefore(prev); } if (next && direction == 'down'){ var nextPos = next.getCoordinates(); if (event.page.y > (nextPos.top + scroll_tweak)) this.active.injectAfter(next); } this.previous = event.page.y; }, serialize: function(){ var serial = []; this.list.getChildren().each(function(el, i){ serial[i] = this.elements.indexOf(el); }, this); return serial; }, end: function(){ this.previous = null; document.removeEvent('mousemove', this.bound.move); document.removeEvent('mouseup', this.bound.end); if (this.options.ghost){ document.removeEvent('mousemove', this.bound.moveGhost); this.fireEvent('onDragComplete', [this.active, this.ghost]); } this.fireEvent('onComplete', this.active); } }); Sortables11.implement(new Events, new Options); /* * Sortable lists */ Element.implement({ makeListSortable: function(server_handler, sort_order_class, item_id_class, item_handle_class, extra_fields) { var sortable_list = this; var sortable_list_orders = []; var order_class = $type(sort_order_class) == false ? 'SortOrder' : sort_order_class; var id_class = $type(item_id_class) == false ? 'ItemId' : item_id_class; var handle_class = $type(item_handle_class) == false ? 'VerticalMove' : item_handle_class; $(this).getElements('input.'+order_class, $(this)).each(function(element){ sortable_list_orders.push(element.value); }, this); extra_fields = extra_fields || {}; new Sortables11($(this), { handles: $(this).getElements('.'+handle_class), onDragStart: function(element, ghost){ ghost.destroy(); element.addClass('drag'); }, onDragComplete: function(element, ghost){ element.removeClass('drag'); this.trash.destroy(); sortable_list.postListItemsOrder(server_handler, sortable_list_orders, id_class, extra_fields); element.getParent().fireEvent('dragComplete', [sortable_list_orders]); } }); }, postListItemsOrder: function(server_handler, sortable_list_orders, id_class, extra_fields) { var ids = []; $(this).getElements('input.'+id_class).each(function(element){ ids.push(element.value); }); var post_fields = $merge({ item_ids: ids.join(','), sort_orders: sortable_list_orders.join(',')}, extra_fields ); $(this).getForm().sendPhpr(server_handler, { extraFields: post_fields, loadIndicator: {show: false}, update: 'multi', onResult: function(param1, param2){ this.fireEvent('sortableServerResponse', [param2]); }.bind(this) } ); return false; } }); /* * Date and date range picker */ var DateRangePicker = new Class({ Implements: [Options, Events], Binds: ['cancel', 'show'], options: { type: 'single', displayTrigger: null, displayElement: null, typeDisplayElement: null, typeHiddenElement: null, rangesHiddenElement: null, inputs: [], intYears: [], intMonths: [] }, activeType: null, types: null, initialize: function(options) { this.setOptions(options); if (this.options.type == 'single') this.build(); else { window.addEvent('domready', this.build.bind(this)); this.types = { day: {name: 'Day'}, month: {name: 'Month', range: this.options.intMonths}, year: {name: 'Year', range: this.options.intYears} }; } if (!this.options.displayTrigger) { if (this.options.type == 'single') $(this.options.inputs[0]).addEvent('click', this.show); } else $(this.options.displayTrigger).addEvent('click', this.show); }, cancel: function() { $(document).removeEvent('click', this.cancel); $(document).removeEvent('keyescape', this.cancel); if (!Browser.Engine.trident) this.slideFx.slideOut().chain(this.hideContainer.bind(this)); else { this.slideFx.hide(); this.hideContainer(); } window.fireEvent('datePickerHide'); if (this.options.type == 'single') showSelects(); }, hideContainer: function() { this.container.setStyle('visibility', 'hidden'); }, build: function() { this.container = new Element('div', { 'class': 'datePickerWrapper' }).inject(this.options.inputs[0], 'after'); this.slide = new Element('div', { 'class': 'datePickerSliderConainer '+this.options.type }).inject(this.container, 'top'); this.pickerPanel = new Element('div', {'class': 'picker_panel day_panel'}).inject(this.slide, 'top'); this.slideFx = new Fx.Slide(this.slide, {'duration': 250}); this.slideFx.hide(); var pickerOptions = { flat: true, starts: 1 }; pickerOptions = $merge(pickerOptions, this.options); if (this.options.type == 'single') pickerOptions.onDayClick = this.onSetDate.bind(this); else { pickerOptions.calendars = 2; pickerOptions.mode = 'range'; } this.picker = jQuery(this.pickerPanel).DatePicker(pickerOptions); /* * Inject OK button to the control */ if (this.options.type != 'single') { this.typeSelectorPanel = new Element('div', {'class': 'type_selector'}).inject(this.slide, 'top'); this.typeSelectorPanel.innerHTML = '<h5>Interval</h5>'; var ranges = this.parseRanges(); for (var key in this.types){ if (key == 'day' || this.types[key].range.length) { var p = new Element('p').inject(this.typeSelectorPanel, 'bottom'); var a = new Element('a', {'class': key, 'href': '#'}).inject(p, 'bottom'); a.innerHTML = this.types[key].name; if (key != 'day') { var rangeStart = ranges ? ranges[key][0] : null; var rangeEnd = ranges ? ranges[key][1] : null; var panel = new Element('div', {'class': 'picker_panel hidden '+key+'_panel'}).inject(this.slide, 'bottom'); var from_label = new Element('label').inject(panel, 'bottom'); from_label.innerHTML = this.types[key].name+', from'; var selectStart = new Element('select', {'class': 'start no-styling'}).inject(panel, 'bottom'); this.popupateRange(selectStart, this.types[key].range, 1, rangeStart); var to_label = new Element('label', {'class': 'to'}).inject(panel, 'bottom'); to_label.innerHTML = 'to'; var selectEnd = new Element('select', {'class': 'end no-styling'}).inject(panel, 'bottom'); this.popupateRange(selectEnd, this.types[key].range, 2, rangeEnd); } a.addEvent('click', this.switchIntervalType.bind(this, [key])); } } new Element('div', {'class': 'clear'}).inject(this.slide, 'bottom'); this.controlPanel = new Element('div', {'class': 'control_panel'}).inject(this.slide, 'bottom'); this.cancelBtn = new Element('a', { 'class': 'calendar_button last', 'href': '#' }).inject(this.controlPanel, 'bottom'); this.cancelBtn.innerHTML = 'Cancel'; this.cancelBtn.addEvent('click', function(){this.cancel(); return false;}.bind(this)); this.okBtn = new Element('a', { 'class': 'calendar_button', 'href': '#' }).inject(this.controlPanel, 'bottom'); this.okBtn.innerHTML = 'OK'; this.okBtn.addEvent('click', this.setDateRange.bind(this)); new Element('div', {'class': 'clear'}).inject(this.controlPanel, 'bottom'); } var containerCoords = this.container.getCoordinates(); if (containerCoords.left < 0) this.container.setStyle('right', containerCoords.left); this.container.setStyle('visibility', 'hidden'); }, parseRanges: function() { if (!this.options.rangesHiddenElement) return false; var value = $(this.options.rangesHiddenElement).value; if (!value.length) return false; var result = {}; value.split(',').each(function(typeRange){ if (typeRange.length) { var typePairs = typeRange.split(':'); var rangeDates = typePairs[1].split('-'); var key = typePairs[0]; result[key] = [rangeDates[0], rangeDates[1]]; } }); return result; }, switchIntervalType: function(key) { this.slide.getElements('.picker_panel').each(function(element){element.hide()}); this.slide.getElement('.'+key+'_panel').show(); this.typeSelectorPanel.getElements('a').each(function(element){element.removeClass('current')}); this.typeSelectorPanel.getElement('a.'+key).addClass('current'); this.activeType = key; return false; }, onSetDate: function(formated, dates) { $(this.options.inputs[0]).value = formated; if($(this.options.inputs[0]).onchange) $(this.options.inputs[0]).onchange(); this.cancel(); }, popupateRange: function(element, range, type, value) { range.each(function(range_element){ var opt = new Element('option', {'value': range_element[type]}).inject(element, 'bottom'); opt.innerHTML = range_element[0]; }); if (value) { $A(element.options).some(function(option){ if (option.value == value) { option.selected = true; return true; } return false; }); } }, setDateRange: function() { var startDate = null; var endDate = null; if (this.activeType != 'day') { var panel = this.getActivePanel(); var startIndex = this.getOptionIndex(panel, 'start'); var endIndex = this.getOptionIndex(panel, 'end'); if (startIndex > endIndex) { alert('Interval start date must be less or equal the interval end date.'); return false; } startDate = this.getOptionValue(panel, 'start'); endDate = this.getOptionValue(panel, 'end'); } if (this.options.displayElement) { if (this.activeType == 'day') { var d1_text = this.picker.DatePickerGetDate(true)[0]; var d2_text = this.picker.DatePickerGetDate(true)[1]; var display_text = (d1_text == d2_text) ? d1_text : d1_text + ' - ' + d2_text; this.options.displayElement.innerHTML = display_text; if (this.options.typeDisplayElement) { var display_type = (d1_text == d2_text) ? 'Date' : 'Interval'; this.options.typeDisplayElement.innerHTML = display_type; } } else { var display_text = startDate + ' - ' + endDate; this.options.displayElement.innerHTML = display_text; this.options.typeDisplayElement.innerHTML = 'Interval'; } $(this.options.typeHiddenElement).value = this.activeType; } if (this.options.rangesHiddenElement) { var ranges_value = ''; for (var key in this.types) { if (key != 'day' && this.types[key].range.length) { var panel = this.slide.getElement('.'+key+'_panel'); var start = this.getOptionValue(panel, 'start'); var end = this.getOptionValue(panel, 'end'); ranges_value += key + ':' + start + '-' + end + ','; } } $(this.options.rangesHiddenElement).set('value', ranges_value); } if (this.activeType == 'day') { startDate = this.picker.DatePickerGetDate(true)[0]; endDate = this.picker.DatePickerGetDate(true)[1]; } this.options.inputs[0].set('value', startDate); this.options.inputs[1].set('value', endDate); this.fireEvent('setRange', [startDate, endDate]); this.cancel(); return false; }, getActivePanel: function() { return this.slide.getElement('.'+this.activeType+'_panel'); }, getOptionIndex: function(panel, controlClass) { var select = panel.getElement('select.'+controlClass) var indexFound = -1; $A(select.options).some(function(item, index){ indexFound = index; return item.selected ? true : false; }); return indexFound; }, getOptionValue: function(panel, controlClass) { var select = panel.getElement('select.'+controlClass) return select.get('value'); }, show: function() { if (this.options.type == 'single') hideSelects(); if (this.options.type == 'single') this.picker.DatePickerSetDate($(this.options.inputs[0]).get('value'), true); else { this.activeType = $(this.options.typeHiddenElement).value; var dates = [ $(this.options.inputs[0]).value, $(this.options.inputs[1]).value ]; this.picker.DatePickerSetDate(dates, true); this.switchIntervalType(this.activeType); } this.container.setStyle('visibility', 'visible'); if (!Browser.Engine.trident) this.slideFx.slideIn().chain(this.attachEvents.bind(this)); else { this.slideFx.show(); this.attachEvents(); } window.fireEvent('datePickerDisplay'); return false; }, attachEvents: function() { if (this.options.type == 'single') $(document).addEvent('click', this.cancel); $(document).addEvent('keyescape', this.cancel); } }); /* * Scroller controls */ var BackendVScroller = new Class({ Implements: [Options, Events], element: null, knob: null, element_fx_scroll: null, slider_fx: null, slider: null, bound_mouse_up: null, options: { slider_height_tweak: 0, auto_hide_slider: false, position_threshold: 8 }, initialize: function(element, options) { this.setOptions(options); this.element = $(element); this.element_fx_scroll = new Fx.Scroll(this.element); /* * Build the slider */ var element_size = this.element.getSize(); var scroll_container = new Element('div', {'class': 'backend_scroller_container'}).inject(element, 'before'); this.element.inject(scroll_container); var element_scroll_size = this.element.getScrollSize(); this.slider = new Element('div', {'class': 'v_slider'}).inject(scroll_container); this.slider.setStyle('height', (element_size.y + this.options.slider_height_tweak) + 'px'); var effective_scroll_size = element_scroll_size.y - element_size.y; var knob = new Element('div', {'class': 'knob'}).inject(this.slider); if (effective_scroll_size <= 0) { knob.addClass('invisible'); this.element.removeClass('scroll_enabled'); if (this.options.auto_hide_slider) this.slider.addClass('invisible'); } else this.element.addClass('scroll_enabled'); this.bound_mouse_up = this.mouse_release.bind(this); this.knob = knob; this.knob.addEvent('mousedown', function(){ this.slider.addClass('active'); window.addEvent('mouseup', this.bound_mouse_up); this.bound_mouse_up }.bind(this)); this.init_slider_fx(); }, init_slider_fx: function() { this.slider_fx = new Slider(this.slider, this.knob, { steps: 1000, range: [0, 1000], mode: 'vertical', wheel: true, onChange: function(step){ var effective_scroll_size = this.element.getScrollSize().y - this.element.getSize().y; this.element_fx_scroll.set(0, Math.ceil(effective_scroll_size*step/1000)); jQuery(this.element).trigger('onScroll'); }.bind(this) }); this.element.addEvent('mousewheel', this.mouse_scroll.bindWithEvent(this)); }, mouse_release: function() { this.slider.removeClass('active'); window.removeEvent('mouseup', this.bound_mouse_up); }, mouse_scroll: function(event) { var ev = jQuery.Event("onBeforeWheel"); jQuery(this.element).trigger(ev); if (ev.isDefaultPrevented()) return; var mode = (this.slider_fx.options.mode == 'horizontal') ? (event.wheel < 0) : (event.wheel > 0); if ($(document.body).hasClass('chrome')) { event.wheel = event.wheel < 0 ? -1 : 1; } var step_size = Math.round(event.wheel*20*1000/this.element.getScrollSize().y); var position = this.slider_fx.step - step_size; if (this.last_position === undefined || this.last_position == position) { this.slider_fx.set(position); jQuery(this.element).trigger('onScroll'); } this.last_position == position; event.stop(); }, update: function(position) { var element_size = this.element.getSize(); var element_scroll_size = this.element.getScrollSize(); var effective_scroll_size = element_scroll_size.y - element_size.y; if (effective_scroll_size <= 0) { this.knob.addClass('invisible'); this.element.removeClass('scroll_enabled'); this.slider_fx.set(0); if (this.options.auto_hide_slider) this.slider.addClass('invisible'); } else { this.knob.removeClass('invisible'); this.element.addClass('scroll_enabled'); if (this.options.auto_hide_slider) this.slider.removeClass('invisible'); } if (this.element.scrollTop + element_size.y > element_scroll_size.y || (position !== undefined && position == 'bottom')) { this.slider_fx.set(1000); this.element_fx_scroll.toBottom(); } else { if (this.slider_fx.step == 1000 && (element_scroll_size.y > this.element.scrollTop + element_size.y)) { this.slider_fx.set(1000); this.element_fx_scroll.toBottom(); } } }, update_position: function(position) { var element_size = this.element.getSize(); var element_scroll_size = this.element.getScrollSize(); var max = element_scroll_size.y - element_size.y; var new_position = position === undefined ? this.element.scrollTop : position; if (new_position <= this.options.position_threshold) this.slider_fx.set(0); else if (max - new_position <= this.options.position_threshold) this.slider_fx.set(1000); else this.slider_fx.set(Math.floor(new_position/max*1000)); } });
JavaScript
/* * Popup modal windows */ var Overlay = new Class({ Implements: [Options, Events], options: { opacity: 0.1, className: 'overlay', background: '', zIndex: 1600, closeByClick: false, autoCenter: true }, initialize: function(options) { this.setOptions(options); this.overlay = null; this.listeners = { resize: this.resize.bind(this), click: this.click.bind(this) }; }, toggleListeners: function(state) { var task = state ? 'addEvent' : 'removeEvent'; window[task]('resize', this.listeners.resize); if (this.options.autoCenter) window[task]('scroll', this.listeners.resize); }, build: function() { if (!this.overlay) { this.overlay = new Element('div', { 'class': this.options.className, 'styles': { 'position': 'fixed', 'left': 0, 'top': 0, 'width': 1, 'height': 1, 'padding': 0, 'margin': 0, 'opacity': 0, 'visibility': 'hidden', 'z-index': this.options.zIndex } }).inject(document.body, 'top').addClass('ui-overlay'); if (this.options.background != '') this.overlay.setStyle('background', this.options.background); this.overlay.addEvent('click', this.listeners.click); this.overlay.addEvent('mouseup', function(event) { new Event(event).stop(); } ); } }, resize: function() { this.fireEvent('resize'); if (this.overlay) { var sizes = { scroll: window.getScroll(), scrollSize: window.getScrollSize(), size: window.getSize() } if (Browser.Engine.trident) { this.overlay.setStyles({ 'left': sizes.scroll.x, 'top': sizes.scroll.y }); } this.overlay.setStyles({ 'width': sizes.size.x, 'height': sizes.size.y }); } }, show: function() { if (this.overlay && this.overlay.getStyle('visibility') != 'hidden') return; this.fireEvent('show'); this.build(); if (this.overlay) { this.resize(); this.toggleListeners(true); this.overlay.setStyle('visibility', 'visible').set('tween', {duration: 250}).tween('opacity', this.options.opacity); } }, hide: function() { if (!this.overlay || this.overlay.getStyle('visibility') == 'hidden') return; this.fireEvent('hide'); if (this.overlay) { this.toggleListeners(false); this.overlay.set('tween', { duration: 250, onComplete: function() { this.overlay.setStyles({ 'visibility': 'hidden', 'left': 0, 'top': 0, 'width': 0, 'height': 0 }); }.bind(this) }).tween('opacity', 0); } }, click: function() { this.fireEvent('click'); if (this.options.closeByClick) { this.fireEvent('close'); this.hide(); } }, destroy: function() { if (!this.overlay) return; this.toggleListeners(false); this.overlay.removeEvent('click', this.listeners.click); this.overlay.destroy(); this.overlay = null; } }); PopupForm = new Class({ Implements: [Options, Events], Binds: ['cancel', 'cancelByKey'], formLoadHandler: null, overlay: null, formContainer: null, tmp: null, lockName: false, options: { opacity: 0.1, className: 'popupForm', background: '', zIndex: 1601, closeByClick: false, ajaxFields: {}, closeByEsc: true, popupData: {}, autoCenter: true }, initialize: function(formLoadHandler, options) { var lockName = 'poppup' + formLoadHandler; if (lockManager.get(lockName)) return; lockManager.set(lockName); this.lockName = lockName; this.setOptions(options); this.formLoadHandler = formLoadHandler; this.show(); window.PopupWindows.push(this); }, show: function() { this.overlay = new Overlay({ onClose: cancelPopup, onResize: this.alignForm.bind(this), closeByClick: this.options.closeByClick, zIndex: 1601 + window.PopupWindows.length + 1, autoCenter: this.options.autoCenter }); addPopup(); this.overlay.show(); this.formContainer = new Element('div', { 'class': 'popupLoading', 'styles': { 'position': 'absolute', 'visibility': 'hidden', 'z-index': this.options.zIndex + window.PopupWindows.length + 1, 'padding': '10px' } }).inject($('content'), 'top'); this.tmp = new Element('div', {'styles': {'visibility': 'hidden', 'position': 'absolute'}}).inject($('content'), 'top'); new Element('div', {'class': 'popupForm'}).inject(this.tmp, 'top'); this.alignForm(); this.formContainer.setStyle( 'visibility', 'visible' ); if (this.options.closeByEsc) $(document).addEvent('keydown', this.cancelByKey); new Request.Phpr({url: location.pathname, handler: this.formLoadHandler, extraFields: this.options.ajaxFields, update: this.tmp.getFirst(), loadIndicator: {show: false}, onSuccess: this.formLoaded.bind(this)}).post({phpr_popup_form_request: 1}); }, cancelByKey: function(event) { if (event.key == 'esc') { this.cancel(); event.stop(); } }, cancel: function() { var allow_close = true; try { var first_element = this.formContainer.getFirst(); if (first_element) { var top_element = first_element.getFirst(); if (top_element) { try { top_element.fireEvent('onClosePopup'); } catch (e) { allow_close = false; } } } } catch (e) {} if (allow_close) { this.destroy(); $(document).removeEvent('keydown', this.cancelByKey); return false; } }, formLoaded: function() { var newSize = this.tmp.getSize(); var myEffect = new Fx.Morph(this.formContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut, onStep: this.alignForm.bind(this), onComplete: this.loadComplete.bind(this)}); myEffect.start({ 'height': newSize.y, 'width': newSize.x+1 }); }, loadComplete: function() { var first = this.tmp.getFirst(); if(first) this.tmp.getFirst().inject(this.formContainer); this.tmp.destroy(); this.formContainer.removeClass('popupLoading'); this.formContainer.setStyles({'width': 'auto', 'height': 'auto'}); var top_element = this.formContainer.getFirst().getFirst(); if (top_element) { top_element.fireEvent('popupLoaded'); window.fireEvent('popupLoaded', top_element); top_element.addClass('popup_content'); top_element.popupData = this.options.popupData; var a = new Element('a', {'class': 'popup_close', 'title': 'Close'}); a.innerHTML = 'Close'; a.href = '#'; a.addEvent('click', function(){ cancelPopup(); return false; }); a.inject(top_element, 'top'); } }, alignForm: function() { if (!this.formContainer) return; var windowSize = window.getSize(); var formSize = this.formContainer.getSize(); var scroll = window.getScroll(); if (!Browser.Engine.trident) { var top = 0; if (formSize.y > windowSize.y) top = Math.round(windowSize.y/2-formSize.y/2); else top = Math.round(scroll.y + windowSize.y/2-formSize.y/2); var left = Math.round(windowSize.x/2-formSize.x/2); } else { var scrollSize = window.getScrollSize(); var top = Math.round(scroll.y + windowSize.y/2-formSize.y/2); var left = Math.round(windowSize.x/2-formSize.x/2); } if(top < 0) top = 0; if(left < 0) left = 0; var contentContainer = this.formContainer.getElements('.content'); var popupContent = this.formContainer.getElements('.popup_content'); /* if(contentContainer && popupContent) { var popupSize = popupContent.getSize()[0]; var contentOffset = contentContainer.getOffsets()[0]; if(popupSize && contentOffset) { var offset = formSize.y - popupSize.y + contentOffset.y; if(formSize.y > windowSize.y) { contentContainer.setStyles({ 'overflow-y': 'scroll', 'height': windowSize.y - offset }); } else { contentContainer.setStyles({ 'overflow-y': 'hidden', 'height': 'auto' }); } } } */ this.formContainer.setStyles({ 'left': left, 'top': top }); }, destroy: function() { hide_tooltips(); lockManager.remove(this.lockName); this.overlay.destroy(); this.formContainer.destroy(); window.PopupWindows.pop(); } }); window.PopupWindows = []; function cancelPopup() { if (window.PopupWindows.length) window.PopupWindows.getLast().cancel(); if (!window.PopupWindows.length) window.fireEvent('popupHide'); return false; } function cancelPopups() { while (window.PopupWindows.length) cancelPopup(); } function addPopup() { if (window.PopupWindows.length == 0) window.fireEvent('popupDisplay'); } function realignPopups() { window.PopupWindows.each(function(popup){popup.alignForm()}); }
JavaScript
/* Script: Moo.js My Object Oriented javascript. Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. Mootools Credits: - Class is slightly based on Base.js <http://dean.edwards.name/weblog/2006/03/base/> (c) 2006 Dean Edwards, License <http://creativecommons.org/licenses/LGPL/2.1/> - Some functions are based on those found in prototype.js <http://prototype.conio.net/> (c) 2005 Sam Stephenson sam [at] conio [dot] net, MIT-style license - Documentation by Aaron Newton (aaron.newton [at] cnet [dot] com) and Valerio Proietti. */ /* Class: Class The base class object of the <http://mootools.net> framework. Arguments: properties - the collection of properties that apply to the class. Creates a new class, its initialize method will fire upon class instantiation. Example: (start code) var Cat = new Class({ initialize: function(name){ this.name = name; } }); var myCat = new Cat('Micia'); alert myCat.name; //alerts 'Micia' (end) */ var Class = function(properties){ var klass = function(){ if (this.initialize && arguments[0] != 'noinit') return this.initialize.apply(this, arguments); else return this; }; for (var property in this) klass[property] = this[property]; klass.prototype = properties; return klass; }; /* Property: empty Returns an empty function */ Class.empty = function(){}; Class.prototype = { /* Property: extend Returns the copy of the Class extended with the passed in properties. Arguments: properties - the properties to add to the base class in this new Class. Example: (start code) var Animal = new Class({ initialize: function(age){ this.age = age; } }); var Cat = Animal.extend({ initialize: function(name, age){ this.parent(age); //will call the previous initialize; this.name = name; } }); var myCat = new Cat('Micia', 20); alert myCat.name; //alerts 'Micia' alert myCat.age; //alerts 20 (end) */ extend: function(properties){ var pr0t0typ3 = new this('noinit'); var parentize = function(previous, current){ if (!previous.apply || !current.apply) return false; return function(){ this.parent = previous; return current.apply(this, arguments); }; }; for (var property in properties){ var previous = pr0t0typ3[property]; var current = properties[property]; if (previous && previous != current) current = parentize(previous, current) || current; pr0t0typ3[property] = current; } return new Class(pr0t0typ3); }, /* Property: implement Implements the passed in properties to the base Class prototypes, altering the base class, unlike <Class.extend>. Arguments: properties - the properties to add to the base class. Example: (start code) var Animal = new Class({ initialize: function(age){ this.age = age; } }); Animal.implement({ setName: function(name){ this.name = name } }); var myAnimal = new Animal(20); myAnimal.setName('Micia'); alert(myAnimal.name); //alerts 'Micia' (end) */ implement: function(properties){ for (var property in properties) this.prototype[property] = properties[property]; } }; /* Section: Object related Functions */ /* Function: Object.extend Copies all the properties from the second passed object to the first passed Object. If you do myWhatever.extend = Object.extend the first parameter will become myWhatever, and your extend function will only need one parameter. Example: (start code) var firstOb = { 'name': 'John', 'lastName': 'Doe' }; var secondOb = { 'age': '20', 'sex': 'male', 'lastName': 'Dorian' }; Object.extend(firstOb, secondOb); //firstOb will become: { 'name': 'John', 'lastName': 'Dorian', 'age': '20', 'sex': 'male' }; (end) Returns: The first object, extended. */ var $extend = Object.extend = function(){ var args = arguments; args = (args[1]) ? [args[0], args[1]] : [this, args[0]]; for (var property in args[1]) args[0][property] = args[1][property]; return args[0]; }; /* Function: Object.Native Will add a .extend method to the objects passed as a parameter, equivalent to <Class.implement> Arguments: a number of classes/native javascript objects */ Object.Native = function(){ for (var i = 0; i < arguments.length; i++) arguments[i].extend = Class.prototype.implement; }; new Object.Native(Function, Array, String, Number, Class); /* Script: Utility.js Contains Utility functions Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ //htmlelement if (typeof HTMLElement == 'undefined'){ var HTMLElement = Class.empty; HTMLElement.prototype = {}; } else { HTMLElement.prototype.htmlElement = true; } //window, document window.extend = document.extend = Object.extend; var Window = window; /* Function: $type Returns the type of object that matches the element passed in. Arguments: obj - the object to inspect. Example: >var myString = 'hello'; >$type(myString); //returns "string" Returns: 'element' - if obj is a DOM element node 'textnode' - if obj is a DOM text node 'whitespace' - if obj is a DOM whitespace node 'array' - if obj is an array 'object' - if obj is an object 'string' - if obj is a string 'number' - if obj is a number 'boolean' - if obj is a boolean 'function' - if obj is a function false - (boolean) if the object is not defined or none of the above. */ function $type(obj){ if (obj === null || obj === undefined) return false; var type = typeof obj; if (type == 'object'){ if (obj.htmlElement) return 'element'; if (obj.push) return 'array'; if (obj.nodeName){ switch (obj.nodeType){ case 1: return 'element'; case 3: return obj.nodeValue.test(/\S/) ? 'textnode' : 'whitespace'; } } } return type; }; /* Function: $chk Returns true if the passed in value/object exists or is 0, otherwise returns false. Useful to accept zeroes. */ function $chk(obj){ return !!(obj || obj === 0); }; /* Function: $pick Returns the first object if defined, otherwise returns the second. */ function $pick(obj, picked){ return ($type(obj)) ? obj : picked; }; /* Function: $random Returns a random integer number between the two passed in values. Arguments: min - integer, the minimum value (inclusive). max - integer, the maximum value (inclusive). Returns: a random integer between min and max. */ function $random(min, max){ return Math.floor(Math.random() * (max - min + 1) + min); }; /* Function: $clear clears a timeout or an Interval. Returns: null Arguments: timer - the setInterval or setTimeout to clear. Example: >var myTimer = myFunction.delay(5000); //wait 5 seconds and execute my function. >myTimer = $clear(myTimer); //nevermind See also: <Function.delay>, <Function.periodical> */ function $clear(timer){ clearTimeout(timer); clearInterval(timer); return null; }; /* Class: window Some properties are attached to the window object by the browser detection. Properties: window.ie - will be set to true if the current browser is internet explorer (any). window.ie6 - will be set to true if the current browser is internet explorer 6. window.ie7 - will be set to true if the current browser is internet explorer 7. window.khtml - will be set to true if the current browser is Safari/Konqueror. window.gecko - will be set to true if the current browser is Mozilla/Gecko. */ if (window.ActiveXObject) window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true; else if (document.childNodes && !document.all && !navigator.taintEnabled) window.khtml = true; else if (document.getBoxObjectFor != null) window.gecko = true; //enables background image cache for internet explorer 6 if (window.ie6) try {document.execCommand("BackgroundImageCache", false, true);} catch (e){}; /* Script: Array.js Contains Array prototypes, <$A>, <$each> Authors: - Christophe Beyls, <http://digitalia.be> - Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Array A collection of The Array Object prototype methods. */ //emulated methods /* Property: forEach Iterates through an array; This method is only available for browsers without native *forEach* support. For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:forEach> */ Array.prototype.forEach = Array.prototype.forEach || function(fn, bind){ for (var i = 0; i < this.length; i++) fn.call(bind, this[i], i, this); }; /* Property: filter This method is provided only for browsers without native *filter* support. For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:filter> */ Array.prototype.filter = Array.prototype.filter || function(fn, bind){ var results = []; for (var i = 0; i < this.length; i++){ if (fn.call(bind, this[i], i, this)) results.push(this[i]); } return results; }; /* Property: map This method is provided only for browsers without native *map* support. For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:map> */ Array.prototype.map = Array.prototype.map || function(fn, bind){ var results = []; for (var i = 0; i < this.length; i++) results[i] = fn.call(bind, this[i], i, this); return results; }; /* Property: every This method is provided only for browsers without native *every* support. For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:every> */ Array.prototype.every = Array.prototype.every || function(fn, bind){ for (var i = 0; i < this.length; i++){ if (!fn.call(bind, this[i], i, this)) return false; } return true; }; /* Property: some This method is provided only for browsers without native *some* support. For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:some> */ Array.prototype.some = Array.prototype.some || function(fn, bind){ for (var i = 0; i < this.length; i++){ if (fn.call(bind, this[i], i, this)) return true; } return false; }; /* Property: indexOf This method is provided only for browsers without native *indexOf* support. For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:indexOf> */ Array.prototype.indexOf = Array.prototype.indexOf || function(item, from){ from = from || 0; if (from < 0) from = Math.max(0, this.length + from); while (from < this.length){ if(this[from] === item) return from; from++; } return -1; }; //custom methods Array.extend({ /* Property: each Same as <Array.forEach>. Arguments: fn - the function to execute with each item in the array bind - optional, the object that the "this" of the function will refer to. Example: >var Animals = ['Cat', 'Dog', 'Coala']; >Animals.forEach(function(animal){ > document.write(animal) >}); */ each: Array.prototype.forEach, /* Property: copy returns a copy of the array. Returns: a new array which is a copy of the current one. Arguments: start - optional, the index where to start the copy, default is 0. If negative, it is taken as the offset from the end of the array. length - optional, the number of elements to copy. By default, copies all elements from start to the end of the array. Example: >var letters = ["a","b","c"]; >var copy = letters.copy(); // ["a","b","c"] (new instance) */ copy: function(start, length){ start = start || 0; if (start < 0) start = this.length + start; length = length || (this.length - start); var newArray = []; for (var i = 0; i < length; i++) newArray[i] = this[start++]; return newArray; }, /* Property: remove Removes all occurrences of an item from the array. Arguments: item - the item to remove Returns: the Array with all occurrences of the item removed. Example: >["1","2","3","2"].remove("2") // ["1","3"]; */ remove: function(item){ var i = 0; while (i < this.length){ if (this[i] === item) this.splice(i, 1); else i++; } return this; }, /* Property: test Tests an array for the presence of an item. Arguments: item - the item to search for in the array. from - optional, the index at which to begin the search, default is 0. If negative, it is taken as the offset from the end of the array. Returns: true - the item was found false - it wasn't Example: >["a","b","c"].test("a"); // true >["a","b","c"].test("d"); // false */ test: function(item, from){ return this.indexOf(item, from) != -1; }, /* Property: extend Extends an array with another Arguments: newArray - the array to extend ours with Example: >var Animals = ['Cat', 'Dog', 'Coala']; >Animals.extend(['Lizard']); >//Animals is now: ['Cat', 'Dog', 'Coala', 'Lizard']; */ extend: function(newArray){ for (var i = 0; i < newArray.length; i++) this.push(newArray[i]); return this; }, /* Property: associate Creates an object with key-value pairs based on the array of keywords passed in and the current content of the array. Arguments: keys - the array of keywords. Example: (start code) var Animals = ['Cat', 'Dog', 'Coala', 'Lizard']; var Speech = ['Miao', 'Bau', 'Fruuu', 'Mute']; var Speeches = Animals.associate(speech); //Speeches['Miao'] is now Cat. //Speeches['Bau'] is now Dog. //... (end) */ associate: function(keys){ var obj = {}, length = Math.min(this.length, keys.length); for (var i = 0; i < length; i++) obj[keys[i]] = this[i]; return obj; } }); /* Section: Utility Functions */ /* Function: $A() Same as <Array.copy>, but as function. Useful to apply Array prototypes to iterable objects, as a collection of DOM elements or the arguments object. Example: (start code) function myFunction(){ $A(arguments).each(argument, function(){ alert(argument); }); }; //the above will alert all the arguments passed to the function myFunction. (end) */ function $A(array, start, length){ return Array.prototype.copy.call(array, start, length); }; /* Function: $each use to iterate through iterables that are not regular arrays, such as builtin getElementsByTagName calls, or arguments of a function. Arguments: iterable - an iterable element. function - function to apply to the iterable. bind - optional, the 'this' of the function will refer to this object. */ function $each(iterable, fn, bind){ return Array.prototype.forEach.call(iterable, fn, bind); }; /* Script: String.js Contains String prototypes and Number prototypes. Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: String A collection of The String Object prototype methods. */ String.extend({ /* Property: test Tests a string with a regular expression. Arguments: regex - a string or regular expression object, the regular expression you want to match the string with params - optional, if first parameter is a string, any parameters you want to pass to the regex ('g' has no effect) Returns: true if a match for the regular expression is found in the string, false if not. See <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:RegExp:test> Example: >"I like cookies".test("cookie"); // returns true >"I like cookies".test("COOKIE", "i") // ignore case, returns true >"I like cookies".test("cake"); // returns false */ test: function(regex, params){ return ((typeof regex == 'string') ? new RegExp(regex, params) : regex).test(this); }, /* Property: toInt parses a string to an integer. Returns: either an int or "NaN" if the string is not a number. Example: >var value = "10px".toInt(); // value is 10 */ toInt: function(){ return parseInt(this); }, toFloat: function(){ return parseFloat(this); }, /* Property: camelCase Converts a hiphenated string to a camelcase string. Example: >"I-like-cookies".camelCase(); //"ILikeCookies" Returns: the camel cased string */ camelCase: function(){ return this.replace(/-\D/g, function(match){ return match.charAt(1).toUpperCase(); }); }, /* Property: hyphenate Converts a camelCased string to a hyphen-ated string. Example: >"ILikeCookies".hyphenate(); //"I-like-cookies" */ hyphenate: function(){ return this.replace(/\w[A-Z]/g, function(match){ return (match.charAt(0)+'-'+match.charAt(1).toLowerCase()); }); }, /* Property: capitalize Converts the first letter in each word of a string to Uppercase. Example: >"i like cookies".capitalize(); //"I Like Cookies" Returns: the capitalized string */ capitalize: function(){ return this.toLowerCase().replace(/\b[a-z]/g, function(match){ return match.toUpperCase(); }); }, /* Property: trim Trims the leading and trailing spaces off a string. Example: >" i like cookies ".trim() //"i like cookies" Returns: the trimmed string */ trim: function(){ return this.replace(/^\s+|\s+$/g, ''); }, /* Property: clean trims (<String.trim>) a string AND removes all the double spaces in a string. Returns: the cleaned string Example: >" i like cookies \n\n".clean() //"i like cookies" */ clean: function(){ return this.replace(/\s{2,}/g, ' ').trim(); }, /* Property: rgbToHex Converts an RGB value to hexidecimal. The string must be in the format of "rgb(255,255,255)" or "rgba(255,255,255,1)"; Arguments: array - boolean value, defaults to false. Use true if you want the array ['FF','33','00'] as output instead of "#FF3300" Returns: hex string or array. returns "transparent" if the output is set as string and the fourth value of rgba in input string is 0. Example: >"rgb(17,34,51)".rgbToHex(); //"#112233" >"rgba(17,34,51,0)".rgbToHex(); //"transparent" >"rgb(17,34,51)".rgbToHex(true); //['11','22','33'] */ rgbToHex: function(array){ var rgb = this.match(/\d{1,3}/g); return (rgb) ? rgb.rgbToHex(array) : false; }, /* Property: hexToRgb Converts a hexidecimal color value to RGB. Input string must be the hex color value (with or without the hash). Also accepts triplets ('333'); Arguments: array - boolean value, defaults to false. Use true if you want the array [255,255,255] as output instead of "rgb(255,255,255)"; Returns: rgb string or array. Example: >"#112233".hexToRgb(); //"rgb(17,34,51)" >"#112233".hexToRgb(true); //[17,34,51] */ hexToRgb: function(array){ var hex = this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); return (hex) ? hex.slice(1).hexToRgb(array) : false; } }); Array.extend({ /* Property: rgbToHex see <String.rgbToHex>, but as an array method. */ rgbToHex: function(array){ if (this.length < 3) return false; if (this[3] && (this[3] == 0) && !array) return 'transparent'; var hex = []; for (var i = 0; i < 3; i++){ var bit = (this[i]-0).toString(16); hex.push((bit.length == 1) ? '0'+bit : bit); } return array ? hex : '#'+hex.join(''); }, /* Property: hexToRgb same as <String.hexToRgb>, but as an array method. */ hexToRgb: function(array){ if (this.length != 3) return false; var rgb = []; for (var i = 0; i < 3; i++){ rgb.push(parseInt((this[i].length == 1) ? this[i]+this[i] : this[i], 16)); } return array ? rgb : 'rgb('+rgb.join(',')+')'; } }); /* Class: Number contains the internal method toInt. */ Number.extend({ /* Property: toInt Returns this number; useful because toInt must work on both Strings and Numbers. */ toInt: function(){ return parseInt(this); }, toFloat: function(){ return parseFloat(this); } }); /* Script: Function.js Contains Function prototypes and utility functions . Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. Credits: - Some functions are inspired by those found in prototype.js <http://prototype.conio.net/> (c) 2005 Sam Stephenson sam [at] conio [dot] net, MIT-style license */ /* Class: Function A collection of The Function Object prototype methods. */ Function.extend({ /* Property: create Main function to create closures. Returns: a function. Arguments: options - An Options object. Options: bind - The object that the "this" of the function will refer to. Default is the current function. event - If set to true, the function will act as an event listener and receive an event as first argument. If set to a class name, the function will receive a new instance of this class (with the event passed as argument's constructor) as first argument. Default is false. arguments - A single argument or array of arguments that will be passed to the function when called. If both the event and arguments options are set, the event is passed as first argument and the arguments array will follow. Default is no custom arguments, the function will receive the standard arguments when called. delay - Numeric value: if set, the returned function will delay the actual execution by this amount of milliseconds and return a timer handle when called. Default is no delay. periodical - Numeric value: if set, the returned function will periodically perform the actual execution with this specified interval and return a timer handle when called. Default is no periodical execution. attempt - If set to true, the returned function will try to execute and return either the results or the error when called. Default is false. */ create: function(options){ var fn = this; options = Object.extend({ 'bind': fn, 'event': false, 'arguments': null, 'delay': false, 'periodical': false, 'attempt': false }, options || {}); if ($chk(options.arguments) && $type(options.arguments) != 'array') options.arguments = [options.arguments]; return function(event){ var args; if (options.event){ event = event || window.event; args = [(options.event === true) ? event : new options.event(event)]; if (options.arguments) args = args.concat(options.arguments); } else args = options.arguments || arguments; var returns = function(){ return fn.apply(options.bind, args); }; if (options.delay) return setTimeout(returns, options.delay); if (options.periodical) return setInterval(returns, options.periodical); if (options.attempt){ try { return returns(); } catch(err){ return err; } } return returns(); }; }, /* Property: pass Shortcut to create closures with arguments and bind. Returns: a function. Arguments: args - the arguments passed. must be an array if arguments > 1 bind - optional, the object that the "this" of the function will refer to. Example: >myFunction.pass([arg1, arg2], myElement); */ pass: function(args, bind){ return this.create({'arguments': args, 'bind': bind}); }, /* Property: attempt Tries to execute the function, returns either the function results or the error. Arguments: args - the arguments passed. must be an array if arguments > 1 bind - optional, the object that the "this" of the function will refer to. Example: >myFunction.attempt([arg1, arg2], myElement); */ attempt: function(args, bind){ return this.create({'arguments': args, 'bind': bind, 'attempt': true})(); }, /* Property: bind method to easily create closures with "this" altered. Arguments: bind - optional, the object that the "this" of the function will refer to. args - optional, the arguments passed. must be an array if arguments > 1 Returns: a function. Example: >function myFunction(){ > this.setStyle('color', 'red'); > // note that 'this' here refers to myFunction, not an element > // we'll need to bind this function to the element we want to alter >}; >var myBoundFunction = myFunction.bind(myElement); >myBoundFunction(); // this will make the element myElement red. */ bind: function(bind, args){ return this.create({'bind': bind, 'arguments': args}); }, /* Property: bindAsEventListener cross browser method to pass event firer Arguments: bind - optional, the object that the "this" of the function will refer to. args - optional, the arguments passed. must be an array if arguments > 1 Returns: a function with the parameter bind as its "this" and as a pre-passed argument event or window.event, depending on the browser. Example: >function myFunction(event){ > alert(event.clientx) //returns the coordinates of the mouse.. >}; >myElement.onclick = myFunction.bindAsEventListener(myElement); */ bindAsEventListener: function(bind, args){ return this.create({'bind': bind, 'event': true, 'arguments': args}); }, /* Property: delay Delays the execution of a function by a specified duration. Arguments: ms - the duration to wait in milliseconds bind - optional, the object that the "this" of the function will refer to. args - optional, the arguments passed. must be an array if arguments > 1 Example: >myFunction.delay(50, myElement) //wait 50 milliseconds, then call myFunction and bind myElement to it >(function(){alert('one second later...')}).delay(1000); //wait a second and alert */ delay: function(ms, bind, args){ return this.create({'delay': ms, 'bind': bind, 'arguments': args})(); }, /* Property: periodical Executes a function in the specified intervals of time Arguments: ms - the duration of the intervals between executions. bind - optional, the object that the "this" of the function will refer to. args - optional, the arguments passed. must be an array if arguments > 1 */ periodical: function(ms, bind, args){ return this.create({'periodical': ms, 'bind': bind, 'arguments': args})(); } }); /* Script: Element.js Contains useful Element prototypes, to be used with the dollar function <$>. Authors: - Valerio Proietti, <http://mad4milk.net> - Christophe Beyls, <http://digitalia.be> License: MIT-style license. Credits: - Some functions are inspired by those found in prototype.js <http://prototype.conio.net/> (c) 2005 Sam Stephenson sam [at] conio [dot] net, MIT-style license */ /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ var Element = new Class({ /* Property: initialize Creates a new element of the type passed in. Arguments: el - the tag name for the element you wish to create. Example: >var div = new Element('div'); */ initialize: function(el){ if ($type(el) == 'string') el = document.createElement(el); return $(el); } }); /* Section: Utility Functions Function: $ returns the element passed in with all the Element prototypes applied. Arguments: el - a reference to an actual element or a string representing the id of an element Example: >$('myElement') // gets a DOM element by id with all the Element prototypes applied. >var div = document.getElementById('myElement'); >$(div) //returns an Element also with all the mootools extentions applied. You'll use this when you aren't sure if a variable is an actual element or an id, as well as just shorthand for document.getElementById(). Returns: a DOM element or false (if no id was found). Note: you need to call $ on an element only once to get all the prototypes. But its no harm to call it multiple times, as it will detect if it has been already extended. */ function $(el){ if (!el) return false; if (el._element_extended_ || [window, document].test(el)) return el; if ($type(el) == 'string') el = document.getElementById(el); if ($type(el) != 'element') return false; if (['object', 'embed'].test(el.tagName.toLowerCase()) || el.extend) return el; el._element_extended_ = true; Garbage.collect(el); el.extend = Object.extend; if (!(el.htmlElement)) el.extend(Element.prototype); return el; }; //elements class var Elements = new Class({}); new Object.Native(Elements); document.getElementsBySelector = document.getElementsByTagName; /* Function: $$ Selects, and extends DOM elements. Arguments: HTMLCollection(document.getElementsByTagName, element.childNodes), an array of elements, a string. Note: if you loaded <Dom.js>, $$ will also accept CSS Selectors. Example: >$$('a') //an array of all anchor tags on the page >$$('a', 'b') //an array of all anchor and bold tags on the page >$$('#myElement') //array containing only the element with id = myElement. (only with <Dom.js>) >$$('#myElement a.myClass') //an array of all anchor tags with the class "myClass" within the DOM element with id "myElement" (only with <Dom.js>) Returns: array - array of all the dom elements matched */ function $$(){ if (!arguments) return false; if (arguments.length == 1){ if (!arguments[0]) return false; if (arguments[0]._elements_extended_) return arguments[0]; } var elements = []; $each(arguments, function(selector){ switch ($type(selector)){ case 'element': elements.push($(selector)); break; case 'string': selector = document.getElementsBySelector(selector); default: if (selector.length){ $each(selector, function(el){ if ($(el)) elements.push(el); }); } } }); elements._elements_extended_ = true; return Object.extend(elements, new Elements); }; Elements.Multi = function(property){ return function(){ var args = arguments; var items = []; var elements = true; $each(this, function(el){ var returns = el[property].apply(el, args); if ($type(returns) != 'element') elements = false; items.push(returns); }); if (elements) items = $$(items); return items; }; }; Element.extend = function(properties){ for (var property in properties){ HTMLElement.prototype[property] = properties[property]; Element.prototype[property] = properties[property]; Elements.prototype[property] = Elements.Multi(property); } }; /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ inject: function(el, where){ el = $(el) || new Element(el); switch (where){ case "before": $(el.parentNode).insertBefore(this, el); break; case "after": if (!el.getNext()) $(el.parentNode).appendChild(this); else $(el.parentNode).insertBefore(this, el.getNext()); break; case "inside": el.appendChild(this); } return this; }, /* Property: injectBefore Inserts the Element before the passed element. Parameteres: el - a string representing the element to be injected in (myElementId, or div), or an element reference. If you pass div or another tag, the element will be created. Example: >html: ><div id="myElement"></div> ><div id="mySecondElement"></div> >js: >$('mySecondElement').injectBefore('myElement'); >resulting html: ><div id="mySecondElement"></div> ><div id="myElement"></div> */ injectBefore: function(el){ return this.inject(el, 'before'); }, /* Property: injectAfter Same as <Element.injectBefore>, but inserts the element after. */ injectAfter: function(el){ return this.inject(el, 'after'); }, /* Property: injectInside Same as <Element.injectBefore>, but inserts the element inside. */ injectInside: function(el){ return this.inject(el, 'inside'); }, /* Property: adopt Inserts the passed element inside the Element. Works as <Element.injectInside> but in reverse. Parameteres: el - a string representing the element to be injected in (myElementId, or div), or an element reference. If you pass div or another tag, the element will be created. */ adopt: function(el){ this.appendChild($(el) || new Element(el)); return this; }, /* Property: remove Removes the Element from the DOM. Example: >$('myElement').remove() //bye bye */ remove: function(){ this.parentNode.removeChild(this); return this; }, /* Property: clone Clones the Element and returns the cloned one. Returns: the cloned element Example: >var clone = $('myElement').clone().injectAfter('myElement'); >//clones the Element and append the clone after the Element. */ clone: function(contents){ var el = this.cloneNode(contents !== false); return $(el); }, /* Property: replaceWith Replaces the Element with an element passed. Parameteres: el - a string representing the element to be injected in (myElementId, or div), or an element reference. If you pass div or another tag, the element will be created. Returns: the passed in element Example: >$('myOldElement').replaceWith($('myNewElement')); //$('myOldElement') is gone, and $('myNewElement') is in its place. */ replaceWith: function(el){ el = $(el) || new Element(el); this.parentNode.replaceChild(el, this); return el; }, /* Property: appendText Appends text node to a DOM element. Arguments: text - the text to append. Example: ><div id="myElement">hey</div> >$('myElement').appendText(' howdy'); //myElement innerHTML is now "hey howdy" */ appendText: function(text){ if (window.ie){ switch(this.getTag()){ case 'style': this.styleSheet.cssText = text; return this; case 'script': this.setProperty('text', text); return this; } } this.appendChild(document.createTextNode(text)); return this; }, /* Property: hasClass Tests the Element to see if it has the passed in className. Returns: true - the Element has the class false - it doesn't Arguments: className - the class name to test. Example: ><div id="myElement" class="testClass"></div> >$('myElement').hasClass('testClass'); //returns true */ hasClass: function(className){ return this.className.test('(?:^|\\s)'+className+'(?:\\s|$)'); }, /* Property: addClass Adds the passed in class to the Element, if the element doesnt already have it. Arguments: className - the class name to add Example: ><div id="myElement" class="testClass"></div> >$('myElement').addClass('newClass'); //<div id="myElement" class="testClass newClass"></div> */ addClass: function(className){ if (!this.hasClass(className)) this.className = (this.className+' '+className).clean(); return this; }, /* Property: removeClass works like <Element.addClass>, but removes the class from the element. */ removeClass: function(className){ this.className = this.className.replace(new RegExp('(^|\\s)'+className+'(?:\\s|$)'), '$1').clean(); return this; }, /* Property: toggleClass Adds or removes the passed in class name to the element, depending on if it's present or not. Arguments: className - the class to add or remove Example: ><div id="myElement" class="myClass"></div> >$('myElement').toggleClass('myClass'); ><div id="myElement" class=""></div> >$('myElement').toggleClass('myClass'); ><div id="myElement" class="myClass"></div> */ toggleClass: function(className){ return this.hasClass(className) ? this.removeClass(className) : this.addClass(className); }, /* Property: setStyle Sets a css property to the Element. Arguments: property - the property to set value - the value to which to set it Example: >$('myElement').setStyle('width', '300px'); //the width is now 300px */ setStyle: function(property, value){ if (property == 'opacity') this.setOpacity(parseFloat(value)); else this.style[property.camelCase()] = (value.push) ? 'rgb('+value.join(',')+')' : value; return this; }, /* Property: setStyles Applies a collection of styles to the Element. Arguments: source - an object or string containing all the styles to apply. You cannot set the opacity using a string. Examples: >$('myElement').setStyles({ > border: '1px solid #000', > width: '300px', > height: '400px' >}); OR >$('myElement').setStyles('border: 1px solid #000; width: 300px; height: 400px;'); */ setStyles: function(source){ switch ($type(source)){ case 'object': for (var property in source) this.setStyle(property, source[property]); break; case 'string': this.style.cssText = source; } return this; }, /* Property: setOpacity Sets the opacity of the Element, and sets also visibility == "hidden" if opacity == 0, and visibility = "visible" if opacity > 0. Arguments: opacity - Accepts numbers from 0 to 1. Example: >$('myElement').setOpacity(0.5) //make it 50% transparent */ setOpacity: function(opacity){ if (opacity == 0){ if(this.style.visibility != "hidden") this.style.visibility = "hidden"; } else { if(this.style.visibility != "visible") this.style.visibility = "visible"; } if (!this.currentStyle || !this.currentStyle.hasLayout) this.style.zoom = 1; if (window.ie) this.style.filter = "alpha(opacity=" + opacity*100 + ")"; this.style.opacity = this.opacity = opacity; return this; }, /* Property: getStyle Returns the style of the Element given the property passed in. Arguments: property - the css style property you want to retrieve Example: >$('myElement').getStyle('width'); //returns "400px" >//but you can also use >$('myElement').getStyle('width').toInt(); //returns "400" Returns: the style as a string */ getStyle: function(property){ property = property.camelCase(); var style = this.style[property] || false; if (!$chk(style)){ if (property == 'opacity') return $chk(this.opacity) ? this.opacity : 1; if (['margin', 'padding'].test(property)){ return [this.getStyle(property+'-top') || 0, this.getStyle(property+'-right') || 0, this.getStyle(property+'-bottom') || 0, this.getStyle(property+'-left') || 0].join(' '); } if (document.defaultView) style = document.defaultView.getComputedStyle(this, null).getPropertyValue(property.hyphenate()); else if (this.currentStyle) style = this.currentStyle[property]; } if (style == 'auto' && ['height', 'width'].test(property)) return this['offset'+property.capitalize()]+'px'; return (style && property.test(/color/i) && style.test(/rgb/)) ? style.rgbToHex() : style; }, /* Property: addEvent Attaches an event listener to a DOM element. Arguments: type - the event to monitor ('click', 'load', etc) without the prefix 'on'. fn - the function to execute Example: >$('myElement').addEvent('click', function(){alert('clicked!')}); */ addEvent: function(type, fn){ this.events = this.events || {}; this.events[type] = this.events[type] || {'keys': [], 'values': []}; if (!this.events[type].keys.test(fn)){ this.events[type].keys.push(fn); if (this.addEventListener){ this.addEventListener((type == 'mousewheel' && window.gecko) ? 'DOMMouseScroll' : type, fn, false); } else { fn = fn.bind(this); this.attachEvent('on'+type, fn); this.events[type].values.push(fn); } } return this; }, addEvents: function(source){ if (source){ for (var type in source) this.addEvent(type, source[type]); } return this; }, /* Property: removeEvent Works as Element.addEvent, but instead removes the previously added event listener. */ removeEvent: function(type, fn){ if (this.events && this.events[type]){ var pos = this.events[type].keys.indexOf(fn); if (pos == -1) return this; var key = this.events[type].keys.splice(pos,1)[0]; if (this.removeEventListener){ this.removeEventListener((type == 'mousewheel' && window.gecko) ? 'DOMMouseScroll' : type, key, false); } else { this.detachEvent('on'+type, this.events[type].values.splice(pos,1)[0]); } } return this; }, /* Property: removeEvents removes all events of a certain type from an element. if no argument is passed in, removes all events. */ removeEvents: function(type){ if (this.events){ if (type){ if (this.events[type]){ this.events[type].keys.each(function(fn){ this.removeEvent(type, fn); }, this); this.events[type] = null; } } else { for (var evType in this.events) this.removeEvents(evType); this.events = null; } } return this; }, /* Property: fireEvent executes all events of the specified type present in the element. */ fireEvent: function(type, args){ if (this.events && this.events[type]){ this.events[type].keys.each(function(fn){ fn.bind(this, args)(); }, this); } }, getBrother: function(what){ var el = this[what+'Sibling']; while ($type(el) == 'whitespace') el = el[what+'Sibling']; return $(el); }, /* Property: getPrevious Returns the previousSibling of the Element, excluding text nodes. Example: >$('myElement').getPrevious(); //get the previous DOM element from myElement Returns: the sibling element or undefined if none found. */ getPrevious: function(){ return this.getBrother('previous'); }, /* Property: getNext Works as Element.getPrevious, but tries to find the nextSibling. */ getNext: function(){ return this.getBrother('next'); }, /* Property: getFirst Works as <Element.getPrevious>, but tries to find the firstChild. */ getFirst: function(){ var el = this.firstChild; while ($type(el) == 'whitespace') el = el.nextSibling; return $(el); }, /* Property: getLast Works as <Element.getPrevious>, but tries to find the lastChild. */ getLast: function(){ var el = this.lastChild; while ($type(el) == 'whitespace') el = el.previousSibling; return $(el); }, /* Property: getParent returns the $(element.parentNode) */ getParent: function(){ return $(this.parentNode); }, /* Property: getChildren returns all the $(element.childNodes), excluding text nodes. Returns as <Elements>. */ getChildren: function(){ return $$(this.childNodes); }, /* Property: setProperty Sets an attribute for the Element. Arguments: property - the property to assign the value passed in value - the value to assign to the property passed in Example: >$('myImage').setProperty('src', 'whatever.gif'); //myImage now points to whatever.gif for its source */ setProperty: function(property, value){ switch (property){ case 'class': this.className = value; break; case 'style': this.setStyles(value); break; case 'name': if (window.ie6){ var el = $(document.createElement('<'+this.getTag()+' name="'+value+'" />')); $each(this.attributes, function(attribute){ if (attribute.name != 'name') el.setProperty(attribute.name, attribute.value); }); if (this.parentNode) this.replaceWith(el); return el; } default: this.setAttribute(property, value); } return this; }, /* Property: setProperties Sets numerous attributes for the Element. Arguments: source - an object with key/value pairs. Example: (start code) $('myElement').setProperties({ src: 'whatever.gif', alt: 'whatever dude' }); <img src="whatever.gif" alt="whatever dude"> (end) */ setProperties: function(source){ for (var property in source) this.setProperty(property, source[property]); return this; }, /* Property: setHTML Sets the innerHTML of the Element. Arguments: html - the new innerHTML for the element. Example: >$('myElement').setHTML(newHTML) //the innerHTML of myElement is now = newHTML */ setHTML: function(){ this.innerHTML = $A(arguments).join(''); return this; }, /* Property: getProperty Gets the an attribute of the Element. Arguments: property - the attribute to retrieve Example: >$('myImage').getProperty('src') // returns whatever.gif Returns: the value, or an empty string */ getProperty: function(property){ return (property == 'class') ? this.className : this.getAttribute(property); }, /* Property: getTag Returns the tagName of the element in lower case. Example: >$('myImage').getTag() // returns 'img' Returns: The tag name in lower case */ getTag: function(){ return this.tagName.toLowerCase(); }, /* Property: scrollTo scrolls the element to the specified coordinated (if the element has an overflow) Arguments: x - the x coordinate y - the y coordinate Example: >$('myElement').scrollTo(0, 100) */ scrollTo: function(x, y){ this.scrollLeft = x; this.scrollTop = y; }, /* Property: getValue Returns the value of the Element, if its tag is textarea, select or input. no multiple select support. */ getValue: function(){ switch (this.getTag()){ case 'select': if (this.selectedIndex != -1){ var opt = this.options[this.selectedIndex]; return opt.value || opt.text; } break; case 'input': if (!(this.checked && ['checkbox', 'radio'].test(this.type)) && !['hidden', 'text', 'password'].test(this.type)) break; case 'textarea': return this.value; } return false; }, /* Property: getSize return an Object representing the size/scroll values of the element. Example: (start code) $('myElement').getSize(); (end) Returns: (start code) { 'scroll': {'x': 100, 'y': 100}, 'size': {'x': 200, 'y': 400}, 'scrollSize': {'x': 300, 'y': 500} } (end) */ getSize: function(){ return { 'scroll': {'x': this.scrollLeft, 'y': this.scrollTop}, 'size': {'x': this.offsetWidth, 'y': this.offsetHeight}, 'scrollSize': {'x': this.scrollWidth, 'y': this.scrollHeight} }; }, /* Property: getPosition Returns the real offsets of the element. Example: >$('element').getPosition(); Returns: >{x: 100, y:500}; */ getPosition: function(overflown){ overflown = overflown || []; var el = this, left = 0, top = 0; do { left += el.offsetLeft || 0; top += el.offsetTop || 0; el = el.offsetParent; } while (el); overflown.each(function(element){ left -= element.scrollLeft || 0; top -= element.scrollTop || 0; }); return {'x': left, 'y': top}; }, /* Property: getTop Returns the distance from the top of the window to the Element. */ getTop: function(){ return this.getPosition().y; }, /* Property: getLeft Returns the distance from the left of the window to the Element. */ getLeft: function(){ return this.getPosition().x; }, /* Property: getCoordinates Returns an object with width, height, left, right, top, and bottom, representing the values of the Element Example: (start code) var myValues = $('myElement').getCoordinates(); (end) Returns: (start code) { width: 200, height: 300, left: 100, top: 50, right: 300, bottom: 350 } (end) */ getCoordinates: function(overflown){ var position = this.getPosition(overflown); var obj = { 'width': this.offsetWidth, 'height': this.offsetHeight, 'left': position.x, 'top': position.y }; obj.right = obj.left + obj.width; obj.bottom = obj.top + obj.height; return obj; } }); window.addEvent = document.addEvent = Element.prototype.addEvent; window.removeEvent = document.removeEvent = Element.prototype.removeEvent; window.removeEvents = document.removeEvents = Element.prototype.removeEvents; var Garbage = { elements: [], collect: function(element){ Garbage.elements.push(element); }, trash: function(){ Garbage.collect(window); Garbage.collect(document); Garbage.elements.each(function(el){ el.removeEvents(); for (var p in Element.prototype) el[p] = null; el.extend = null; }); } }; window.addEvent('unload', Garbage.trash); /* Script: Event.js Event class Authors: - Valerio Proietti, <http://mad4milk.net> - Michael Jackson, <http://ajaxon.com/michael> License: MIT-style license. */ /* Class: Event Cross browser methods to manage events. Arguments: event - the event Properties: shift - true if the user pressed the shift control - true if the user pressed the control alt - true if the user pressed the alt meta - true if the user pressed the meta key code - the keycode of the key pressed page.x - the x position of the mouse, relative to the full window page.y - the y position of the mouse, relative to the full window client.x - the x position of the mouse, relative to the viewport client.y - the y position of the mouse, relative to the viewport key - the key pressed as a lowercase string. key also returns 'enter', 'up', 'down', 'left', 'right', 'space', 'backspace', 'delete', 'esc'. Handy for these special keys. target - the event target relatedTarget - the event related target Example: (start code) $('myLink').onkeydown = function(event){ var event = new Event(event); //event is now the Event class. alert(event.key); //returns the lowercase letter pressed alert(event.shift); //returns true if the key pressed is shift if (event.key == 's' && event.control) alert('document saved'); }; (end) */ var Event = new Class({ initialize: function(event){ this.event = event || window.event; this.type = this.event.type; this.target = this.event.target || this.event.srcElement; if (this.target.nodeType == 3) this.target = this.target.parentNode; // Safari this.shift = this.event.shiftKey; this.control = this.event.ctrlKey; this.alt = this.event.altKey; this.meta = this.event.metaKey; if (['DOMMouseScroll', 'mousewheel'].test(this.type)){ this.wheel = this.event.wheelDelta ? (this.event.wheelDelta / (window.opera ? -120 : 120)) : -(this.event.detail || 0) / 3; } else if (this.type.test(/key/)){ this.code = this.event.which || this.event.keyCode; for (var name in Event.keys){ if (Event.keys[name] == this.code){ this.key = name; break; } } this.key = this.key || String.fromCharCode(this.code).toLowerCase(); } else if (this.type.test(/mouse/) || (this.type == 'click')){ this.page = { 'x': this.event.pageX || this.event.clientX + document.documentElement.scrollLeft, 'y': this.event.pageY || this.event.clientY + document.documentElement.scrollTop }; this.client = { 'x': this.event.pageX ? this.event.pageX - window.pageXOffset : this.event.clientX, 'y': this.event.pageY ? this.event.pageY - window.pageYOffset : this.event.clientY }; this.rightClick = (this.event.which == 3) || (this.event.button == 2); switch (this.type){ case 'mouseover': this.relatedTarget = this.event.relatedTarget || this.event.fromElement; break; case 'mouseout': this.relatedTarget = this.event.relatedTarget || this.event.toElement; } } }, /* Property: stop cross browser method to stop an event */ stop: function() { this.stopPropagation(); this.preventDefault(); return this; }, /* Property: stopPropagation cross browser method to stop the propagation of an event */ stopPropagation: function(){ if (this.event.stopPropagation) this.event.stopPropagation(); else this.event.cancelBubble = true; return this; }, /* Property: preventDefault cross browser method to prevent the default action of the event */ preventDefault: function(){ if (this.event.preventDefault) this.event.preventDefault(); else this.event.returnValue = false; return this; } }); Event.keys = { 'enter': 13, 'up': 38, 'down': 40, 'left': 37, 'right': 39, 'esc': 27, 'space': 32, 'backspace': 8, 'delete': 46 }; Function.extend({ /* Property: bindWithEvent automatically passes mootools Event Class. Arguments: bind - optional, the object that the "this" of the function will refer to. Returns: a function with the parameter bind as its "this" and as a pre-passed argument event or window.event, depending on the browser. Example: >function myFunction(event){ > alert(event.clientx) //returns the coordinates of the mouse.. >}; >myElement.onclick = myFunction.bindWithEvent(myElement); */ bindWithEvent: function(bind, args){ return this.create({'bind': bind, 'arguments': args, 'event': Event}); } }); /* Script: Common.js Contains common implementations for custom classes. In Mootools is implemented in <Ajax>, <XHR> and <Fx.Base>. Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Chain An "Utility" Class. Its methods can be implemented with <Class.implement> into any <Class>. Currently implemented in <Fx.Base>, <XHR> and <Ajax>. In <Fx.Base> for example, is used to execute a list of function, one after another, once the effect is completed. The functions will not be fired all togheter, but one every completion, to create custom complex animations. Example: (start code) var myFx = new Fx.Style('element', 'opacity'); myFx.start(1,0).chain(function(){ myFx.start(0,1); }).chain(function(){ myFx.start(1,0); }).chain(function(){ myFx.start(0,1); }); //the element will appear and disappear three times (end) */ var Chain = new Class({ /* Property: chain adds a function to the Chain instance stack. Arguments: fn - the function to append. */ chain: function(fn){ this.chains = this.chains || []; this.chains.push(fn); return this; }, /* Property: callChain Executes the first function of the Chain instance stack, then removes it. The first function will then become the second. */ callChain: function(){ if (this.chains && this.chains.length) this.chains.shift().delay(10, this); }, /* Property: clearChain Clears the stack of a Chain instance. */ clearChain: function(){ this.chains = []; } }); /* Class: Events An "Utility" Class. Its methods can be implemented with <Class.implement> into any <Class>. In <Fx.Base> Class, for example, is used to give the possibility add any number of functions to the Effects events, like onComplete, onStart, onCancel Example: (start code) var myFx = new Fx.Style('element', 'opacity').addEvent('onComplete', function(){ alert('the effect is completed'); }).addEvent('onComplete', function(){ alert('I told you the effect is completed'); }); myFx.start(0,1); //upon completion it will display the 2 alerts, in order. (end) */ var Events = new Class({ /* Property: addEvent adds an event to the stack of events of the Class instance. */ addEvent: function(type, fn){ if (fn != Class.empty){ this.events = this.events || {}; this.events[type] = this.events[type] || []; if (!this.events[type].test(fn)) this.events[type].push(fn); } return this; }, /* Property: fireEvent fires all events of the specified type in the Class instance. */ fireEvent: function(type, args, delay){ if (this.events && this.events[type]){ this.events[type].each(function(fn){ fn.create({'bind': this, 'delay': delay, 'arguments': args})(); }, this); } return this; }, /* Property: removeEvent removes an event from the stack of events of the Class instance. */ removeEvent: function(type, fn){ if (this.events && this.events[type]) this.events[type].remove(fn); return this; } }); /* Class: Options An "Utility" Class. Its methods can be implemented with <Class.implement> into any <Class>. Used to automate the options settings, also adding Class <Events> when the option begins with on. */ var Options = new Class({ /* Property: setOptions sets this.options Arguments: defaults - the default set of options options - the user entered options. can be empty too. Note: if your Class has <Events> implemented, every option beginning with on, followed by a capital letter (onComplete) becomes an Class instance event. */ setOptions: function(defaults, options){ this.options = Object.extend(defaults, options); if (this.addEvent){ for (var option in this.options){ if (($type(this.options[option]) == 'function') && option.test(/^on[A-Z]/)) this.addEvent(option, this.options[option]); } } return this; } }); /* Class: Group An "Utility" Class. */ var Group = new Class({ initialize: function(){ this.instances = $A(arguments); this.events = {}; this.checker = {}; }, addEvent: function(type, fn){ this.checker[type] = this.checker[type] || {}; this.events[type] = this.events[type] || []; if (this.events[type].test(fn)) return false; else this.events[type].push(fn); this.instances.each(function(instance, i){ instance.addEvent(type, this.check.bind(this, [type, instance, i])); }, this); return this; }, check: function(type, instance, i){ this.checker[type][i] = true; var every = this.instances.every(function(current, j){ return this.checker[type][j] || false; }, this); if (!every) return; this.instances.each(function(current, j){ this.checker[type][j] = false; }, this); this.events[type].each(function(event){ event.call(this, this.instances, instance); }, this); } }); /* Script: Dom.js Css Query related function and <Element> extensions Authors: - Valerio Proietti, <http://mad4milk.net> - Christophe Beyls, <http://digitalia.be> License: MIT-style license. */ /* Section: Utility Functions */ /* Function: $E Selects a single (i.e. the first found) Element based on the selector passed in and an optional filter element. Arguments: selector - the css selector to match filter - optional; a DOM element to limit the scope of the selector match; defaults to document. Example: >$E('a', 'myElement') //find the first anchor tag inside the DOM element with id 'myElement' Returns: a DOM element - the first element that matches the selector */ function $E(selector, filter){ return ($(filter) || document).getElement(selector); }; /* Function: $ES Returns a collection of Elements that match the selector passed in limited to the scope of the optional filter. See Also: <Element.getElements> for an alternate syntax. Returns: an array of dom elements that match the selector within the filter Arguments: selector - css selector to match filter - optional; a DOM element to limit the scope of the selector match; defaults to document. Examples: >$ES("a") //gets all the anchor tags; synonymous with $$("a") >$ES('a','myElement') //get all the anchor tags within $('myElement') */ function $ES(selector, filter){ return ($(filter) || document).getElementsBySelector(selector); }; /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: getElements Gets all the elements within an element that match the given (single) selector. Arguments: selector - the css selector to match Example: >$('myElement').getElements('a'); // get all anchors within myElement */ getElements: function(selector){ var elements = []; selector.clean().split(' ').each(function(sel, i){ var param = sel.match(/^(\w*|\*)(?:#([\w-]+)|\.([\w-]+))?(?:\[(\w+)(?:([*^$]?=)["']?([^"'\]]*)["']?)?])?$/); //PARAM ARRAY: 0 = full string: 1 = tag; 2 = id; 3 = class; 4 = attribute; 5 = operator; 6 = value; if (!param) return; Filters.selector = param; param[1] = param[1] || '*'; if (i == 0){ if (param[2]){ var el = this.getElementById(param[2]); if (!el || ((param[1] != '*') && (Element.prototype.getTag.call(el) != param[1]))) return; elements = [el]; } else { elements = $A(this.getElementsByTagName(param[1])); } } else { elements = Elements.prototype.getElementsByTagName.call(elements, param[1], true); if (param[2]) elements = elements.filter(Filters.id); } if (param[3]) elements = elements.filter(Filters.className); if (param[4]) elements = elements.filter(Filters.attribute); }, this); return $$(elements); }, /* Property: getElementById Targets an element with the specified id found inside the Element. Does not overwrite document.getElementById. Arguments: id - the id of the element to find. */ getElementById: function(id){ var el = document.getElementById(id); if (!el) return false; for (var parent = el.parentNode; parent != this; parent = parent.parentNode){ if (!parent) return false; } return el; }, /* Property: getElement Same as <Element.getElements>, but returns only the first. Alternate syntax for <$E>, where filter is the Element. */ getElement: function(selector){ return this.getElementsBySelector(selector)[0]; }, /* Property: getElementsBySelector Same as <Element.getElements>, but allows for comma separated selectors, as in css. Alternate syntax for <$$>, where filter is the Element. */ getElementsBySelector: function(selector){ var els = []; selector.split(',').each(function(sel){ els.extend(this.getElements(sel)); }, this); return $$(els); } }); /* Section: document related functions */ document.extend({ /* Function: document.getElementsByClassName Returns all the elements that match a specific class name. Here for compatibility purposes. can also be written: document.getElements('.className'), or $$('.className') */ getElementsByClassName: function(className){ return document.getElements('.'+className); }, getElement: Element.prototype.getElement, getElements: Element.prototype.getElements, getElementsBySelector: Element.prototype.getElementsBySelector }); //dom filters, internal methods. var Filters = { selector: [], id: function(el){ return (el.id == Filters.selector[2]); }, className: function(el){ return (Element.prototype.hasClass.call(el, Filters.selector[3])); }, attribute: function(el){ var current = el.getAttribute(Filters.selector[4]); if (!current) return false; var operator = Filters.selector[5]; if (!operator) return true; var value = Filters.selector[6]; switch (operator){ case '*=': return (current.test(value)); case '=': return (current == value); case '^=': return (current.test('^'+value)); case '$=': return (current.test(value+'$')); } return false; } }; /* Class: Elements Methods for dom queries arrays, <$$>. */ Elements.extend({ getElementsByTagName: function(tagName){ var found = []; this.each(function(el){ found.extend(el.getElementsByTagName(tagName)); }); return found; } }); /* Script: Hash.js Contains the class Hash. Author: Christophe Beyls, <http://digitalia.be> License: MIT-style license. */ /* Class: Hash It wraps an object that it uses internally as a map. The user must use set(), get(), and remove() to add/change, retrieve and remove values, it must not access the internal object directly. null values are allowed. Example: (start code) var hash = new Hash({a: 'hi', b: 'world', c: 'howdy'}); hash.remove('b'); // b is removed. hash.set('c', 'hello'); hash.get('c'); // returns 'hello' hash.length // returns 2 (a and b) (end) */ var Hash = new Class({ length: 0, obj: {}, initialize: function(obj){ this.extend(obj); }, /* Property: get Retrieves a value from the hash. Arguments: key - The key Returns: The value */ get: function(key){ return this.obj[key]; }, /* Property: hasKey Check the presence of a specified key-value pair in the hash. Arguments: key - The key Returns: True if the Hash contains an value for the specified key, otherwise false */ hasKey: function(key){ return this.obj[key] !== undefined; }, /* Property: set Adds a key-value pair to the hash or replaces a previous value associated with the key. Arguments: key - The key value - The value */ set: function(key, value){ if (value === undefined) return false; if (this.obj[key] === undefined) this.length++; this.obj[key] = value; return this; }, /* Property: remove Removes a key-value pair from the hash. Arguments: key - The key */ remove: function(key){ if (this.obj[key] === undefined) return this; var obj = {}; this.length--; for (var property in this.obj){ if (property != key) obj[property] = this.obj[property]; } this.obj = obj; return this; }, /* Property: each Calls a function for each key-value pair. The first argument passed to the function will be the key, the second one will be the value. Arguments: fn - The function to call for each key-value pair bind - Optional, the object that will be referred to as "this" in the function */ each: function(fn, bind){ for (var property in this.obj) fn.call(bind || this, property, this.obj[property]); }, /* Property: extend Extends the current hash with an object containing key-value pairs. Values for duplicate keys will be replaced by the new ones. Arguments: obj - An object containing key-value pairs */ extend: function(obj){ for (var property in obj){ if (this.obj[property] === undefined) this.length++; this.obj[property] = obj[property]; } return this; }, /* Property: empty Checks if the hash is empty. Returns: True if the hash is empty, otherwise false */ empty: function(){ return (this.length == 0); }, /* Property: keys Returns an array containing all the keys, in the same order as the values returned by <Hash.values>. Returns: An array containing all the keys of the hash */ keys: function(){ var keys = []; for (var property in this.obj) keys.push(property); return keys; }, /* Property: values Returns an array containing all the values, in the same order as the keys returned by <Hash.keys>. Returns: An array containing all the values of the hash */ values: function(){ var values = []; for (var property in this.obj) values.push(this.obj[property]); return values; } }); /* Function: $H Shortcut to create a Hash from an Object. */ function $H(obj){ return new Hash(obj); }; /* Script: Color.js Contains the Color class. Authors: - Michael Jackson, <http://ajaxon.com/michael> - Valerio Proietti, <http://mad4milk.net> - Christophe Beyls, <http://www.digitalia.be> License: MIT-style license. */ /* Class: Color Creates a new Color Object, which is an array with some color specific methods. Arguments: color - the hex, the RGB array or the HSB array of the color to create. For HSB colors, you need to specify the second argument. type - a string representing the type of the color to create. needs to be specified if you intend to create the color with HSB values, or an array of HEX values. Can be 'rgb', 'hsb' or 'hex'. Example: (start code) var black = new Color('#000'); var purple = new Color([255,0,255]); // mix black with white and purple, each time at 10% of the new color var darkpurple = black.mix('#fff', purple, 10); $('myDiv').setStyle('background-color', darkpurple); (end) */ var Color = new Class({ initialize: function(color, type){ if (color.isColor) return color; color.isColor = true; type = type || (color.push ? 'rgb' : 'hex'); var rgb, hsb; switch(type){ case 'rgb': rgb = color; hsb = rgb.rgbToHsb(); break; case 'hsb': rgb = color.hsbToRgb(); hsb = color; break; default: rgb = color.hexToRgb(true); hsb = rgb.rgbToHsb(); } rgb.hsb = hsb; return Object.extend(rgb, Color.prototype); }, /* Property: mix Mixes two or more colors with the Color. Arguments: color - a color to mix. you can use as arguments how many colors as you want to mix with the original one. alpha - if you use a number as the last argument, it will be threated as the amount of the color to mix. */ mix: function(){ var colors = $A(arguments); var alpha = ($type(colors[colors.length-1]) == 'number') ? colors.pop() : 50; var rgb = this.copy(); colors.each(function(color){ color = new Color(color); for (var i = 0; i < 3; i++) rgb[i] = Math.round((rgb[i] / 100 * (100 - alpha)) + (color[i] / 100 * alpha)); }); return new Color(rgb, 'rgb'); }, /* Property: invert Inverts the Color. */ invert: function(){ return new Color(this.map(function(value){ return 255 - value; })); }, /* Property: setHue Modifies the hue of the Color, and returns a new one. Arguments: value - the hue to set */ setHue: function(value){ return new Color([value, this.hsb[1], this.hsb[2]], 'hsb'); }, /* Property: setSaturation Changes the saturation of the Color, and returns a new one. Arguments: percent - the percentage of the saturation to set */ setSaturation: function(percent){ return new Color([this.hsb[0], percent, this.hsb[2]], 'hsb'); }, /* Property: setBrightness Changes the brightness of the Color, and returns a new one. Arguments: percent - the percentage of the brightness to set */ setBrightness: function(percent){ return new Color([this.hsb[0], this.hsb[1], percent], 'hsb'); } }); /* Function: $RGB Shortcut to create a new color, based on red, green, blue values. */ function $RGB(r, g, b){ return new Color([r, g, b], 'rgb'); }; /* Function: $HSB Shortcut to create a new color, based on hue, saturation, brightness values. */ function $HSB(h, s, b){ return new Color([h, s, b], 'hsb'); }; /* Class: Array A collection of The Array Object prototype methods. */ Array.extend({ /* Property: rgbToHsb Converts a RGB array to an HSB array. Returns: the HSB array. */ rgbToHsb: function(){ var red = this[0], green = this[1], blue = this[2]; var hue, saturation, brightness; var max = Math.max(red, green, blue), min = Math.min(red, green, blue); var delta = max - min; brightness = max / 255; saturation = (max != 0) ? delta / max : 0; if (saturation == 0){ hue = 0; } else { var rr = (max - red) / delta; var gr = (max - green) / delta; var br = (max - blue) / delta; if (red == max) hue = br - gr; else if (green == max) hue = 2 + rr - br; else hue = 4 + gr - rr; hue /= 6; if (hue < 0) hue++; } return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)]; }, /* Property: hsbToRgb Converts an HSB array to an RGB array. Returns: the RGB array. */ hsbToRgb: function(){ var br = Math.round(this[2] / 100 * 255); if (this[1] == 0){ return [br, br, br]; } else { var hue = this[0] % 360; var f = hue % 60; var p = Math.round((this[2] * (100 - this[1])) / 10000 * 255); var q = Math.round((this[2] * (6000 - this[1] * f)) / 600000 * 255); var t = Math.round((this[2] * (6000 - this[1] * (60 - f))) / 600000 * 255); switch (Math.floor(hue / 60)){ case 0: return [br, t, p]; case 1: return [q, br, p]; case 2: return [p, br, t]; case 3: return [p, q, br]; case 4: return [t, p, br]; case 5: return [br, p, q]; } } return false; } }); /* Script: Window.Base.js Contains Window.onDomReady Authors: - Christophe Beyls, <http://www.digitalia.be> - Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Window Cross browser methods to get the window size, onDomReady method. */ window.extend({ /* Property: window.addEvent same as <Element.addEvent> but allows the event 'domready', which is the same as <window.onDomReady> Credits: (c) Dean Edwards/Matthias Miller/John Resig, remastered for mootools. Arguments: init - the function to execute when the DOM is ready Example: > window.addEvent('domready', function(){alert('the dom is ready')}); */ addEvent: function(type, fn){ if (type == 'domready'){ if (this.loaded) fn(); else if (!this.events || !this.events.domready){ var domReady = function(){ if (this.loaded) return; this.loaded = true; if (this.timer) this.timer = $clear(this.timer); Element.prototype.fireEvent.call(this, 'domready'); this.events.domready = null; }.bind(this); if (document.readyState && this.khtml){ //safari and konqueror this.timer = function(){ if (['loaded','complete'].test(document.readyState)) domReady(); }.periodical(50); } else if (document.readyState && this.ie){ //ie document.write("<script id=ie_ready defer src=javascript:void(0)><\/script>"); $('ie_ready').onreadystatechange = function(){ if (this.readyState == 'complete') domReady(); }; } else { //others this.addEvent("load", domReady); document.addEvent("DOMContentLoaded", domReady); } } } Element.prototype.addEvent.call(this, type, fn); return this; }, /* Property: window.onDomReady Executes the passed in function when the DOM is ready (when the document tree has loaded, not waiting for images). Same as <window.addEvent> ('domready', init). Arguments: init - the function to execute when the DOM is ready Example: > window.addEvent('domready', function(){alert('the dom is ready')}); */ onDomReady: function(init){ return this.addEvent('domready', init); } }); /* Script: Window.Size.js Window cross-browser dimensions methods. Authors: - Christophe Beyls, <http://www.digitalia.be> - Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: window Cross browser methods to get various window dimensions. Warning: All these methods require that the browser operates in strict mode, not quirks mode. */ window.extend({ /* Property: getWidth Returns an integer representing the width of the browser window (without the scrollbar). */ getWidth: function(){ if (this.khtml) return this.innerWidth; if (this.opera) return document.body.clientWidth; return document.documentElement.clientWidth; }, /* Property: getHeight Returns an integer representing the height of the browser window (without the scrollbar). */ getHeight: function(){ if (this.khtml) return this.innerHeight; if (this.opera) return document.body.clientHeight; return document.documentElement.clientHeight; }, /* Property: getScrollWidth Returns an integer representing the scrollWidth of the window. This value is equal to or bigger than <getWidth>. See Also: <http://developer.mozilla.org/en/docs/DOM:element.scrollWidth> */ getScrollWidth: function(){ if (this.ie) return Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth); if (this.khtml) return document.body.scrollWidth; return document.documentElement.scrollWidth; }, /* Property: getScrollHeight Returns an integer representing the scrollHeight of the window. This value is equal to or bigger than <getHeight>. See Also: <http://developer.mozilla.org/en/docs/DOM:element.scrollHeight> */ getScrollHeight: function(){ if (this.ie) return Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight); if (this.khtml) return document.body.scrollHeight; return document.documentElement.scrollHeight; }, /* Property: getScrollLeft Returns an integer representing the scrollLeft of the window (the number of pixels the window has scrolled from the left). See Also: <http://developer.mozilla.org/en/docs/DOM:element.scrollLeft> */ getScrollLeft: function(){ return this.pageXOffset || document.documentElement.scrollLeft; }, /* Property: getScrollTop Returns an integer representing the scrollTop of the window (the number of pixels the window has scrolled from the top). See Also: <http://developer.mozilla.org/en/docs/DOM:element.scrollTop> */ getScrollTop: function(){ return this.pageYOffset || document.documentElement.scrollTop; }, /* Property: getSize Same as <Element.getSize> */ getSize: function(){ return { 'size': {'x': this.getWidth(), 'y': this.getHeight()}, 'scrollSize': {'x': this.getScrollWidth(), 'y': this.getScrollHeight()}, 'scroll': {'x': this.getScrollLeft(), 'y': this.getScrollTop()} }; }, //ignore getPosition: function(){return {'x': 0, 'y': 0}} }); /* Script: Fx.Base.js Contains <Fx.Base> and two Transitions. Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ var Fx = {}; /* Class: Fx.Base Base class for the Mootools Effects (Moo.Fx) library. Options: onStart - the function to execute as the effect begins; nothing (<Class.empty>) by default. onComplete - the function to execute after the effect has processed; nothing (<Class.empty>) by default. transition - the equation to use for the effect see <Fx.Transitions>; default is <Fx.Transitions.sineInOut> duration - the duration of the effect in ms; 500 is the default. unit - the unit is 'px' by default (other values include things like 'em' for fonts or '%'). wait - boolean: to wait or not to wait for a current transition to end before running another of the same instance. defaults to true. fps - the frames per second for the transition; default is 30 */ Fx.Base = new Class({ getOptions: function(){ return { onStart: Class.empty, onComplete: Class.empty, onCancel: Class.empty, transition: Fx.Transitions.sineInOut, duration: 500, unit: 'px', wait: true, fps: 50 }; }, initialize: function(options){ this.element = this.element || null; this.setOptions(this.getOptions(), options); if (this.options.initialize) this.options.initialize.call(this); }, step: function(){ var time = new Date().getTime(); if (time < this.time + this.options.duration){ this.cTime = time - this.time; this.setNow(); this.increase(); } else { this.stop(true); this.now = this.to; this.increase(); this.fireEvent('onComplete', this.element, 10); this.callChain(); } }, /* Property: set Immediately sets the value with no transition. Arguments: to - the point to jump to Example: >var myFx = new Fx.Style('myElement', 'opacity').set(0); //will make it immediately transparent */ set: function(to){ this.now = to; this.increase(); return this; }, setNow: function(){ this.now = this.compute(this.from, this.to); }, compute: function(from, to){ return this.options.transition(this.cTime, from, (to - from), this.options.duration); }, /* Property: start Executes an effect from one position to the other. Arguments: from - integer: staring value to - integer: the ending value Examples: >var myFx = new Fx.Style('myElement', 'opacity').start(0,1); //display a transition from transparent to opaque. */ start: function(from, to){ if (!this.options.wait) this.stop(); else if (this.timer) return this; this.from = from; this.to = to; this.time = new Date().getTime(); this.timer = this.step.periodical(Math.round(1000/this.options.fps), this); this.fireEvent('onStart', this.element); return this; }, /* Property: stop Stops the transition. */ stop: function(end){ if (!this.timer) return this; this.timer = $clear(this.timer); if (!end) this.fireEvent('onCancel', this.element); return this; }, //compat custom: function(from, to){return this.start(from, to)}, clearTimer: function(end){return this.stop(end)} }); Fx.Base.implement(new Chain); Fx.Base.implement(new Events); Fx.Base.implement(new Options); /* Class: Fx.Transitions A collection of transition equations for use with the <Fx.Base> Class. See Also: <Fx.Transitions.js> for a whole bunch of transitions. Credits: Easing Equations, (c) 2003 Robert Penner (http://www.robertpenner.com/easing/), Open Source BSD License. */ Fx.Transitions = { /* Property: linear */ linear: function(t, b, c, d){ return c*t/d + b; }, /* Property: sineInOut */ sineInOut: function(t, b, c, d){ return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; } }; /* Script: Fx.CSS.js Css parsing class for effects. Required by <Fx.Style>, <Fx.Styles>, <Fx.Elements>. No documentation needed, as its used internally. Authors: - Christophe Beyls, <http://www.digitalia.be> - Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ Fx.CSS = { select: function(property, to){ if (property.test(/color/i)) return this.Color; if (to.test && to.test(' ')) return this.Multi; return this.Single; }, parse: function(el, property, fromTo){ if (!fromTo.push) fromTo = [fromTo]; var from = fromTo[0], to = fromTo[1]; if (!to && to != 0){ to = from; from = el.getStyle(property); } var css = this.select(property, to); return {from: css.parse(from), to: css.parse(to), css: css}; } }; Fx.CSS.Single = { parse: function(value){ return parseFloat(value); }, getNow: function(from, to, fx){ return fx.compute(from, to); }, getValue: function(value, unit){ return value+unit; } }; Fx.CSS.Multi = { parse: function(value){ return value.push ? value : value.split(' ').map(function(v){ return parseFloat(v); }); }, getNow: function(from, to, fx){ var now = []; for (var i = 0; i < from.length; i++) now[i] = fx.compute(from[i], to[i]); return now; }, getValue: function(value, unit){ return value.join(unit+' ')+unit; } }; Fx.CSS.Color = { parse: function(value){ return value.push ? value : value.hexToRgb(true); }, getNow: function(from, to, fx){ var now = []; for (var i = 0; i < from.length; i++) now[i] = Math.round(fx.compute(from[i], to[i])); return now; }, getValue: function(value){ return 'rgb('+value.join(',')+')'; } }; /* Script: Fx.Style.js Contains <Fx.Style> Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Fx.Style The Style effect; Extends <Fx.Base>, inherits all its properties. Used to transition any css property from one value to another. Includes colors. Colors must be in hex format. Arguments: el - the $(element) to apply the style transition to property - the property to transition options - the Fx.Base options (see: <Fx.Base>) Example: >var marginChange = new Fx.Style('myElement', 'margin-top', {duration:500}); >marginChange.start(10, 100); */ Fx.Style = Fx.Base.extend({ initialize: function(el, property, options){ this.element = $(el); this.property = property; this.parent(options); }, /* Property: hide Same as <Fx.Base.set> (0) */ hide: function(){ return this.set(0); }, setNow: function(){ this.now = this.css.getNow(this.from, this.to, this); }, set: function(to){ this.css = Fx.CSS.select(this.property, to); return this.parent(this.css.parse(to)); }, /* Property: start displays the transition to the value/values passed in Example: (start code) var var marginChange = new Fx.Style('myElement', 'margin-top', {duration:500}); marginChange.start(10); //tries to read current margin top value and goes from current to 10 (end) */ start: function(from, to){ if (this.timer && this.options.wait) return this; var parsed = Fx.CSS.parse(this.element, this.property, [from, to]); this.css = parsed.css; return this.parent(parsed.from, parsed.to); }, increase: function(){ this.element.setStyle(this.property, this.css.getValue(this.now, this.options.unit)); } }); /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: effect Applies an <Fx.Style> to the Element; This a shortcut for <Fx.Style>. Example: >var myEffect = $('myElement').effect('height', {duration: 1000, transition: Fx.Transitions.linear}); >myEffect.start(10, 100); */ effect: function(property, options){ return new Fx.Style(this, property, options); } }); /* Script: Fx.Styles.js Contains <Fx.Styles> Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Fx.Styles Allows you to animate multiple css properties at once; Extends <Fx.Base>, inherits all its properties. Includes colors. Colors must be in hex format. Arguments: el - the $(element) to apply the styles transition to options - the fx options (see: <Fx.Base>) Example: (start code) var myEffects = new Fx.Styles('myElement', {duration: 1000, transition: Fx.Transitions.linear}); //height from 10 to 100 and width from 900 to 300 myEffects.start({ 'height': [10, 100], 'width': [900, 300] }); //or height from current height to 100 and width from current width to 300 myEffects.start({ 'height': 100, 'width': 300 }); (end) */ Fx.Styles = Fx.Base.extend({ initialize: function(el, options){ this.element = $(el); this.parent(options); }, setNow: function(){ for (var p in this.from) this.now[p] = this.css[p].getNow(this.from[p], this.to[p], this); }, set: function(to){ var parsed = {}; this.css = {}; for (var p in to){ this.css[p] = Fx.CSS.select(p, to[p]); parsed[p] = this.css[p].parse(to[p]); } return this.parent(parsed); }, /* Property: start The function you'll actually use to execute a transition. Arguments: an object Example: see <Fx.Styles> */ start: function(obj){ if (this.timer && this.options.wait) return this; this.now = {}; this.css = {}; var from = {}, to = {}; for (var p in obj){ var parsed = Fx.CSS.parse(this.element, p, obj[p]); from[p] = parsed.from; to[p] = parsed.to; this.css[p] = parsed.css; } return this.parent(from, to); }, increase: function(){ for (var p in this.now) this.element.setStyle(p, this.css[p].getValue(this.now[p], this.options.unit)); } }); /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: effects Applies an <Fx.Styles> to the Element; This a shortcut for <Fx.Styles>. Example: >var myEffects = $(myElement).effects({duration: 1000, transition: Fx.Transitions.sineInOut}); >myEffects.start({'height': [10, 100], 'width': [900, 300]}); */ effects: function(options){ return new Fx.Styles(this, options); } }); /* Script: Fx.Elements.js Contains <Fx.Elements> Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Fx.Elements Fx.Elements allows you to apply any number of styles transitions to a selection of elements. Includes colors (must be in hex format). Arguments: elements - a collection of elements the effects will be applied to. options - same as <Fx.Base> options. */ Fx.Elements = Fx.Base.extend({ initialize: function(elements, options){ this.elements = $$(elements); this.parent(options); }, setNow: function(){ for (var i in this.from){ var iFrom = this.from[i], iTo = this.to[i], iCss = this.css[i], iNow = this.now[i] = {}; for (var p in iFrom) iNow[p] = iCss[p].getNow(iFrom[p], iTo[p], this); } }, set: function(to){ var parsed = {}; this.css = {}; for (var i in to){ var iTo = to[i], iCss = this.css[i] = {}, iParsed = parsed[i] = {}; for (var p in iTo){ iCss[p] = Fx.CSS.select(p, iTo[p]); iParsed[p] = iCss[p].parse(iTo[p]); } } return this.parent(parsed); }, /* Property: start Applies the passed in style transitions to each object named (see example). Each item in the collection is refered to as a numerical string ("1" for instance). The first item is "0", the second "1", etc. Example: (start code) var myElementsEffects = new Fx.Elements($$('a')); myElementsEffects.start({ '0': { //let's change the first element's opacity and width 'opacity': [0,1], 'width': [100,200] }, '1': { //and the second one's opacity 'opacity': [0.2, 0.5] } }); (end) */ start: function(obj){ if (this.timer && this.options.wait) return this; this.now = {}; this.css = {}; var from = {}, to = {}; for (var i in obj){ var iProps = obj[i], iFrom = from[i] = {}, iTo = to[i] = {}, iCss = this.css[i] = {}; for (var p in iProps){ var parsed = Fx.CSS.parse(this.elements[i], p, iProps[p]); iFrom[p] = parsed.from; iTo[p] = parsed.to; iCss[p] = parsed.css; } } return this.parent(from, to); }, increase: function(){ for (var i in this.now){ var iNow = this.now[i], iCss = this.css[i]; for (var p in iNow) this.elements[i].setStyle(p, iCss[p].getValue(iNow[p], this.options.unit)); } } }); /* Script: Fx.Scroll.js Contains <Fx.Scroll> Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Fx.Scroll Scroll any element with an overflow, including the window element. Arguments: element - the element to scroll options - same as <Fx.Base> options. */ Fx.Scroll = Fx.Base.extend({ initialize: function(element, options){ this.now = []; this.element = $(element); this.addEvent('onStart', function(){ this.element.addEvent('mousewheel', this.stop.bind(this, false)); }.bind(this)); this.removeEvent('onComplete', function(){ this.element.removeEvent('mousewheel', this.stop.bind(this, false)); }.bind(this)); this.parent(options); }, setNow: function(){ for (var i = 0; i < 2; i++) this.now[i] = this.compute(this.from[i], this.to[i]); }, /* Property: scrollTo Scrolls the chosen element to the x/y coordinates. Arguments: x - the x coordinate to scroll the element to y - the y coordinate to scroll the element to */ scrollTo: function(x, y){ if (this.timer && this.options.wait) return this; var el = this.element.getSize(); var values = {'x': x, 'y': y}; for (var z in el.size){ var max = el.scrollSize[z] - el.size[z]; if ($chk(values[z])) values[z] = ($type(values[z]) == 'number') ? Math.max(Math.min(values[z], max), 0) : max; else values[z] = el.scroll[z]; } return this.start([el.scroll.x, el.scroll.y], [values.x, values.y]); }, /* Property: toTop Scrolls the chosen element to its maximum top. */ toTop: function(){ return this.scrollTo(false, 0); }, /* Property: toBottom Scrolls the chosen element to its maximum bottom. */ toBottom: function(){ return this.scrollTo(false, 'full'); }, /* Property: toLeft Scrolls the chosen element to its maximum left. */ toLeft: function(){ return this.scrollTo(0, false); }, /* Property: toRight Scrolls the chosen element to its maximum right. */ toRight: function(){ return this.scrollTo('full', false); }, /* Property: toElement Scrolls the specified element to the position the passed in element is found. Only usable if the chosen element is == window. Arguments: el - the $(element) to scroll the window to */ toElement: function(el){ return this.scrollTo($(el).getLeft(), $(el).getTop()); }, increase: function(){ this.element.scrollTo(this.now[0], this.now[1]); } }); /* Script: Fx.Slide.js Contains <Fx.Slide> Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Fx.Slide The slide effect; slides an element in horizontally or vertically, the contents will fold inside. Extends <Fx.Base>, inherits all its properties. Note: This effect works on any block element, but the element *cannot be positioned*; no margins or absolute positions. To position the element, put it inside another element (a wrapper div, for instance) and position that instead. Options: mode - set it to vertical or horizontal. Defaults to vertical. and all the <Fx.Base> options Example: (start code) var mySlider = new Fx.Slide('myElement', {duration: 500}); mySlider.toggle() //toggle the slider up and down. (end) */ Fx.Slide = Fx.Base.extend({ initialize: function(el, options){ this.element = $(el).setStyle('margin', 0); this.wrapper = new Element('div').injectAfter(this.element).setStyle('overflow', 'hidden').adopt(this.element); this.setOptions({'mode': 'vertical'}, options); this.now = []; this.parent(this.options); }, setNow: function(){ for (var i = 0; i < 2; i++) this.now[i] = this.compute(this.from[i], this.to[i]); }, vertical: function(){ this.margin = 'top'; this.layout = 'height'; this.offset = this.element.offsetHeight; return [this.element.getStyle('margin-top').toInt(), this.wrapper.getStyle('height').toInt()]; }, horizontal: function(){ this.margin = 'left'; this.layout = 'width'; this.offset = this.element.offsetWidth; return [this.element.getStyle('margin-left').toInt(), this.wrapper.getStyle('width').toInt()]; }, /* Property: slideIn slides the elements in view horizontally or vertically, depending on the mode parameter or options.mode. */ slideIn: function(mode){ return this.start(this[mode || this.options.mode](), [0, this.offset]); }, /* Property: slideOut slides the elements out of the view horizontally or vertically, depending on the mode parameter or options.mode. */ slideOut: function(mode){ return this.start(this[mode || this.options.mode](), [-this.offset, 0]); }, /* Property: hide Hides the element without a transition. */ hide: function(mode){ this[mode || this.options.mode](); return this.set([-this.offset, 0]); }, /* Property: show Shows the element without a transition. */ show: function(mode){ this[mode || this.options.mode](); return this.set([0, this.offset]); }, /* Property: toggle Slides in or Out the element, depending on its state */ toggle: function(mode){ if (this.wrapper.offsetHeight == 0 || this.wrapper.offsetWidth == 0) return this.slideIn(mode); else return this.slideOut(mode); }, increase: function(){ this.element.setStyle('margin-'+this.margin, this.now[0]+this.options.unit); this.wrapper.setStyle(this.layout, this.now[1]+this.options.unit); } }); /* Script: Fx.Transitions.js Cool transitions, to be used with all the effects. Author: Robert Penner, <http://www.robertpenner.com/easing/>, modified to be used with mootools. License: Easing Equations v1.5, (c) 2003 Robert Penner, all rights reserved. Open Source BSD License. */ /* Class: Fx.Transitions A collection of tweaning transitions for use with the <Fx.Base> classes. */ Fx.Transitions = { /* Property: linear */ linear: function(t, b, c, d){ return c*t/d + b; }, /* Property: quadIn */ quadIn: function(t, b, c, d){ return c*(t/=d)*t + b; }, /* Property: quadOut */ quadOut: function(t, b, c, d){ return -c *(t/=d)*(t-2) + b; }, /* Property: quadInOut */ quadInOut: function(t, b, c, d){ if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, /* Property: cubicIn */ cubicIn: function(t, b, c, d){ return c*(t/=d)*t*t + b; }, /* Property: cubicOut */ cubicOut: function(t, b, c, d){ return c*((t=t/d-1)*t*t + 1) + b; }, /* Property: cubicInOut */ cubicInOut: function(t, b, c, d){ if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, /* Property: quartIn */ quartIn: function(t, b, c, d){ return c*(t/=d)*t*t*t + b; }, /* Property: quartOut */ quartOut: function(t, b, c, d){ return -c * ((t=t/d-1)*t*t*t - 1) + b; }, /* Property: quartInOut */ quartInOut: function(t, b, c, d){ if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, /* Property: quintIn */ quintIn: function(t, b, c, d){ return c*(t/=d)*t*t*t*t + b; }, /* Property: quintOut */ quintOut: function(t, b, c, d){ return c*((t=t/d-1)*t*t*t*t + 1) + b; }, /* Property: quintInOut */ quintInOut: function(t, b, c, d){ if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, /* Property: sineIn */ sineIn: function(t, b, c, d){ return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, /* Property: sineOut */ sineOut: function(t, b, c, d){ return c * Math.sin(t/d * (Math.PI/2)) + b; }, /* Property: sineInOut */ sineInOut: function(t, b, c, d){ return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, /* Property: expoIn */ expoIn: function(t, b, c, d){ return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, /* Property: expoOut */ expoOut: function(t, b, c, d){ return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, /* Property: expoInOut */ expoInOut: function(t, b, c, d){ if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, /* Property: circIn */ circIn: function(t, b, c, d){ return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, /* Property: circOut */ circOut: function(t, b, c, d){ return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, /* Property: circInOut */ circInOut: function(t, b, c, d){ if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, /* Property: elasticIn */ elasticIn: function(t, b, c, d, a, p){ if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (!a) a = 1; if (a < Math.abs(c)){ a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin(c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, /* Property: elasticOut */ elasticOut: function(t, b, c, d, a, p){ if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (!a) a = 1; if (a < Math.abs(c)){ a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin(c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, /* Property: elasticInOut */ elasticInOut: function(t, b, c, d, a, p){ if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (!a) a = 1; if (a < Math.abs(c)){ a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin(c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, /* Property: backIn */ backIn: function(t, b, c, d, s){ if (!s) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, /* Property: backOut */ backOut: function(t, b, c, d, s){ if (!s) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, /* Property: backInOut */ backInOut: function(t, b, c, d, s){ if (!s) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, /* Property: bounceIn */ bounceIn: function(t, b, c, d){ return c - Fx.Transitions.bounceOut (d-t, 0, c, d) + b; }, /* Property: bounceOut */ bounceOut: function(t, b, c, d){ if ((t/=d) < (1/2.75)){ return c*(7.5625*t*t) + b; } else if (t < (2/2.75)){ return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)){ return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, /* Property: bounceInOut */ bounceInOut: function(t, b, c, d){ if (t < d/2) return Fx.Transitions.bounceIn(t*2, 0, c, d) * .5 + b; return Fx.Transitions.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; } }; /* Script: Drag.Base.js Contains <Drag.Base>, <Element.makeResizable> Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ var Drag = {}; /* Class: Drag.Base Modify two css properties of an element based on the position of the mouse. Arguments: el - the $(element) to apply the transformations to. options - optional. The options object. Options: handle - the $(element) to act as the handle for the draggable element. defaults to the $(element) itself. modifiers - an object. see Modifiers Below. onStart - optional, function to execute when the user starts to drag (on mousedown); onComplete - optional, function to execute when the user completes the drag. onDrag - optional, function to execute at every step of the drag limit - an object, see Limit below. snap - optional, the distance you have to drag before the element starts to respond to the drag. defaults to false modifiers: x - string, the style you want to modify when the mouse moves in an horizontal direction. defaults to 'left' y - string, the style you want to modify when the mouse moves in a vertical direction. defaults to 'top' limit: x - array with start and end limit relative to modifiers.x y - array with start and end limit relative to modifiers.y */ Drag.Base = new Class({ getOptions: function(){ return { handle: false, unit: 'px', onStart: Class.empty, onBeforeStart: Class.empty, onComplete: Class.empty, onSnap: Class.empty, onDrag: Class.empty, limit: false, modifiers: {x: 'left', y: 'top'}, snap: 6 }; }, initialize: function(el, options){ this.setOptions(this.getOptions(), options); this.element = $(el); this.handle = $(this.options.handle) || this.element; this.mouse = {'now': {}, 'pos': {}}; this.value = {'start': {}, 'now': {}}; this.bound = {'start': this.start.bindWithEvent(this)}; this.attach(); if (this.options.initialize) this.options.initialize.call(this); }, attach: function(){ this.handle.addEvent('mousedown', this.bound.start); }, start: function(event){ this.fireEvent('onBeforeStart', this.element); this.mouse.start = event.page; var limit = this.options.limit; this.limit = {'x': [], 'y': []}; for (var z in this.options.modifiers){ this.value.now[z] = this.element.getStyle(this.options.modifiers[z]).toInt(); this.mouse.pos[z] = event.page[z] - this.value.now[z]; if (limit && limit[z]){ for (var i = 0; i < 2; i++){ if ($chk(limit[z][i])) this.limit[z][i] = limit[z][i].apply ? limit[z][i].call(this) : limit[z][i]; } } } this.bound.drag = this.drag.bindWithEvent(this); this.bound.stop = this.stop.bind(this); this.bound.move = this.options.snap ? this.checkAndDrag.bindWithEvent(this) : this.bound.drag; document.addEvent('mousemove', this.bound.move); document.addEvent('mouseup', this.bound.stop); this.fireEvent('onStart', this.element); event.stop(); }, checkAndDrag: function(event){ var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2))); if (distance > this.options.snap){ document.removeEvent('mousemove', this.bound.move); this.bound.move = this.bound.drag; document.addEvent('mousemove', this.bound.move); this.drag(event); this.fireEvent('onSnap', this.element); } event.stop(); }, drag: function(event){ this.out = false; this.mouse.now = event.page; for (var z in this.options.modifiers){ this.value.now[z] = this.mouse.now[z] - this.mouse.pos[z]; if (this.limit[z]){ if ($chk(this.limit[z][1]) && (this.value.now[z] > this.limit[z][1])){ this.value.now[z] = this.limit[z][1]; this.out = true; } else if ($chk(this.limit[z][0]) && (this.value.now[z] < this.limit[z][0])){ this.value.now[z] = this.limit[z][0]; this.out = true; } } this.element.setStyle(this.options.modifiers[z], this.value.now[z] + this.options.unit); } this.fireEvent('onDrag', this.element); event.stop(); }, detach: function(){ this.handle.removeEvent('mousedown', this.bound.start); }, stop: function(){ document.removeEvent('mousemove', this.bound.move); document.removeEvent('mouseup', this.bound.stop); this.fireEvent('onComplete', this.element); } }); Drag.Base.implement(new Events); Drag.Base.implement(new Options); /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: makeResizable Makes an element resizable (by dragging) with the supplied options. Arguments: options - see <Drag.Base> for acceptable options. */ makeResizable: function(options){ return new Drag.Base(this, Object.extend(options || {}, {modifiers: {x: 'width', y: 'height'}})); } }); /* Script: Drag.Move.js Contains <Drag.Move>, <Element.makeDraggable> Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Drag.Move Extends <Drag.Base>, has additional functionality for dragging an element, support snapping and droppables. Drag.move supports either position absolute or relative. If no position is found, absolute will be set. Arguments: el - the $(element) to apply the drag to. options - optional. see Options below. Options: all the drag.Base options, plus: container - an element, will fill automatically limiting options based on the $(element) size and position. defaults to false (no limiting) droppables - an array of elements you can drop your draggable to. */ Drag.Move = Drag.Base.extend({ getExtended: function(){ return { droppables: [], container: false, overflown: [] } }, initialize: function(el, options){ this.setOptions(this.getExtended(), options); this.element = $(el); this.position = this.element.getStyle('position'); this.droppables = $$(this.options.droppables); if (!['absolute', 'relative'].test(this.position)) this.position = 'absolute'; var top = this.element.getStyle('top').toInt(); var left = this.element.getStyle('left').toInt(); if (this.position == 'absolute'){ top = $chk(top) ? top : this.element.getTop(); left = $chk(left) ? left : this.element.getLeft(); } else { top = $chk(top) ? top : 0; left = $chk(left) ? left : 0; } this.element.setStyles({ 'top': top+'px', 'left': left+'px', 'position': this.position }); this.parent(this.element, this.options); }, start: function(event){ this.container = $(this.options.container); if (this.container){ var cont = this.container.getCoordinates(); var el = this.element.getCoordinates(); if (this.position == 'absolute'){ this.options.limit = { 'x': [cont.left, cont.right - el.width], 'y': [cont.top, cont.bottom - el.height] }; } else { var diffx = el.left - this.element.getStyle('left').toInt(); var diffy = el.top - this.element.getStyle('top').toInt(); this.options.limit = { 'y': [-(diffy) + cont.top, cont.bottom - diffy - el.height], 'x': [-(diffx) + cont.left, cont.right - diffx - el.width] }; } } this.parent(event); }, drag: function(event){ this.parent(event); if (this.out) return this; this.droppables.each(function(drop){ if (this.checkAgainst($(drop))){ if (!drop.overing) drop.fireEvent('over', [this.element, this]); drop.overing = true; } else { if (drop.overing) drop.fireEvent('leave', [this.element, this]); drop.overing = false; } }, this); return this; }, checkAgainst: function(el){ el = el.getCoordinates(this.options.overflown); return (this.mouse.now.x > el.left && this.mouse.now.x < el.right && this.mouse.now.y < el.bottom && this.mouse.now.y > el.top); }, stop: function(){ this.parent(); this.timer = $clear(this.timer); if (this.out) return this; var dropped = false; this.droppables.each(function(drop){ if (this.checkAgainst(drop)){ drop.fireEvent('drop', [this.element, this]); dropped = true; } }, this); if (!dropped) this.element.fireEvent('drop', this); return this; } }); /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: makeDraggable Makes an element draggable with the supplied options. Arguments: options - see <Drag.Move> and <Drag.Base> for acceptable options. */ makeDraggable: function(options){ return new Drag.Move(this, options); } }); /* Script: XHR.js Contains the basic XMLHttpRequest Class Wrapper. Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: XHR Basic XMLHttpRequest Wrapper. Arguments: Options: method - 'post' or 'get' - the prototcol for the request; optional, defaults to 'post'. async - boolean: asynchronous option; true uses asynchronous requests. Defaults to true. onRequest - function to execute when the XHR request is fired. onSuccess - function to execute when the XHR request completes. onStateChange - function to execute when the state of the XMLHttpRequest changes. onFailure - function to execute when the state of the XMLHttpRequest changes. headers - accepts an object, that will be set to request headers. Example: >var myXHR = new XHR({method: 'get'}).send('http://site.com/requestHandler.php', 'name=john&lastname=doe'); */ var XHR = new Class({ getOptions: function(){ return { method: 'post', async: true, onRequest: Class.empty, onStateChange: Class.empty, onSuccess: Class.empty, onFailure: Class.empty, headers: {}, isSuccess: this.isSuccess } }, initialize: function(options){ this.transport = window.XMLHttpRequest ? new XMLHttpRequest() : (window.ie ? new ActiveXObject('Microsoft.XMLHTTP') : false); this.setOptions(this.getOptions(), options); if (!this.transport) return; this.headers = {}; if (this.options.initialize) this.options.initialize.call(this); }, onStateChange: function(){ this.fireEvent('onStateChange', this.transport); if (this.transport.readyState != 4) return; var status = 0; try {status = this.transport.status} catch (e){} if (this.options.isSuccess(status)) this.onSuccess(); else this.onFailure(); this.transport.onreadystatechange = Class.empty; }, isSuccess: function(status){ return ((status >= 200) && (status < 300)); }, onSuccess: function(){ this.response = { 'text': this.transport.responseText, 'xml': this.transport.responseXML }; this.fireEvent('onSuccess', [this.response.text, this.response.xml]); this.callChain(); }, onFailure: function(){ this.fireEvent('onFailure', this.transport); }, setHeader: function(name, value){ this.headers[name] = value; return this; }, send: function(url, data){ this.fireEvent('onRequest'); this.transport.open(this.options.method, url, this.options.async); this.transport.onreadystatechange = this.onStateChange.bind(this); if ((this.options.method == 'post') && this.transport.overrideMimeType) this.setHeader('Connection', 'close'); Object.extend(this.headers, this.options.headers); for (var type in this.headers) this.transport.setRequestHeader(type, this.headers[type]); this.transport.send(data); return this; } }); XHR.implement(new Chain); XHR.implement(new Events); XHR.implement(new Options); /* Script: Ajax.js Contains the <Ajax> class. Also contains methods to generate querystings from forms and Objects. Authors: - Valerio Proietti, <http://mad4milk.net> - Christophe Beyls, <http://digitalia.be> Credits: Loosely based on the version from prototype.js <http://prototype.conio.net> License: MIT-style license. */ /* Class: Ajax An Ajax class, For all your asynchronous needs. Inherits methods, properties and options from <XHR>. Arguments: url - the url pointing to the server-side script. options - optional, an object containing options. Options: postBody - if method is post, you can write parameters here. Can be a querystring, an object or a Form element. onComplete - function to execute when the ajax request completes. update - $(element) to insert the response text of the XHR into, upon completion of the request. evalScripts - boolean; default is false. Execute scripts in the response text onComplete. evalResponse - boolean; should you eval the whole responsetext? I dont know, but this option makes it possible. encoding - the encoding, defaults to utf-8. Example: >var myAjax = new Ajax(url, {method: 'get'}).request(); */ var Ajax = XHR.extend({ moreOptions: function(){ return { postBody: null, update: null, onComplete: Class.empty, evalScripts: false, evalResponse: false, encoding: 'utf-8' }; }, initialize: function(url, options){ this.addEvent('onSuccess', this.onComplete); this.setOptions(this.moreOptions(), options); this.parent(this.options); if (!['post', 'get'].test(this.options.method)){ this._method = '_method='+this.options.method; this.options.method = 'post'; } if (this.options.method == 'post'){ var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : ''; this.setHeader('Content-type', 'application/x-www-form-urlencoded' + encoding); } this.setHeader('X-Requested-With', 'XMLHttpRequest'); this.setHeader('Accept', 'text/javascript, text/html, application/xml, text/xml, */*'); this.url = url; }, onComplete: function(){ if (this.options.update) $(this.options.update).setHTML(this.response.text); if (this.options.evalResponse) eval(this.response.text); if (this.options.evalScripts) this.evalScripts.delay(30, this); this.fireEvent('onComplete', [this.response.text, this.response.xml], 20); }, /* Property: request Executes the ajax request. Example: >var myAjax = new Ajax(url, {method: 'get'}); >myAjax.request(); OR >new Ajax(url, {method: 'get'}).request(); */ request: function(){ var data = null; switch ($type(this.options.postBody)){ case 'element': data = $(this.options.postBody).toQueryString(); break; case 'object': data = Object.toQueryString(this.options.postBody); break; case 'string': data = this.options.postBody; } if (this._method) data = (data) ? [this._method, data].join('&') : this._method; return this.send(this.url, data); }, /* Property: evalScripts Executes scripts in the response text */ evalScripts: function(){ var script, regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi; while ((script = regexp.exec(this.response.text))) eval(script[1]); } }); /* Section: Object related Functions */ /* Function: Object.toQueryString Generates a querystring from key/pair values in an object Arguments: source - the object to generate the querystring from. Returns: the query string. Example: >Object.toQueryString({apple: "red", lemon: "yellow"}); //returns "apple=red&lemon=yellow" */ Object.toQueryString = function(source){ var queryString = []; for (var property in source) queryString.push(encodeURIComponent(property)+'='+encodeURIComponent(source[property])); return queryString.join('&'); }; /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: send Sends a form with an ajax post request Arguments: options - option collection for ajax request. See <Ajax> for the options list. Returns: The Ajax Class Instance Example: (start code) <form id="myForm" action="submit.php"> <input name="email" value="bob@bob.com"> <input name="zipCode" value="90210"> </form> <script> $('myForm').send() </script> (end) */ send: function(options){ options = Object.extend(options || {}, {postBody: this.toQueryString(), method: 'post'}); return new Ajax(this.getProperty('action'), options).request(); }, /* Property: toQueryString Reads the children inputs of the Element and generates a query string, based on their values. Used internally in <Ajax> Example: (start code) <form id="myForm" action="submit.php"> <input name="email" value="bob@bob.com"> <input name="zipCode" value="90210"> </form> <script> $('myForm').toQueryString() </script> (end) Returns: email=bob@bob.com&zipCode=90210 */ toObject: function(){ var obj = {}; $$(this.getElementsByTagName('input'), this.getElementsByTagName('select'), this.getElementsByTagName('textarea')).each(function(el){ var name = $(el).name; var value = el.getValue(); if ((value !== false) && name) obj[name] = value; }); return obj; }, toQueryString: function(){ return Object.toQueryString(this.toObject()); } }); /* Script: Cookie.js A cookie reader/creator Author: Christophe Beyls, <http://www.digitalia.be> Credits: based on the functions by Peter-Paul Koch (http://quirksmode.org) */ /* Class: Cookie Class for creating, getting, and removing cookies. */ var Cookie = { /* Property: set Sets a cookie in the browser. Arguments: key - the key (name) for the cookie value - the value to set, cannot contain semicolons options - an object representing the Cookie options. See Options below: Options: domain - the domain the Cookie belongs to. If you want to share the cookie with pages located on a different domain, you have to set this value. Defaults to the current domain. path - the path the Cookie belongs to. If you want to share the cookie with pages located in a different path, you have to set this value, for example to "/" to share the cookie with all pages on the domain. Defaults to the current path. duration - the duration of the Cookie before it expires, in days. If set to false or 0, the cookie will be a session cookie that expires when the browser is closed. Defaults to 365 days. Example: >Cookie.set("username", "Aaron", {duration: 5}); //save this for 5 days >Cookie.set("username", "Jack", {duration: false}); //session cookie */ set: function(key, value, options){ options = Object.extend({ domain: false, path: false, duration: 365 }, options || {}); value = escape(value); if (options.domain) value += "; domain=" + options.domain; if (options.path) value += "; path=" + options.path; if (options.duration){ var date = new Date(); date.setTime(date.getTime() + (options.duration * 86400000)); value += "; expires=" + date.toGMTString(); } document.cookie = key + "=" + value; }, /* Property: get Gets the value of a cookie. Arguments: key - the name of the cookie you wish to retrieve. Returns: The cookie string value, or false if not found. Example: >Cookie.get("username") //returns Aaron */ get: function(key){ var value = document.cookie.match('(?:^|;)\\s*'+key+'=([^;]*)'); return value ? unescape(value[1]) : false; }, /* Property: remove Removes a cookie from the browser. Arguments: key - the name of the cookie to remove Examples: >Cookie.remove("username") //bye-bye Aaron */ remove: function(key){ this.set(key, '', {duration: -1}); } }; /* Script: Json.js Simple Json parser and Stringyfier, See: <http://www.json.org/> Authors: - Christophe Beyls, <http://www.digitalia.be> - Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Json Simple Json parser and Stringyfier, See: <http://www.json.org/> */ var Json = { /* Property: toString Converts an object to a string, to be passed in server-side scripts as a parameter. Although its not normal usage for this class, this method can also be used to convert functions and arrays to strings. Arguments: obj - the object to convert to string Returns: A json string Example: (start code) Json.toString({apple: 'red', lemon: 'yellow'}); "{"apple":"red","lemon":"yellow"}" //don't get hung up on the quotes; it's just a string. (end) */ toString: function(obj){ switch ($type(obj)){ case 'string': return '"'+obj.replace(new RegExp('(["\\\\])', 'g'), '\\$1')+'"'; case 'array': return '['+ obj.map(function(ar){ return Json.toString(ar); }).join(',') +']'; case 'object': var string = []; for (var property in obj) string.push('"'+property+'":'+Json.toString(obj[property])); return '{'+string.join(',')+'}'; } return String(obj); }, /* Property: evaluate converts a json string to an javascript Object. Arguments: str - the string to evaluate. Example: >var myObject = Json.evaluate('{"apple":"red","lemon":"yellow"}'); >//myObject will become {apple: 'red', lemon: 'yellow'} */ evaluate: function(str){ return eval('(' + str + ')'); } }; /* Script: Json.Remote.js Contains <Json.Remote>. Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Json.Remote Wrapped XHR with automated sending and receiving of Javascript Objects in Json Format. Arguments: url - the url you want to send your object to. options - see <XHR> options Example: this code will send user information based on name/last name (start code) var jSonRequest = new Json.Remote("http://site.com/tellMeAge.php", onComplete: function(person){ alert(person.age); //is 25 years alert(person.height); //is 170 cm alert(person.weight); //is 120 kg }).send({'name': 'John', 'lastName': 'Doe'}); (end) */ Json.Remote = XHR.extend({ initialize: function(url, options){ this.url = url; this.addEvent('onSuccess', this.onComplete); this.parent(options); this.setHeader('X-Request', 'JSON'); }, send: function(obj){ return this.parent(this.url, 'json='+Json.toString(obj)); }, onComplete: function(){ this.fireEvent('onComplete', Json.evaluate(this.response.text)); } }); /* Script: Assets.js provides dynamic loading for images, css and javascript files. Authors: - Valerio Proietti, <http://mad4milk.net> - Fredrik Branstrom <http://fredrik.branstrom.name> - Yaroslaff Fedin <http://inviz.ru> License: MIT-style license. */ var Asset = { /* Property: javascript injects into the page a javascript file. Arguments: source - the path of the javascript file properties - some additional attributes you might want to add to the script element Example: > new Asset.javascript('/scripts/myScript.js', {id: 'myScript'}); */ javascript: function(source, properties){ return Asset.create('script', { 'type': 'text/javascript', 'src': source }, properties, true); }, /* Property: css injects into the page a css file. Arguments: source - the path of the css file properties - some additional attributes you might want to add to the link element Example: > new Asset.css('/css/myStyle.css', {id: 'myStyle', title: 'myStyle'}); */ css: function(source, properties){ return Asset.create('link', { 'rel': 'stylesheet', 'media': 'screen', 'type': 'text/css', 'href': source }, properties, true); }, /* Property: image Preloads an image and returns the img element. does not inject it to the page. Arguments: source - the path of the image file properties - some additional attributes you might want to add to the img element Example: > new Asset.image('/images/myImage.png', {id: 'myImage', title: 'myImage', onload: myFunction}); Returns: the img element. you can inject it anywhere you want with <Element.injectInside>/<Element.injectAfter>/<Element.injectBefore> */ image: function(source, properties){ properties = Object.extend({ 'src': source, 'onload': Class.empty, 'onabort': Class.empty, 'onerror': Class.empty }, properties || {}); var image = new Image(); image.onload = function(){ if (arguments.callee.done) return false; arguments.callee.done = true; this.onload = null; return properties.onload.call(this); }; image.onerror = properties.onerror; image.onabort = properties.onabort; image.src = properties.src; return Asset.create('img', properties); }, /* Property: images Preloads an array of images (as strings) and returns an array of img elements. does not inject them to the page. Arguments: sources - array, the paths of the image files options - object, see below Options: onComplete - a function to execute when all image files are loaded in the browser's cache onProgress - a function to execute when one image file is loaded in the browser's cache Example: (start code) new Asset.images(['/images/myImage.png', '/images/myImage2.gif'], { onComplete: function(){ alert('all images loaded!'); } }); (end) Returns: the img element. you can inject it anywhere you want with <Element.injectInside>/<Element.injectAfter>/<Element.injectBefore> */ images: function(sources, options){ options = Object.extend({ onComplete: Class.empty, onProgress: Class.empty }, options || {}); if (!sources.push) sources = [sources]; var images = []; counter = 0; sources.each(function(source){ var img = new Asset.image(source, { 'onload': function(){ counter++; options.onProgress(); if (counter == sources.length) options.onComplete(); } }); images.push(img); }); return images; }, create: function(type, defaults, properties, inject){ Object.extend(defaults, properties || {}); var element = new Element(type).setProperties(defaults); if (inject) element.injectInside($$('head')[0]); return element; } }; /* Script: Accordion.js Contains <Accordion> Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Accordion The Accordion class creates a group of elements that are toggled when their handles are clicked. When one elements toggles in, the others toggles back. Arguments: elements - required, a collection of elements the transitions will be applied to. togglers - required, a collection of elements, the elements handlers that will be clickable. options - optional, see options below, and <Fx.Base> options. Options: show - integer, the Index of the element to show at start. display - integer, the Index of the element to show at start (with a transition). defaults to 0. fixedHeight - integer, if you want the elements to have a fixed height. defaults to false. fixedWidth - integer, if you want the elements to have a fixed width. defaults to false. onActive - function to execute when an element starts to show onBackground - function to execute when an element starts to hide height - boolean, will add a height transition to the accordion if true. defaults to true. opacity - boolean, will add an opacity transition to the accordion if true. defaults to true. width - boolean, will add a width transition to the accordion if true. defaults to false, css mastery is required to make this work! alwaysHide - boolean, will allow to hide all elements if true, instead of always keeping one element shown. defaults to false. */ var Accordion = Fx.Elements.extend({ getExtended: function(){ return { onActive: Class.empty, onBackground: Class.empty, display: 0, show: false, height: true, width: false, opacity: true, fixedHeight: false, fixedWidth: false, wait: false, alwaysHide: false }; }, initialize: function(togglers, elements, options){ this.setOptions(this.getExtended(), options); this.previous = -1; if (this.options.alwaysHide) this.options.wait = true; if ($chk(this.options.show)){ this.options.display = false; this.previous = this.options.show; } if (this.options.start){ this.options.display = false; this.options.show = false; } this.togglers = $$(togglers); this.elements = $$(elements); this.togglers.each(function(tog, i){ tog.addEvent('click', this.display.bind(this, i)); }, this); this.elements.each(function(el, i){ el.fullOpacity = 1; if (this.options.fixedWidth) el.fullWidth = this.options.fixedWidth; if (this.options.fixedHeight) el.fullHeight = this.options.fixedHeight; el.setStyle('overflow', 'hidden'); }, this); this.effects = {}; if (this.options.opacity) this.effects.opacity = 'fullOpacity'; if (this.options.width) this.effects.width = this.options.fixedWidth ? 'fullWidth' : 'offsetWidth'; if (this.options.height) this.effects.height = this.options.fixedHeight ? 'fullHeight' : 'scrollHeight'; this.elements.each(function(el, i){ if (this.options.show === i) this.fireEvent('onActive', [this.togglers[i], el]); else for (var fx in this.effects) el.setStyle(fx, 0); }, this); this.parent(this.elements, this.options); if ($chk(this.options.display)) this.display(this.options.display); }, /* Property: display Shows a specific section and hides all others. Useful when triggering an accordion from outside. Arguments: index - integer, the index of the item to show. */ display: function(index){ if ((this.timer && this.options.wait) || (index === this.previous && !this.options.alwaysHide)) return this; this.previous = index; var obj = {}; this.elements.each(function(el, i){ obj[i] = {}; if ((i != index) || (this.options.alwaysHide && (el.offsetHeight > 0))){ this.fireEvent('onBackground', [this.togglers[i], el]); for (var fx in this.effects) obj[i][fx] = 0; } else { this.fireEvent('onActive', [this.togglers[i], el]); for (var fx in this.effects) obj[i][fx] = el[this.effects[fx]]; } }, this); return this.start(obj); }, showThisHideOpen: function(index){return this.display(index)} }); Fx.Accordion = Accordion; /* Script: Scroller.js Contains the <Scroller>. Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Scroller The Scroller is a class to scroll any element with an overflow (including the window) when the mouse cursor reaches certain buondaries of that element. You must call its start method to start listening to mouse movements. Arguments: element - required, the element to scroll. options - optional, see options below, and <Fx.Base> options. Options: area - integer, the necessary boundaries to make the element scroll. velocity - integer, velocity ratio, the modifier for the window scrolling speed. onChange - optionally, when the mouse reaches some boundaries, you can choose to alter some other values, instead of the scrolling offsets. Automatically passes as parameters x and y values. */ var Scroller = new Class({ getOptions: function(){ return { area: 20, velocity: 1, onChange: function(x, y){ this.element.scrollTo(x, y); } }; }, initialize: function(element, options){ this.setOptions(this.getOptions(), options); this.element = $(element); this.mousemover = ([window, document].test(element)) ? $(document.body) : this.element; }, /* Property: start The scroller starts listening to mouse movements. */ start: function(){ this.coord = this.getCoords.bindWithEvent(this); this.mousemover.addEvent('mousemove', this.coord); }, /* Property: stop The scroller stops listening to mouse movements. */ stop: function(){ this.mousemover.removeEvent('mousemove', this.coord); this.timer = $clear(this.timer); }, getCoords: function(event){ this.page = (this.element == window) ? event.client : event.page; if (!this.timer) this.timer = this.scroll.periodical(50, this); }, scroll: function(){ var el = this.element.getSize(); var pos = this.element.getPosition(); var change = {'x': 0, 'y': 0}; for (var z in this.page){ if (this.page[z] < (this.options.area + pos[z]) && el.scroll[z] != 0) change[z] = (this.page[z] - this.options.area - pos[z]) * this.options.velocity; else if (this.page[z] + this.options.area > (el.size[z] + pos[z]) && el.scroll[z] + el.size[z] != el.scrollSize[z]) change[z] = (this.page[z] - el.size[z] + this.options.area - pos[z]) * this.options.velocity; } if (change.y || change.x) this.fireEvent('onChange', [el.scroll.x + change.x, el.scroll.y + change.y]); } }); Scroller.implement(new Events); Scroller.implement(new Options); /* Script: Slider.js Contains <Slider> Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Slider Creates a slider with two elements: a knob and a container. Returns the values. Arguments: element - the knob container knob - the handle options - see Options below Options: onChange - a function to fire when the value changes. onComplete - a function to fire when you're done dragging. onTick - optionally, you can alter the onTick behavior, for example displaying an effect of the knob moving to the desired position. Passes as parameter the new position. steps - the number of steps for your slider. mode - either 'horizontal' or 'vertical'. defaults to horizontal. wheel - experimental! Also use the mouse wheel to control the slider. defaults to false. */ var Slider = new Class({ getOptions: function(){ return { onChange: Class.empty, onComplete: Class.empty, onTick: function(pos){ this.knob.setStyle(this.p, pos+'px'); }, steps: 100, mode: 'horizontal', wheel: false }; }, initialize: function(el, knob, options){ this.element = $(el); this.knob = $(knob); this.setOptions(this.getOptions(), options); this.previousChange = -1; this.previousEnd = -1; this.step = -1; this.element.addEvent('mousedown', this.clickedElement.bindWithEvent(this)); if (this.options.wheel) this.element.addEvent('mousewheel', this.scrolledElement.bindWithEvent(this)); if (this.options.mode == 'horizontal'){ this.z = 'x'; this.p = 'left'; this.max = this.element.offsetWidth-this.knob.offsetWidth; this.half = this.knob.offsetWidth/2; this.getPos = this.element.getLeft.bind(this.element); } else if (this.options.mode == 'vertical'){ this.z = 'y'; this.p = 'top'; this.max = this.element.offsetHeight-this.knob.offsetHeight; this.half = this.knob.offsetHeight/2; this.getPos = this.element.getTop.bind(this.element); } this.knob.setStyle('position', 'relative').setStyle(this.p, 0); var modSlide = {}, limSlide = {}; limSlide[this.z] = [0, this.max]; modSlide[this.z] = this.p; this.drag = new Drag.Base(this.knob, { limit: limSlide, snap: 0, modifiers: modSlide, onStart: function(){ this.draggedKnob(); }.bind(this), onDrag: function(){ this.draggedKnob(); }.bind(this), onComplete: function(){ this.draggedKnob(); this.end(); }.bind(this) }); if (this.options.initialize) this.options.initialize.call(this); }, /* Property: set The slider will get the step you pass. Arguments: step - one integer */ set: function(step){ if (step > this.options.steps) step = this.options.steps; else if (step < 0) step = 0; this.step = step; this.checkStep(); this.end(); this.fireEvent('onTick', this.toPosition(this.step)+''); return this; }, scrolledElement: function(event){ if (event.wheel < 0) this.set(this.step + 1); else if (event.wheel > 0) this.set(this.step - 1); event.stop(); }, clickedElement: function(event){ var position = event.page[this.z] - this.getPos() - this.half; if (position > this.max) position = this.max; else if (position < 0) position = 0; this.step = this.toStep(position); this.checkStep(); this.end(); this.fireEvent('onTick', position+''); }, draggedKnob: function(){ this.step = this.toStep(this.drag.value.now[this.z]); this.checkStep(); }, checkStep: function(){ if (this.previousChange != this.step){ this.previousChange = this.step; this.fireEvent('onChange', this.step); } }, end: function(){ if (this.previousEnd !== this.step){ this.previousEnd = this.step; this.fireEvent('onComplete', this.step+''); } }, toStep: function(position){ return Math.round(position/this.max*this.options.steps); }, toPosition: function(step){ return (this.max)*step/this.options.steps; } }); Slider.implement(new Events); Slider.implement(new Options); /* Script: SmoothScroll.js Contains <SmoothScroll> Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: SmoothScroll Auto targets all the anchors in a page and display a smooth scrolling effect upon clicking them. Arguments: options - the Fx.Base options (see: <Fx.Base>) Example: >new SmoothScroll(); */ var SmoothScroll = Fx.Scroll.extend({ initialize: function(options){ this.addEvent('onCancel', this.clearChain); var location = window.location.href.match(/^[^#]*/)[0] + '#'; $each(document.links, function(lnk){ if (lnk.href.indexOf(location) != 0) return; var anchor = lnk.href.substr(location.length); if (anchor && $(anchor)) this.useLink(lnk, anchor); }, this); this.parent(window, options); }, useLink: function(lnk, anchor){ lnk.addEvent('click', function(event){ if(!window.khtml) this.chain(function(){ window.location.href = '#'+anchor; }); this.toElement(anchor); event.stop(); }.bindWithEvent(this)); } }); /* Script: Sortables.js Contains <Sortables> Class. Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. */ /* Class: Sortables Creates an interface for <Drag.Base> and drop, resorting of a list. Arguments: list - required, the list that will become sortable. options - an Object, see options below. Options: handles - a collection of elements to be used for drag handles. defaults to the elements. onStart - function executed when the item starts dragging onComplete - function executed when the item ends dragging */ var Sortables = new Class({ getOptions: function() { return { handles: false, onStart: Class.empty, onComplete: Class.empty, ghost: true, snap: 3, onDragStart: function(element, ghost){ ghost.setStyle('opacity', 0.5); }, onDragComplete: function(element, ghost){ ghost.remove(); } }; }, initialize: function(list, options){ this.setOptions(this.getOptions(), options); this.list = $(list); this.elements = this.list.getChildren(); this.handles = $$(this.options.handles) || this.elements; this.drag = []; this.bound = {'start': []}; this.elements.each(function(el, i){ this.bound.start[i] = this.start.bindWithEvent(this, el); if (this.options.ghost){ this.trash = new Element('div').injectInside(document.body); var limit = this.list.getCoordinates(); this.drag[i] = new Drag.Base(el, { handle: this.handles[i], snap: this.options.snap, modifiers: {y: 'top'}, limit: {y: [limit.top, limit.bottom - el.offsetHeight]}, onBeforeStart: function(element){ var offsets = element.getPosition(); this.old = element; this.drag[i].element = this.ghost = element.clone().setStyles({ 'position': 'absolute', 'top': offsets.y+'px', 'left': offsets.x+'px' }).injectInside(this.trash); this.fireEvent('onDragStart', [el, this.ghost]); }.bind(this), onComplete: function(element){ this.drag[i].element = this.old; this.fireEvent('onDragComplete', [el, this.ghost]); }.bind(this) }); } this.handles[i].addEvent('mousedown', this.start.bindWithEvent(this, el)); }, this); if (this.options.initialize) this.options.initialize.call(this); }, start: function(event, el){ this.bound.move = this.move.bindWithEvent(this, el); this.bound.end = this.end.bind(this, el); document.addEvent('mousemove', this.bound.move); document.addEvent('mouseup', this.bound.end); this.fireEvent('onStart', el); event.stop(); }, move: function(event, el){ var prev = el.getPrevious(); var next = el.getNext(); if (prev){ var prevPos = prev.getCoordinates(); if (event.page.y < prevPos.bottom) el.injectBefore(prev); } if (next){ var nextPos = next.getCoordinates(); if (event.page.y > nextPos.top) el.injectAfter(next); } event.stop(); }, detach: function(){ this.elements.each(function(el, i){ this.handles[i].removeEvent('mousedown', this.bound.start[i]); }, this); }, serialize: function(){ var serial = []; this.list.getChildren().each(function(el, i){ serial[i] = this.elements.indexOf(el); }, this); return serial; }, end: function(el){ document.removeEvent('mousemove', this.bound.move); document.removeEvent('mouseup', this.bound.end); this.fireEvent('onComplete', el); } }); Sortables.implement(new Events); Sortables.implement(new Options); /* Script: Tips.js Tooltips, BubbleTips, whatever they are, they will appear on mouseover Author: Valerio Proietti, <http://mad4milk.net> License: MIT-style license. Credits: The idea behind Tips.js is based on Bubble Tooltips (<http://web-graphics.com/mtarchive/001717.php>) by Alessandro Fulcitiniti <http://web-graphics.com> */ /* Class: Tips Display a tip on any element with a title and/or href. Arguments: elements - a collection of elements to apply the tooltips to on mouseover. options - an object. See options Below. Options: maxTitleChars - the maximum number of characters to display in the title of the tip. defaults to 30. timeOut - the delay to wait to show the tip (how long the user must hover to have the tooltip appear). defaults to 100. onShow - optionally you can alter the default onShow behaviour with this option (like displaying a fade in effect); onHide - optionally you can alter the default onHide behaviour with this option (like displaying a fade out effect); showDelay - the delay the onShow method is called. (defaults to 100 ms) hideDelay - the delay the onHide method is called. (defaults to 100 ms) className - the prefix for your tooltip classNames. defaults to 'tool'. the whole tooltip will have as classname: tool-tip the title will have as classname: tool-title the text will have as classname: tool-text offsets - the distance of your tooltip from the mouse. an Object with x/y properties. fixed - if set to true, the toolTip will not follow the mouse. Example: (start code) <img src="/images/i.png" title="The body of the tooltip is stored in the title" class="toolTipImg"/> <script> var myTips = new Tips($$('.toolTipImg'), { maxTitleChars: 50 //I like my captions a little long }); </script> (end) */ var Tips = new Class({ getOptions: function(){ return { onShow: function(tip){ tip.setStyle('visibility', 'visible'); }, onHide: function(tip){ tip.setStyle('visibility', 'hidden'); }, maxTitleChars: 30, showDelay: 100, hideDelay: 100, className: 'tool', offsets: {'x': 16, 'y': 16}, fixed: false }; }, initialize: function(elements, options){ this.setOptions(this.getOptions(), options); this.toolTip = new Element('div').addClass(this.options.className+'-tip').setStyles({ 'position': 'absolute', 'top': '0', 'left': '0', 'visibility': 'hidden' }).injectInside(document.body); this.wrapper = new Element('div').injectInside(this.toolTip); $each(elements, function(el){ this.build($(el)); }, this); if (this.options.initialize) this.options.initialize.call(this); }, build: function(el){ el.myTitle = el.href ? el.href.replace('http://', '') : (el.rel || false); if (el.title){ var dual = el.title.split('::'); if (dual.length > 1) { el.myTitle = dual[0].trim(); el.myText = dual[1].trim(); } else { el.myText = el.title; } el.removeAttribute('title'); } else { el.myText = false; } if (el.myTitle && el.myTitle.length > this.options.maxTitleChars) el.myTitle = el.myTitle.substr(0, this.options.maxTitleChars - 1) + "&hellip;"; el.addEvent('mouseover', function(event){ this.start(el); this.locate(event); }.bindWithEvent(this)); if (!this.options.fixed) el.addEvent('mousemove', this.locate.bindWithEvent(this)); el.addEvent('mouseout', this.end.bindWithEvent(this)); }, start: function(el){ this.wrapper.setHTML(''); if (el.myTitle){ new Element('span').injectInside( new Element('div').addClass(this.options.className+'-title').injectInside(this.wrapper) ).setHTML(el.myTitle); } if (el.myText){ new Element('span').injectInside( new Element('div').addClass(this.options.className+'-text').injectInside(this.wrapper) ).setHTML(el.myText); } $clear(this.timer); this.timer = this.show.delay(this.options.showDelay, this); }, end: function(event){ $clear(this.timer); this.timer = this.hide.delay(this.options.hideDelay, this); event.stop(); }, locate: function(event){ var win = {'x': window.getWidth(), 'y': window.getHeight()}; var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()}; var tip = {'x': this.toolTip.offsetWidth, 'y': this.toolTip.offsetHeight}; var prop = {'x': 'left', 'y': 'top'}; for (var z in prop){ var pos = event.page[z] + this.options.offsets[z]; if ((pos + tip[z] - scroll[z]) > win[z]) pos = event.page[z] - this.options.offsets[z] - tip[z]; this.toolTip.setStyle(prop[z], pos + 'px'); }; event.stop(); }, show: function(){ this.fireEvent('onShow', [this.toolTip]); }, hide: function(){ this.fireEvent('onHide', [this.toolTip]); } }); Tips.implement(new Events); Tips.implement(new Options);
JavaScript
(function( $, undefined ) { jQuery.widget( "ui.pagination", { options: { pageSize: 20, recordCount: 0 }, getFirstPageRowIndex: function() { return this.options.pageSize*this.pageIndex; }, getLastPageRowIndex: function() { var index = this.getFirstPageRowIndex(); index += this.options.pageSize-1; if (index > this.recordCount-1) index = this.recordCount-1; return index; }, setRecordCount: function(recordCount) { this.pageCount = this._calculatePageCount(this.options.pageSize, recordCount); this.currentPageIndex = this._fixCurrentPageIndex(this.pageIndex, this.pageCount); this.recordCount = recordCount; this._refresh(); }, setCurrentPageIndex: function(pageIndex) { var lastPageIndex = this.pageCount - 1; if (pageIndex < 0) pageIndex = 0; if ( pageIndex > lastPageIndex ) pageIndex = lastPageIndex; this.currentPageIndex = pageIndex; this._refresh(); return pageIndex; }, _create: function() { this.pageIndex = 0; this._build(); this.setRecordCount(this.options.recordCount); }, _build: function() { this.pageList = jQuery('<p/>'); this.intervalInfo = jQuery('<strong/>'); this.totalRecords = jQuery('<strong/>'); this.pages = jQuery('<span/>').addClass('numbers'); this.pageList.append( document.createTextNode("Showing "), this.intervalInfo, document.createTextNode(" of "), this.totalRecords, document.createTextNode(" records. Page: "), this.pages ) this.element.append(this.pageList); }, _refresh: function() { this.pages.empty(); this.totalRecords.empty(); this.intervalInfo.empty(); var self = this; this.intervalInfo.text((this.getFirstPageRowIndex()+1)+'-'+(this.getLastPageRowIndex()+1)); this.totalRecords.text(this.recordCount); if (this.pageCount < 11) { for (var i = 1; i <= this.pageCount; i++) { if (i != this.currentPageIndex+1) { this._createPageLink(i); } else this._createCurrentPageMark(i); this._createSpace(); } } else { var startIndex = this.currentPageIndex-5, endIndex = this.currentPageIndex+5; lastPageIndex = this.pageCount-1; if (startIndex < 0) startIndex = 0; if (endIndex > lastPageIndex) endIndex = lastPageIndex; if ((endIndex - startIndex) < 11) endIndex = startIndex + 11; if (endIndex > lastPageIndex) endIndex = lastPageIndex; if ((endIndex - startIndex) < 11) startIndex = endIndex - 11; if (startIndex < 0) startIndex = 0; for (i = startIndex+1; i <= endIndex+1; i++) { if (i != this.currentPageIndex+1) this._createPageLink(i); else this._createCurrentPageMark(i); this._createSpace(); } if (startIndex > 0) { if (startIndex > 1) this.pages.prepend(document.createTextNode(' ... ')); this.pages.prepend( jQuery('<a></a>') .text(1) .bind('click', function(){self.element.trigger('pagination-click', 0); return false;}) .attr('href', '#') ); } if (endIndex < lastPageIndex) { if (lastPageIndex-endIndex > 1) this.pages.append(document.createTextNode(' ... ')); this.pages.append( jQuery('<a></a>') .text(lastPageIndex+1) .bind('click', function(){self.element.trigger('pagination-click', lastPageIndex); return false; }) .attr('href', '#') ); } this.pages.append(document.createTextNode(' ')); } }, _createPageLink: function(pageIndex) { var self = this; this.pages.append( jQuery('<a></a>') .text(pageIndex) .bind('click', function(){self.element.trigger('pagination-click', pageIndex-1); return false; }) .attr('href', '#') ); }, _createCurrentPageMark: function(pageIndex) { this.pages.append( jQuery('<span class="current"></span>') .text(pageIndex) ); }, _createSpace: function() { this.pages.append(document.createTextNode(' ')); }, _calculatePageCount: function( pageSize, recordCount ) { var result = Math.ceil(recordCount/pageSize); if (result === 0) result = 1; return result; }, _fixCurrentPageIndex: function( currentPageIndex, pageCount ) { var lastPageIndex = pageCount - 1; if ( currentPageIndex > lastPageIndex ) currentPageIndex = lastPageIndex; return currentPageIndex; } }) })( jQuery );
JavaScript
// jQuery Object Oriented Class // // Version 1.0.2 // // Create By Hassan Jodat Shandi // http://doob.ir/ // 27 Feb 2010 // jQuery.extend({ // define class core object Class: function () { }, // define interface core object Interface: function () { } }); jQuery.extend(jQuery.Class, { extend: function () { var options, name, src, copy, copyIsArray, clone, skip = arguments[0], target = arguments[1] || {}, i = 2, length = arguments.length, deep = false; // Handle a deep copy situation if (typeof target === 'boolean') { deep = target; target = arguments[2] || {}; // skip the boolean and the target i = 3; } // Handle case when target is a string or something (possible in deep copy) if (typeof target !== 'object' && !jQuery.isFunction(target)) { target = {}; } // extend jQuery itself if only one argument is passed if (length === i) { target = this; --i; } for (; i < length; i++) { // Only deal with non-null/undefined values if ((options = arguments[i]) != null) { // Extend the base object for (name in options) { if (name != skip) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging plain objects or arrays if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[name] = jQuery.extend(deep, clone, copy); // Don't bring in undefined values } else if (copy !== undefined) { target[name] = copy; } } } } } // Return the modified object return target; }, getFunctionBody: function (func) { // Get content between first { and last } var m = func.toString().match(/\{([\s\S]*)\}/m)[1]; // Strip comments return jQuery.trim(m.replace(/^\s*\/\/.*$/mg, '')); }, Function: function () { } }); // define Function body jQuery.extend(jQuery.Class.Function, { Empty: function () { } }); // define interface elements jQuery.extend(jQuery.Interface.prototype, { attributes: [], properties: [], methods: [] }); // define class elements jQuery.extend(jQuery.Class, { // this method create getter and setter property createGetSet: function (object, name, element) { eval('object.prototype["get' + name + '"] = function () { return this.' + element + '; };'); eval('object.prototype["set' + name + '"] = function () { this.' + element + ' = arguments[0]; };'); if (!object.prototype[element]) { object.prototype[element] = ''; } }, // this method create getter and setter property in runtime createGetSetRuntime: function (object, name, element) { eval('object.constructor.prototype["get' + name + '"] = function () { return this.' + element + '; };'); eval('object.constructor.prototype["set' + name + '"] = function () { this.' + element + ' = arguments[0]; };'); if (!object.constructor.prototype[element]) { object.constructor.prototype[element] = ''; } }, // this method create module in window object createNamespace: function (name) { var names = name.split('.'), namespaceStr = 'window'; while (names.length) { var name = names.shift(); namespaceStr += '["' + name + '"]'; } return namespaceStr; }, // use this method for understanding interface elements is implemented in class isIn: function (object, name) { for (var item in object.prototype) { if (item == name) { if (jQuery.isArray(object.prototype[item])) return 0; else if (jQuery.isFunction(object.prototype[item])) return 1; else if (jQuery.isEmptyObject(object.prototype[item]) || jQuery.isPlainObject(object.prototype[item])) return 2; else if (jQuery.isXMLDoc(object.prototype[item])) return 3; else return 0; } } return -1; }, // this method for create class object create: function () { var parent = null, elements = null, base = null, options = { abstract: false, getset: [], implements: [], module: '' }; // check for extending if (jQuery.isFunction(arguments[0])) { parent = arguments[0]; elements = arguments[1]; if (arguments[2]) { jQuery.extend(options, arguments[2] || {}); } } else { elements = arguments[0]; if (arguments[1]) { jQuery.extend(options, arguments[1] || {}); } } // create new class core function handle() { // check if class is abstracted if (this.options.abstract) { throw new Error('abstract classes cannot be instantiated'); } // execute constructor method try { this.initialize.apply(this, arguments); } catch (ex) { } } // extend class base methods in new class core jQuery.extend(handle.prototype, jQuery.Class); // extend parent class methods in new class core if (parent) { // extend parent class methods in new class core function clone(obj) { if (obj == null || typeof (obj) != 'object') return obj; var temp = obj.constructor(); // changed if (temp == undefined) temp = {}; for (var key in obj) temp[key] = clone(obj[key]); return temp; } for (property in parent.prototype) { if (property != 'superClass') { switch (jQuery.type(parent.prototype[property])) { case 'function': eval('handle.prototype[property] = ' + parent.prototype[property]); break; case 'object': handle.prototype[property] = clone(parent.prototype[property]); break; default: handle.prototype[property] = parent.prototype[property]; break; } } } //jQuery.Class.extend('superClass', true, handle.prototype, parent.prototype); // save parent handle.prototype.superClass = parent.prototype; } // extend user defined methods in new class core jQuery.extend(handle.prototype, elements || {}); handle.prototype.options = options; // define getter and setter functions if (options.getset.length > 0) { for (var i = 0; i < options.getset.length; i++) { var name = options.getset[i][0], element = options.getset[i][1]; this.createGetSet(handle, name, element); } } // check for impelemented elements from interface if (options.implements.length > 0) { var attributesMustImplemented = [], propertiesMustImplemented = [], methodsMustImplemented = []; // extract elements from interface for (var i = 0; i < options.implements.length; i++) { jQuery.merge(attributesMustImplemented, options.implements[i].attributes); jQuery.merge(propertiesMustImplemented, options.implements[i].properties); jQuery.merge(methodsMustImplemented, options.implements[i].methods); } var didNotImplemented = false, msg = 'must be implemented'; // check for attributes for (var i = 0; i < attributesMustImplemented.length; i++) { var result = this.isIn(handle, attributesMustImplemented[i]); if (result != 0 && result != 2) { didNotImplemented = true; msg = 'attribute: ' + attributesMustImplemented[i] + ', ' + msg; } } // check for properties for (var i = 0; i < propertiesMustImplemented.length; i++) { var resultGet = this.isIn(handle, 'get' + propertiesMustImplemented[i]), resultSet = this.isIn(handle, 'set' + propertiesMustImplemented[i]); if (resultGet != 1) { didNotImplemented = true; msg = 'property: get' + propertiesMustImplemented[i] + ', ' + msg; } else if (resultSet != 1) { didNotImplemented = true; msg = 'property: set' + propertiesMustImplemented[i] + ', ' + msg; } } // check for methods for (var i = 0; i < methodsMustImplemented.length; i++) { var result = this.isIn(handle, methodsMustImplemented[i]); if (result != 1) { didNotImplemented = true; msg = 'method: ' + methodsMustImplemented[i] + ', ' + msg; } } if (didNotImplemented) { throw new Error(msg); } } // check if class is module type, create module if (options.module != '') { var names = options.module.split('.'), name = names[0]; if (window[name] == null || window[name] == undefined) window[name] = new function () { }; for (var i = 1; i < names.length; i++) { name += '.' + names[i]; eval('if (' + this.createNamespace(name) + ' == null || ' + this.createNamespace(name) + ' == undefined) ' + this.createNamespace(name) + ' = new function() {};'); } eval('jQuery.extend(' + this.createNamespace(name) + ', handle.prototype);'); } return handle; }, // for add method to class in runtime addMethods: function () { if (arguments[0]) { jQuery.extend(this.constructor.prototype, arguments[0]); } }, // for add attribute to class in runtime addAttributes: function () { if (arguments[0]) { jQuery.extend(this.constructor.prototype, arguments[0]); } }, // for add property to class in runtime addProperty: function () { try { var name = arguments[0], element = arguments[1]; this.createGetSetRuntime(this, name, element); } catch (ex) { } }, // this method is use to get value And set value of property property: function () { // get value section if (arguments.length == 1 && this.constructor.prototype.hasOwnProperty('get' + arguments[0])) { if (arguments[0]) { if (jQuery.isFunction(this['get' + arguments[0]])) { return this['get' + arguments[0]](); } } } //set value section else if (this.constructor.prototype.hasOwnProperty('set' + arguments[0])) { if (jQuery.isFunction(this['set' + arguments[0]])) { this['set' + arguments[0]](arguments[1]); return this['get' + arguments[0]](); } } }, // check if two class is equal equal: function () { if (arguments[1]) { return arguments[0].constructor.prototype == arguments[1].constructor.prototype; } else { return this.constructor.prototype == arguments[0].constructor.prototype; } }, // create fresh clone object from class object clone: function () { function handle() { try { this.initialize.apply(this, arguments); } catch (ex) { } } if (arguments[0] == true) { jQuery.extend(handle.prototype, this.constructor.prototype); return handle; } else { jQuery.extend(handle.constructor.prototype, this.constructor.prototype); return handle; } }, toString: function () { return 'Design By Hassan Jodat Shandi'; }, base: function () { try { var methodName = arguments[0]; this['temp' + methodName] = this.superClass[methodName]; var temp = this.superClass; if (this.superClass.superClass) { this.superClass = this.superClass.superClass; } var caller = 'this["temp" + methodName]('; if(arguments[1]) caller += 'arguments[1]'; for(var i = 2; i < arguments.length; i++) caller += ', arguments[' + i + ']'; caller += ');'; eval(caller); this['temp' + methodName] = null; this.superClass = temp; } catch (ex) { } } });
JavaScript
/* * jQuery Caret Range plugin * Copyright (c) 2009 Matt Zabriskie * Released under the MIT and GPL licenses. */ (function($) { $.extend($.fn, { caret: function (start, end) { var elem = this[0]; if (elem) { // get caret range if (typeof start == "undefined") { if (elem.selectionStart) { start = elem.selectionStart; end = elem.selectionEnd; } else if (document.selection) { var val = this.val(); var range = document.selection.createRange().duplicate(); range.moveEnd("character", val.length) start = (range.text == "" ? val.length : val.lastIndexOf(range.text)); range = document.selection.createRange().duplicate(); range.moveStart("character", -val.length); end = range.text.length; } } // set caret range else { var val = this.val(); if (typeof start != "number") start = -1; if (typeof end != "number") end = -1; if (start < 0) start = 0; if (end > val.length) end = val.length; if (end < start) end = start; if (start > end) start = end; elem.focus(); if (elem.selectionStart !== undefined) { elem.selectionStart = start; elem.selectionEnd = end; } else if (document.selection) { var range = elem.createTextRange(); range.collapse(true); range.moveStart("character", start); range.moveEnd("character", end - start); range.select(); } } return {start:start, end:end}; } } }); })(jQuery);
JavaScript
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.6 * * Requires: 1.2.2+ */ (function($) { var types = ['DOMMouseScroll', 'mousewheel']; if ($.event.fixHooks) { for ( var i=types.length; i; ) { $.event.fixHooks[ types[--i] ] = $.event.mouseHooks; } } $.event.special.mousewheel = { setup: function() { if ( this.addEventListener ) { for ( var i=types.length; i; ) { this.addEventListener( types[--i], handler, false ); } } else { this.onmousewheel = handler; } }, teardown: function() { if ( this.removeEventListener ) { for ( var i=types.length; i; ) { this.removeEventListener( types[--i], handler, false ); } } else { this.onmousewheel = null; } } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, unmousewheel: function(fn) { return this.unbind("mousewheel", fn); } }); function handler(event) { var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0; event = $.event.fix(orgEvent); event.type = "mousewheel"; // Old school scrollwheel delta if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; } if ( orgEvent.detail ) { delta = -orgEvent.detail/3; } // New school multidimensional scroll (touchpads) deltas deltaY = delta; // Gecko if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaY = 0; deltaX = -1*delta; } // Webkit if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; } if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; } // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); return ($.event.dispatch || $.event.handle).apply(this, args); } })(jQuery);
JavaScript
/* Script: Core.js MooTools - My Object Oriented JavaScript Tools. License: MIT-style license. Copyright: Copyright (c) 2006-2007 [Valerio Proietti](http://mad4milk.net/). Code & Documentation: [The MooTools production team](http://mootools.net/developers/). Inspiration: - Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php) - Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php) */ var MooTools = { 'version': '1.2.0', 'build': '' }; var Native = function(options){ options = options || {}; var afterImplement = options.afterImplement || function(){}; var generics = options.generics; generics = (generics !== false); var legacy = options.legacy; var initialize = options.initialize; var protect = options.protect; var name = options.name; var object = initialize || legacy; object.constructor = Native; object.$family = {name: 'native'}; if (legacy && initialize) object.prototype = legacy.prototype; object.prototype.constructor = object; if (name){ var family = name.toLowerCase(); object.prototype.$family = {name: family}; Native.typize(object, family); } var add = function(obj, name, method, force){ if (!protect || force || !obj.prototype[name]) obj.prototype[name] = method; if (generics) Native.genericize(obj, name, protect); afterImplement.call(obj, name, method); return obj; }; object.implement = function(a1, a2, a3){ if (typeof a1 == 'string') return add(this, a1, a2, a3); for (var p in a1) add(this, p, a1[p], a2); return this; }; object.alias = function(a1, a2, a3){ if (typeof a1 == 'string'){ a1 = this.prototype[a1]; if (a1) add(this, a2, a1, a3); } else { for (var a in a1) this.alias(a, a1[a], a2); } return this; }; return object; }; Native.implement = function(objects, properties){ for (var i = 0, l = objects.length; i < l; i++) objects[i].implement(properties); }; Native.genericize = function(object, property, check){ if ((!check || !object[property]) && typeof object.prototype[property] == 'function') object[property] = function(){ var args = Array.prototype.slice.call(arguments); return object.prototype[property].apply(args.shift(), args); }; }; Native.typize = function(object, family){ if (!object.type) object.type = function(item){ return ($type(item) === family); }; }; Native.alias = function(objects, a1, a2, a3){ for (var i = 0, j = objects.length; i < j; i++) objects[i].alias(a1, a2, a3); }; (function(objects){ for (var name in objects) Native.typize(objects[name], name); })({'boolean': Boolean, 'native': Native, 'object': Object}); (function(objects){ for (var name in objects) new Native({name: name, initialize: objects[name], protect: true}); })({'String': String, 'Function': Function, 'Number': Number, 'Array': Array, 'RegExp': RegExp, 'Date': Date}); (function(object, methods){ for (var i = methods.length; i--; i) Native.genericize(object, methods[i], true); return arguments.callee; }) (Array, ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice', 'toString', 'valueOf', 'indexOf', 'lastIndexOf']) (String, ['charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', 'match', 'replace', 'search', 'slice', 'split', 'substr', 'substring', 'toLowerCase', 'toUpperCase', 'valueOf']); function $chk(obj){ return !!(obj || obj === 0); }; function $clear(timer){ clearTimeout(timer); clearInterval(timer); return null; }; function $defined(obj){ return (obj != undefined); }; function $empty(){}; function $arguments(i){ return function(){ return arguments[i]; }; }; function $lambda(value){ return (typeof value == 'function') ? value : function(){ return value; }; }; function $extend(original, extended){ for (var key in (extended || {})) original[key] = extended[key]; return original; }; function $unlink(object){ var unlinked; switch ($type(object)){ case 'object': unlinked = {}; for (var p in object) unlinked[p] = $unlink(object[p]); break; case 'hash': unlinked = $unlink(object.getClean()); break; case 'array': unlinked = []; for (var i = 0, l = object.length; i < l; i++) unlinked[i] = $unlink(object[i]); break; default: return object; } return unlinked; }; function $merge(){ var mix = {}; for (var i = 0, l = arguments.length; i < l; i++){ var object = arguments[i]; if ($type(object) != 'object') continue; for (var key in object){ var op = object[key], mp = mix[key]; mix[key] = (mp && $type(op) == 'object' && $type(mp) == 'object') ? $merge(mp, op) : $unlink(op); } } return mix; }; function $pick(){ for (var i = 0, l = arguments.length; i < l; i++){ if (arguments[i] != undefined) return arguments[i]; } return null; }; function $random(min, max){ return Math.floor(Math.random() * (max - min + 1) + min); }; function $splat(obj){ var type = $type(obj); return (type) ? ((type != 'array' && type != 'arguments') ? [obj] : obj) : []; }; var $time = Date.now || function(){ return new Date().getTime(); }; function $try(){ for (var i = 0, l = arguments.length; i < l; i++){ try { return arguments[i](); } catch(e){} } return null; }; function $type(obj){ if (obj == undefined) return false; if (obj.$family) return (obj.$family.name == 'number' && !isFinite(obj)) ? false : obj.$family.name; if (obj.nodeName){ switch (obj.nodeType){ case 1: return 'element'; case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace'; } } else if (typeof obj.length == 'number'){ if (obj.callee) return 'arguments'; else if (obj.item) return 'collection'; } return typeof obj; }; var Hash = new Native({ name: 'Hash', initialize: function(object){ if ($type(object) == 'hash') object = $unlink(object.getClean()); for (var key in object) this[key] = object[key]; return this; } }); Hash.implement({ getLength: function(){ var length = 0; for (var key in this){ if (this.hasOwnProperty(key)) length++; } return length; }, forEach: function(fn, bind){ for (var key in this){ if (this.hasOwnProperty(key)) fn.call(bind, this[key], key, this); } }, getClean: function(){ var clean = {}; for (var key in this){ if (this.hasOwnProperty(key)) clean[key] = this[key]; } return clean; } }); Hash.alias('forEach', 'each'); function $H(object){ return new Hash(object); }; Array.implement({ forEach: function(fn, bind){ for (var i = 0, l = this.length; i < l; i++) fn.call(bind, this[i], i, this); } }); Array.alias('forEach', 'each'); function $A(iterable){ if (iterable.item){ var array = []; for (var i = 0, l = iterable.length; i < l; i++) array[i] = iterable[i]; return array; } return Array.prototype.slice.call(iterable); }; function $each(iterable, fn, bind){ var type = $type(iterable); ((type == 'arguments' || type == 'collection' || type == 'array') ? Array : Hash).each(iterable, fn, bind); }; /* Script: Browser.js The Browser Core. Contains Browser initialization, Window and Document, and the Browser Hash. License: MIT-style license. */ var Browser = new Hash({ Engine: {name: 'unknown', version: ''}, Platform: {name: (navigator.platform.match(/mac|win|linux/i) || ['other'])[0].toLowerCase()}, Features: {xpath: !!(document.evaluate), air: !!(window.runtime)}, Plugins: {} }); if (window.opera) Browser.Engine = {name: 'presto', version: (document.getElementsByClassName) ? 950 : 925}; else if (window.ActiveXObject) Browser.Engine = {name: 'trident', version: (window.XMLHttpRequest) ? 5 : 4}; else if (!navigator.taintEnabled) Browser.Engine = {name: 'webkit', version: (Browser.Features.xpath) ? 420 : 419}; else if (!(!document.getBoxObjectFor && window.mozInnerScreenX == null)) Browser.Engine = {name: 'gecko', version: (document.getElementsByClassName) ? 19 : 18}; Browser.Engine[Browser.Engine.name] = Browser.Engine[Browser.Engine.name + Browser.Engine.version] = true; if (window.orientation != undefined) Browser.Platform.name = 'ipod'; Browser.Platform[Browser.Platform.name] = true; Browser.Request = function(){ return $try(function(){ return new XMLHttpRequest(); }, function(){ return new ActiveXObject('MSXML2.XMLHTTP'); }); }; Browser.Features.xhr = !!(Browser.Request()); Browser.Plugins.Flash = (function(){ var version = ($try(function(){ return navigator.plugins['Shockwave Flash'].description; }, function(){ return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); }) || '0 r0').match(/\d+/g); return {version: parseInt(version[0] || 0 + '.' + version[1] || 0), build: parseInt(version[2] || 0)}; })(); function $exec(text){ if (!text) return text; if (window.execScript){ window.execScript(text); } else { var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.text = text; document.head.appendChild(script); document.head.removeChild(script); } return text; }; Native.UID = 1; var $uid = (Browser.Engine.trident) ? function(item){ return (item.uid || (item.uid = [Native.UID++]))[0]; } : function(item){ return item.uid || (item.uid = Native.UID++); }; var Window = new Native({ name: 'Window', legacy: (Browser.Engine.trident) ? null: window.Window, initialize: function(win){ $uid(win); if (!win.Element){ win.Element = $empty; if (Browser.Engine.webkit) win.document.createElement("iframe"); //fixes safari 2 win.Element.prototype = (Browser.Engine.webkit) ? window["[[DOMElement.prototype]]"] : {}; } return $extend(win, Window.Prototype); }, afterImplement: function(property, value){ window[property] = Window.Prototype[property] = value; } }); Window.Prototype = {$family: {name: 'window'}}; new Window(window); var Document = new Native({ name: 'Document', legacy: (Browser.Engine.trident) ? null: window.Document, initialize: function(doc){ $uid(doc); doc.head = doc.getElementsByTagName('head')[0]; doc.html = doc.getElementsByTagName('html')[0]; doc.window = doc.defaultView || doc.parentWindow; if (Browser.Engine.trident4) $try(function(){ doc.execCommand("BackgroundImageCache", false, true); }); return $extend(doc, Document.Prototype); }, afterImplement: function(property, value){ document[property] = Document.Prototype[property] = value; } }); Document.Prototype = {$family: {name: 'document'}}; new Document(document); /* Script: Array.js Contains Array Prototypes like copy, each, contains, and remove. License: MIT-style license. */ Array.implement({ every: function(fn, bind){ for (var i = 0, l = this.length; i < l; i++){ if (!fn.call(bind, this[i], i, this)) return false; } return true; }, filter: function(fn, bind){ var results = []; for (var i = 0, l = this.length; i < l; i++){ if (fn.call(bind, this[i], i, this)) results.push(this[i]); } return results; }, clean: function() { return this.filter($defined); }, indexOf: function(item, from){ var len = this.length; for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){ if (this[i] === item) return i; } return -1; }, map: function(fn, bind){ var results = []; for (var i = 0, l = this.length; i < l; i++) results[i] = fn.call(bind, this[i], i, this); return results; }, some: function(fn, bind){ for (var i = 0, l = this.length; i < l; i++){ if (fn.call(bind, this[i], i, this)) return true; } return false; }, associate: function(keys){ var obj = {}, length = Math.min(this.length, keys.length); for (var i = 0; i < length; i++) obj[keys[i]] = this[i]; return obj; }, link: function(object){ var result = {}; for (var i = 0, l = this.length; i < l; i++){ for (var key in object){ if (object[key](this[i])){ result[key] = this[i]; delete object[key]; break; } } } return result; }, contains: function(item, from){ return this.indexOf(item, from) != -1; }, extend: function(array){ for (var i = 0, j = array.length; i < j; i++) this.push(array[i]); return this; }, getLast: function(){ return (this.length) ? this[this.length - 1] : null; }, getRandom: function(){ return (this.length) ? this[$random(0, this.length - 1)] : null; }, include: function(item){ if (!this.contains(item)) this.push(item); return this; }, combine: function(array){ for (var i = 0, l = array.length; i < l; i++) this.include(array[i]); return this; }, erase: function(item){ for (var i = this.length; i--; i){ if (this[i] === item) this.splice(i, 1); } return this; }, empty: function(){ this.length = 0; return this; }, flatten: function(){ var array = []; for (var i = 0, l = this.length; i < l; i++){ var type = $type(this[i]); if (!type) continue; array = array.concat((type == 'array' || type == 'collection' || type == 'arguments') ? Array.flatten(this[i]) : this[i]); } return array; }, hexToRgb: function(array){ if (this.length != 3) return null; var rgb = this.map(function(value){ if (value.length == 1) value += value; return value.toInt(16); }); return (array) ? rgb : 'rgb(' + rgb + ')'; }, rgbToHex: function(array){ if (this.length < 3) return null; if (this.length == 4 && this[3] == 0 && !array) return 'transparent'; var hex = []; for (var i = 0; i < 3; i++){ var bit = (this[i] - 0).toString(16); hex.push((bit.length == 1) ? '0' + bit : bit); } return (array) ? hex : '#' + hex.join(''); } }); /* Script: Function.js Contains Function Prototypes like create, bind, pass, and delay. License: MIT-style license. */ Function.implement({ extend: function(properties){ for (var property in properties) this[property] = properties[property]; return this; }, create: function(options){ var self = this; options = options || {}; return function(event){ var args = options.arguments; args = (args != undefined) ? $splat(args) : Array.slice(arguments, (options.event) ? 1 : 0); if (options.event) args = [event || window.event].extend(args); var returns = function(){ return self.apply(options.bind || null, args); }; if (options.delay) return setTimeout(returns, options.delay); if (options.periodical) return setInterval(returns, options.periodical); if (options.attempt) return $try(returns); return returns(); }; }, pass: function(args, bind){ return this.create({arguments: args, bind: bind}); }, attempt: function(args, bind){ return this.create({arguments: args, bind: bind, attempt: true})(); }, /*<!ES5-bind>*/ bind: function(that){ var self = this, args = arguments.length > 1 ? Array.slice(arguments, 1) : null, F = function(){}; var bound = function(){ var context = that, length = arguments.length; if (this instanceof bound){ F.prototype = self.prototype; context = new F; } var result = (!args && !length) ? self.call(context) : self.apply(context, args && length ? args.concat(Array.slice(arguments)) : args || arguments); return context == that ? result : context; }; return bound; }, /*</!ES5-bind>*/ bindWithEvent: function(bind, args){ return this.create({bind: bind, event: true, arguments: args}); }, delay: function(delay, bind, args){ return this.create({delay: delay, bind: bind, arguments: args})(); }, periodical: function(interval, bind, args){ return this.create({periodical: interval, bind: bind, arguments: args})(); }, run: function(args, bind){ return this.apply(bind, $splat(args)); } }); /* Script: Number.js Contains Number Prototypes like limit, round, times, and ceil. License: MIT-style license. */ Number.implement({ limit: function(min, max){ return Math.min(max, Math.max(min, this)); }, round: function(precision){ precision = Math.pow(10, precision || 0); return Math.round(this * precision) / precision; }, times: function(fn, bind){ for (var i = 0; i < this; i++) fn.call(bind, i, this); }, toFloat: function(){ return parseFloat(this); }, toInt: function(base){ return parseInt(this, base || 10); } }); Number.alias('times', 'each'); (function(math){ var methods = {}; math.each(function(name){ if (!Number[name]) methods[name] = function(){ return Math[name].apply(null, [this].concat($A(arguments))); }; }); Number.implement(methods); })(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']); /* Script: String.js Contains String Prototypes like camelCase, capitalize, test, and toInt. License: MIT-style license. */ String.implement({ test: function(regex, params){ return ((typeof regex == 'string') ? new RegExp(regex, params) : regex).test(this); }, contains: function(string, separator){ return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : this.indexOf(string) > -1; }, trim: function(){ return this.replace(/^\s+|\s+$/g, ''); }, clean: function(){ return this.replace(/\s+/g, ' ').trim(); }, camelCase: function(){ return this.replace(/-\D/g, function(match){ return match.charAt(1).toUpperCase(); }); }, hyphenate: function(){ return this.replace(/[A-Z]/g, function(match){ return ('-' + match.charAt(0).toLowerCase()); }); }, capitalize: function(){ return this.replace(/\b[a-z]/g, function(match){ return match.toUpperCase(); }); }, escapeRegExp: function(){ return this.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1'); }, toInt: function(base){ return parseInt(this, base || 10); }, toFloat: function(){ return parseFloat(this); }, hexToRgb: function(array){ var hex = this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); return (hex) ? hex.slice(1).hexToRgb(array) : null; }, rgbToHex: function(array){ var rgb = this.match(/\d{1,3}/g); return (rgb) ? rgb.rgbToHex(array) : null; }, stripScripts: function(option){ var scripts = ''; var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){ scripts += arguments[1] + '\n'; return ''; }); if (option === true) $exec(scripts); else if ($type(option) == 'function') option(scripts, text); return text; }, substitute: function(object, regexp){ return this.replace(regexp || (/\\?\{([^}]+)\}/g), function(match, name){ if (match.charAt(0) == '\\') return match.slice(1); return (object[name] != undefined) ? object[name] : ''; }); } }); /* Script: Hash.js Contains Hash Prototypes. Provides a means for overcoming the JavaScript practical impossibility of extending native Objects. License: MIT-style license. */ Hash.implement({ has: Object.prototype.hasOwnProperty, keyOf: function(value){ for (var key in this){ if (this.hasOwnProperty(key) && this[key] === value) return key; } return null; }, hasValue: function(value){ return (Hash.keyOf(this, value) !== null); }, extend: function(properties){ Hash.each(properties, function(value, key){ Hash.set(this, key, value); }, this); return this; }, combine: function(properties){ Hash.each(properties, function(value, key){ Hash.include(this, key, value); }, this); return this; }, erase: function(key){ if (this.hasOwnProperty(key)) delete this[key]; return this; }, get: function(key){ return (this.hasOwnProperty(key)) ? this[key] : null; }, set: function(key, value){ if (!this[key] || this.hasOwnProperty(key)) this[key] = value; return this; }, empty: function(){ Hash.each(this, function(value, key){ delete this[key]; }, this); return this; }, include: function(key, value){ var k = this[key]; if (k == undefined) this[key] = value; return this; }, map: function(fn, bind){ var results = new Hash; Hash.each(this, function(value, key){ results.set(key, fn.call(bind, value, key, this)); }, this); return results; }, filter: function(fn, bind){ var results = new Hash; Hash.each(this, function(value, key){ if (fn.call(bind, value, key, this)) results.set(key, value); }, this); return results; }, every: function(fn, bind){ for (var key in this){ if (this.hasOwnProperty(key) && !fn.call(bind, this[key], key)) return false; } return true; }, some: function(fn, bind){ for (var key in this){ if (this.hasOwnProperty(key) && fn.call(bind, this[key], key)) return true; } return false; }, getKeys: function(){ var keys = []; Hash.each(this, function(value, key){ keys.push(key); }); return keys; }, getValues: function(){ var values = []; Hash.each(this, function(value){ values.push(value); }); return values; }, toQueryString: function(base){ var queryString = []; Hash.each(this, function(value, key){ if (base) key = base + '[' + key + ']'; var result; switch ($type(value)){ case 'object': result = Hash.toQueryString(value, key); break; case 'array': var qs = {}; value.each(function(val, i){ qs[i] = val; }); result = Hash.toQueryString(qs, key); break; default: result = key + '=' + encodeURIComponent(value); } if (value != undefined) queryString.push(result); }); return queryString.join('&'); } }); Hash.alias({keyOf: 'indexOf', hasValue: 'contains'}); /* Script: Event.js Contains the Event Native, to make the event object completely crossbrowser. License: MIT-style license. */ var Event = new Native({ name: 'Event', initialize: function(event, win){ win = win || window; var doc = win.document; event = event || win.event; if (event.$extended) return event; this.$extended = true; var type = event.type; var target = event.target || event.srcElement; while (target && target.nodeType == 3) target = target.parentNode; if (type.test(/key/)){ var code = event.which || event.keyCode; var key = Event.Keys.keyOf(code); if (type == 'keydown'){ var fKey = code - 111; if (fKey > 0 && fKey < 13) key = 'f' + fKey; } key = key || String.fromCharCode(code).toLowerCase(); } else if (type.match(/(click|mouse|menu)/i)){ doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; var page = { x: event.pageX || event.clientX + doc.scrollLeft, y: event.pageY || event.clientY + doc.scrollTop }; var client = { x: (event.pageX) ? event.pageX - win.pageXOffset : event.clientX, y: (event.pageY) ? event.pageY - win.pageYOffset : event.clientY }; if (type.match(/DOMMouseScroll|mousewheel/)){ var wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3; } var rightClick = (event.which == 3) || (event.button == 2); var related = null; if (type.match(/over|out/)){ switch (type){ case 'mouseover': related = event.relatedTarget || event.fromElement; break; case 'mouseout': related = event.relatedTarget || event.toElement; } if (!(function(){ while (related && related.nodeType == 3) related = related.parentNode; return true; }).create({attempt: Browser.Engine.gecko})()) related = false; } } return $extend(this, { event: event, type: type, page: page, client: client, rightClick: rightClick, wheel: wheel, relatedTarget: related, target: target, code: code, key: key, shift: event.shiftKey, control: event.ctrlKey, alt: event.altKey, meta: event.metaKey }); } }); Event.Keys = new Hash({ 'enter': 13, 'up': 38, 'down': 40, 'left': 37, 'right': 39, 'esc': 27, 'space': 32, 'backspace': 8, 'tab': 9, 'delete': 46 }); Event.implement({ stop: function(){ return this.stopPropagation().preventDefault(); }, stopPropagation: function(){ if (this.event.stopPropagation) this.event.stopPropagation(); else this.event.cancelBubble = true; return this; }, preventDefault: function(){ if (this.event.preventDefault) this.event.preventDefault(); else this.event.returnValue = false; return this; } }); /* Script: Class.js Contains the Class Function for easily creating, extending, and implementing reusable Classes. License: MIT-style license. */ var Class = new Native({ name: 'Class', initialize: function(properties){ properties = properties || {}; var klass = function(empty){ for (var key in this) this[key] = $unlink(this[key]); for (var mutator in Class.Mutators){ if (!this[mutator]) continue; Class.Mutators[mutator](this, this[mutator]); delete this[mutator]; } this.constructor = klass; if (empty === $empty) return this; var self = (this.initialize) ? this.initialize.apply(this, arguments) : this; if (this.options && this.options.initialize) this.options.initialize.call(this); return self; }; $extend(klass, this); klass.constructor = Class; klass.prototype = properties; return klass; } }); Class.implement({ implement: function(){ Class.Mutators.Implements(this.prototype, Array.slice(arguments)); return this; } }); Class.Mutators = { Implements: function(self, klasses){ $splat(klasses).each(function(klass){ $extend(self, ($type(klass) == 'class') ? new klass($empty) : klass); }); }, Extends: function(self, klass){ var instance = new klass($empty); delete instance.parent; delete instance.parentOf; for (var key in instance){ var current = self[key], previous = instance[key]; if (current == undefined){ self[key] = previous; continue; } var ctype = $type(current), ptype = $type(previous); if (ctype != ptype) continue; switch (ctype){ case 'function': // this code will be only executed if the current browser does not support function.caller (currently only opera). // we replace the function code with brute force. Not pretty, but it will only be executed if function.caller is not supported. if (!arguments.callee.caller) self[key] = eval('(' + String(current).replace(/\bthis\.parent\(\s*(\))?/g, function(full, close){ return 'arguments.callee._parent_.call(this' + (close || ', '); }) + ')'); // end "opera" code self[key]._parent_ = previous; break; case 'object': self[key] = $merge(previous, current); } } self.parent = function(){ return arguments.callee.caller._parent_.apply(this, arguments); }; self.parentOf = function(descendant){ return descendant._parent_.apply(this, Array.slice(arguments, 1)); }; } }; /* Script: Class.Extras.js Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks. License: MIT-style license. */ var Chain = new Class({ chain: function(){ this.$chain = (this.$chain || []).extend(arguments); return this; }, callChain: function(){ return (this.$chain && this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false; }, clearChain: function(){ if (this.$chain) this.$chain.empty(); return this; } }); var Events = new Class({ addEvent: function(type, fn, internal){ type = Events.removeOn(type); if (fn != $empty){ this.$events = this.$events || {}; this.$events[type] = this.$events[type] || []; this.$events[type].include(fn); if (internal) fn.internal = true; } return this; }, addEvents: function(events){ for (var type in events) this.addEvent(type, events[type]); return this; }, fireEvent: function(type, args, delay){ type = Events.removeOn(type); if (!this.$events || !this.$events[type]) return this; this.$events[type].each(function(fn){ fn.create({'bind': this, 'delay': delay, 'arguments': args})(); }, this); return this; }, removeEvent: function(type, fn){ type = Events.removeOn(type); if (!this.$events || !this.$events[type]) return this; if (!fn.internal) this.$events[type].erase(fn); return this; }, removeEvents: function(type){ for (var e in this.$events){ if (type && type != e) continue; var fns = this.$events[e]; for (var i = fns.length; i--; i) this.removeEvent(e, fns[i]); } return this; } }); Events.removeOn = function(string){ return string.replace(/^on([A-Z])/, function(full, first) { return first.toLowerCase(); }); }; var Options = new Class({ setOptions: function(){ this.options = $merge.run([this.options].extend(arguments)); if (!this.addEvent) return this; for (var option in this.options){ if ($type(this.options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue; this.addEvent(option, this.options[option]); delete this.options[option]; } return this; } }); /* Script: Element.js One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, time-saver methods to let you easily work with HTML Elements. License: MIT-style license. */ Document.implement({ newElement: function(tag, props){ if (Browser.Engine.trident && props){ ['name', 'type', 'checked'].each(function(attribute){ if (!props[attribute]) return; tag += ' ' + attribute + '="' + props[attribute] + '"'; if (attribute != 'checked') delete props[attribute]; }); tag = '<' + tag + '>'; } return $.element(this.createElement(tag)).set(props); }, newTextNode: function(text){ return this.createTextNode(text); }, getDocument: function(){ return this; }, getWindow: function(){ return this.defaultView || this.parentWindow; }, purge: function(){ var elements = this.getElementsByTagName('*'); for (var i = 0, l = elements.length; i < l; i++) Browser.freeMem(elements[i]); } }); var Element = new Native({ name: 'Element', legacy: window.Element, initialize: function(tag, props){ var konstructor = Element.Constructors.get(tag); if (konstructor) return konstructor(props); if (typeof tag == 'string') return document.newElement(tag, props); return $(tag).set(props); }, afterImplement: function(key, value){ if (!Array[key]) Elements.implement(key, Elements.multi(key)); Element.Prototype[key] = value; } }); Element.Prototype = {$family: {name: 'element'}}; Element.Constructors = new Hash; var IFrame = new Native({ name: 'IFrame', generics: false, initialize: function(){ var params = Array.link(arguments, {properties: Object.type, iframe: $defined}); var props = params.properties || {}; var iframe = $(params.iframe) || false; var onload = props.onload || $empty; delete props.onload; props.id = props.name = $pick(props.id, props.name, iframe.id, iframe.name, 'IFrame_' + $time()); iframe = new Element(iframe || 'iframe', props); var onFrameLoad = function(){ var host = $try(function(){ return iframe.contentWindow.location.host; }); if (host && host == window.location.host){ var win = new Window(iframe.contentWindow); var doc = new Document(iframe.contentWindow.document); $extend(win.Element.prototype, Element.Prototype); } onload.call(iframe.contentWindow, iframe.contentWindow.document); }; (!window.frames[props.id]) ? iframe.addListener('load', onFrameLoad) : onFrameLoad(); return iframe; } }); var Elements = new Native({ initialize: function(elements, options){ options = $extend({ddup: true, cash: true}, options); elements = elements || []; if (options.ddup || options.cash){ var uniques = {}, returned = []; for (var i = 0, l = elements.length; i < l; i++){ var el = $.element(elements[i], !options.cash); if (options.ddup){ if (uniques[el.uid]) continue; uniques[el.uid] = true; } returned.push(el); } elements = returned; } return (options.cash) ? $extend(elements, this) : elements; } }); Elements.implement({ filter: function(filter, bind){ if (!filter) return this; return new Elements(Array.filter(this, (typeof filter == 'string') ? function(item){ return item.match(filter); } : filter, bind)); } }); Elements.multi = function(property){ return function(){ var items = []; var elements = true; for (var i = 0, j = this.length; i < j; i++){ var returns = this[i][property].apply(this[i], arguments); items.push(returns); if (elements) elements = ($type(returns) == 'element'); } return (elements) ? new Elements(items) : items; }; }; Window.implement({ $: function(el, nocash){ if (el && el.$family && el.uid) return el; var type = $type(el); return ($[type]) ? $[type](el, nocash, this.document) : null; }, $$: function(selector){ if (arguments.length == 1 && typeof selector == 'string') return this.document.getElements(selector); var elements = []; var args = Array.flatten(arguments); for (var i = 0, l = args.length; i < l; i++){ var item = args[i]; switch ($type(item)){ case 'element': item = [item]; break; case 'string': item = this.document.getElements(item, true); break; default: item = false; } if (item) elements.extend(item); } return new Elements(elements); }, getDocument: function(){ return this.document; }, getWindow: function(){ return this; } }); $.string = function(id, nocash, doc){ id = doc.getElementById(id); return (id) ? $.element(id, nocash) : null; }; $.element = function(el, nocash){ $uid(el); if (!nocash && !el.$family && !(/^object|embed$/i).test(el.tagName)){ var proto = Element.Prototype; for (var p in proto) el[p] = proto[p]; }; return el; }; $.object = function(obj, nocash, doc){ if (obj.toElement) return $.element(obj.toElement(doc), nocash); return null; }; $.textnode = $.whitespace = $.window = $.document = $arguments(0); Native.implement([Element, Document], { getElement: function(selector, nocash){ return $(this.getElements(selector, true)[0] || null, nocash); }, getElements: function(tags, nocash){ tags = tags.split(','); var elements = []; var ddup = (tags.length > 1); tags.each(function(tag){ var partial = this.getElementsByTagName(tag.trim()); (ddup) ? elements.extend(partial) : elements = partial; }, this); return new Elements(elements, {ddup: ddup, cash: !nocash}); } }); Element.Storage = { get: function(uid){ return (this[uid] || (this[uid] = {})); } }; Element.Inserters = new Hash({ before: function(context, element){ if (element.parentNode) element.parentNode.insertBefore(context, element); }, after: function(context, element){ if (!element.parentNode) return; var next = element.nextSibling; (next) ? element.parentNode.insertBefore(context, next) : element.parentNode.appendChild(context); }, bottom: function(context, element){ element.appendChild(context); }, top: function(context, element){ var first = element.firstChild; (first) ? element.insertBefore(context, first) : element.appendChild(context); } }); Element.Inserters.inside = Element.Inserters.bottom; Element.Inserters.each(function(value, key){ var Key = key.capitalize(); Element.implement('inject' + Key, function(el){ value(this, $(el, true)); return this; }); Element.implement('grab' + Key, function(el){ value($(el, true), this); return this; }); }); Element.implement({ getDocument: function(){ return this.ownerDocument; }, getWindow: function(){ return this.ownerDocument.getWindow(); }, getElementById: function(id, nocash){ var el = this.ownerDocument.getElementById(id); if (!el) return null; for (var parent = el.parentNode; parent != this; parent = parent.parentNode){ if (!parent) return null; } return $.element(el, nocash); }, set: function(prop, value){ switch ($type(prop)){ case 'object': for (var p in prop) this.set(p, prop[p]); break; case 'string': var property = Element.Properties.get(prop); (property && property.set) ? property.set.apply(this, Array.slice(arguments, 1)) : this.setProperty(prop, value); } return this; }, get: function(prop){ var property = Element.Properties.get(prop); return (property && property.get) ? property.get.apply(this, Array.slice(arguments, 1)) : this.getProperty(prop); }, erase: function(prop){ var property = Element.Properties.get(prop); (property && property.erase) ? property.erase.apply(this, Array.slice(arguments, 1)) : this.removeProperty(prop); return this; }, match: function(tag){ return (!tag || Element.get(this, 'tag') == tag); }, inject: function(el, where){ Element.Inserters.get(where || 'bottom')(this, $(el, true)); return this; }, wraps: function(el, where){ el = $(el, true); return this.replaces(el).grab(el, where); }, grab: function(el, where){ Element.Inserters.get(where || 'bottom')($(el, true), this); return this; }, appendText: function(text, where){ return this.grab(this.getDocument().newTextNode(text), where); }, adopt: function(){ Array.flatten(arguments).each(function(element){ element = $(element, true); if (element) this.appendChild(element); }, this); return this; }, dispose: function(){ return (this.parentNode) ? this.parentNode.removeChild(this) : this; }, clone: function(contents, keepid){ switch ($type(this)){ case 'element': var attributes = {}; for (var j = 0, l = this.attributes.length; j < l; j++){ var attribute = this.attributes[j], key = attribute.nodeName.toLowerCase(); if (Browser.Engine.trident && (/input/i).test(this.tagName) && (/width|height/).test(key)) continue; var value = (key == 'style' && this.style) ? this.style.cssText : attribute.nodeValue; if (!$chk(value) || key == 'uid' || (key == 'id' && !keepid)) continue; if (value != 'inherit' && ['string', 'number'].contains($type(value))) attributes[key] = value; } var element = new Element(this.nodeName.toLowerCase(), attributes); if (contents !== false){ for (var i = 0, k = this.childNodes.length; i < k; i++){ var child = Element.clone(this.childNodes[i], true, keepid); if (child) element.grab(child); } } return element; case 'textnode': return document.newTextNode(this.nodeValue); } return null; }, replaces: function(el){ el = $(el, true); el.parentNode.replaceChild(this, el); return this; }, hasClass: function(className){ return this.className.contains(className, ' '); }, addClass: function(className){ if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean(); return this; }, removeClass: function(className){ this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1').clean(); return this; }, toggleClass: function(className){ return this.hasClass(className) ? this.removeClass(className) : this.addClass(className); }, getComputedStyle: function(property){ if (this.currentStyle) return this.currentStyle[property.camelCase()]; var computed = this.getWindow().getComputedStyle(this, null); return (computed) ? computed.getPropertyValue([property.hyphenate()]) : null; }, empty: function(){ $A(this.childNodes).each(function(node){ Browser.freeMem(node); Element.empty(node); Element.dispose(node); }, this); return this; }, destroy: function(){ Browser.freeMem(this.empty().dispose()); return null; }, getSelected: function(){ return new Elements($A(this.options).filter(function(option){ return option.selected; })); }, toQueryString: function(){ var queryString = []; this.getElements('input, select, textarea').each(function(el){ if (!el.name || el.disabled) return; var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){ return opt.value; }) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value; $splat(value).each(function(val){ if (val) queryString.push(el.name + '=' + encodeURIComponent(val)); }); }); return queryString.join('&'); }, getProperty: function(attribute){ var EA = Element.Attributes, key = EA.Props[attribute]; var value = (key) ? this[key] : this.getAttribute(attribute, 2); return (EA.Bools[attribute]) ? !!value : (key) ? value : value || null; }, getProperties: function(){ var args = $A(arguments); return args.map(function(attr){ return this.getProperty(attr); }, this).associate(args); }, setProperty: function(attribute, value){ var EA = Element.Attributes, key = EA.Props[attribute], hasValue = $defined(value); if (key && EA.Bools[attribute]) value = (value || !hasValue) ? true : false; else if (!hasValue) return this.removeProperty(attribute); (key) ? this[key] = value : this.setAttribute(attribute, value); return this; }, setProperties: function(attributes){ for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]); return this; }, removeProperty: function(attribute){ var EA = Element.Attributes, key = EA.Props[attribute], isBool = (key && EA.Bools[attribute]); (key) ? this[key] = (isBool) ? false : '' : this.removeAttribute(attribute); return this; }, removeProperties: function(){ Array.each(arguments, this.removeProperty, this); return this; } }); (function(){ var walk = function(element, walk, start, match, all, nocash){ var el = element[start || walk]; var elements = []; while (el){ if (el.nodeType == 1 && (!match || Element.match(el, match))){ elements.push(el); if (!all) break; } el = el[walk]; } return (all) ? new Elements(elements, {ddup: false, cash: !nocash}) : $(elements[0], nocash); }; Element.implement({ getPrevious: function(match, nocash){ return walk(this, 'previousSibling', null, match, false, nocash); }, getAllPrevious: function(match, nocash){ return walk(this, 'previousSibling', null, match, true, nocash); }, getNext: function(match, nocash){ return walk(this, 'nextSibling', null, match, false, nocash); }, getAllNext: function(match, nocash){ return walk(this, 'nextSibling', null, match, true, nocash); }, getFirst: function(match, nocash){ return walk(this, 'nextSibling', 'firstChild', match, false, nocash); }, getLast: function(match, nocash){ return walk(this, 'previousSibling', 'lastChild', match, false, nocash); }, getParent: function(match, nocash){ return walk(this, 'parentNode', null, match, false, nocash); }, getParents: function(match, nocash){ return walk(this, 'parentNode', null, match, true, nocash); }, getChildren: function(match, nocash){ return walk(this, 'nextSibling', 'firstChild', match, true, nocash); }, hasChild: function(el){ el = $(el, true); return (!!el && $A(this.getElementsByTagName(el.tagName)).contains(el)); } }); })(); Element.Properties = new Hash; Element.Properties.style = { set: function(style){ this.style.cssText = style; }, get: function(){ return this.style.cssText; }, erase: function(){ this.style.cssText = ''; } }; Element.Properties.tag = {get: function(){ return this.tagName.toLowerCase(); }}; Element.Properties.href = {get: function(){ return (!this.href) ? null : this.href.replace(new RegExp('^' + document.location.protocol + '\/\/' + document.location.host), ''); }}; Element.Properties.html = {set: function(){ return this.innerHTML = Array.flatten(arguments).join(''); }}; Native.implement([Element, Window, Document], { addListener: function(type, fn){ if (this.addEventListener) this.addEventListener(type, fn, false); else this.attachEvent('on' + type, fn); return this; }, removeListener: function(type, fn){ if (this.removeEventListener) this.removeEventListener(type, fn, false); else this.detachEvent('on' + type, fn); return this; }, retrieve: function(property, dflt){ var storage = Element.Storage.get(this.uid); var prop = storage[property]; if ($defined(dflt) && !$defined(prop)) prop = storage[property] = dflt; return $pick(prop); }, store: function(property, value){ var storage = Element.Storage.get(this.uid); storage[property] = value; return this; }, eliminate: function(property){ var storage = Element.Storage.get(this.uid); delete storage[property]; return this; } }); Element.Attributes = new Hash({ Props: {'html': 'innerHTML', 'class': 'className', 'for': 'htmlFor', 'text': (Browser.Engine.trident) ? 'innerText' : 'textContent'}, Bools: ['compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked', 'disabled', 'readonly', 'multiple', 'selected', 'noresize', 'defer'], Camels: ['value', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan', 'frameBorder', 'maxLength', 'readOnly', 'rowSpan', 'tabIndex', 'useMap'] }); Browser.freeMem = function(item){ if (!item) return; if (Browser.Engine.trident && (/object/i).test(item.tagName)){ for (var p in item){ if (typeof item[p] == 'function') item[p] = $empty; } Element.dispose(item); } if (item.uid && item.removeEvents) item.removeEvents(); }; (function(EA){ var EAB = EA.Bools, EAC = EA.Camels; EA.Bools = EAB = EAB.associate(EAB); Hash.extend(Hash.combine(EA.Props, EAB), EAC.associate(EAC.map(function(v){ return v.toLowerCase(); }))); EA.erase('Camels'); })(Element.Attributes); window.addListener('unload', function(){ window.removeListener('unload', arguments.callee); document.purge(); if (Browser.Engine.trident) CollectGarbage(); }); /* Script: Element.Event.js Contains Element methods for dealing with events, and custom Events. License: MIT-style license. */ Element.Properties.events = {set: function(events){ this.addEvents(events); }}; Native.implement([Element, Window, Document], { addEvent: function(type, fn){ var events = this.retrieve('events', {}); events[type] = events[type] || {'keys': [], 'values': []}; if (events[type].keys.contains(fn)) return this; events[type].keys.push(fn); var realType = type, custom = Element.Events.get(type), condition = fn, self = this; if (custom){ if (custom.onAdd) custom.onAdd.call(this, fn); if (custom.condition){ condition = function(event){ if (custom.condition.call(this, event)) return fn.call(this, event); return false; }; } realType = custom.base || realType; } var defn = function(){ return fn.call(self); }; var nativeEvent = Element.NativeEvents[realType] || 0; if (nativeEvent){ if (nativeEvent == 2){ defn = function(event){ event = new Event(event, self.getWindow()); if (condition.call(self, event) === false) event.stop(); }; } this.addListener(realType, defn); } events[type].values.push(defn); return this; }, removeEvent: function(type, fn){ var events = this.retrieve('events'); if (!events || !events[type]) return this; var pos = events[type].keys.indexOf(fn); if (pos == -1) return this; var key = events[type].keys.splice(pos, 1)[0]; var value = events[type].values.splice(pos, 1)[0]; var custom = Element.Events.get(type); if (custom){ if (custom.onRemove) custom.onRemove.call(this, fn); type = custom.base || type; } return (Element.NativeEvents[type]) ? this.removeListener(type, value) : this; }, addEvents: function(events){ for (var event in events) this.addEvent(event, events[event]); return this; }, removeEvents: function(type){ var events = this.retrieve('events'); if (!events) return this; if (!type){ for (var evType in events) this.removeEvents(evType); events = null; } else if (events[type]){ while (events[type].keys[0]) this.removeEvent(type, events[type].keys[0]); events[type] = null; } return this; }, fireEvent: function(type, args, delay){ var events = this.retrieve('events'); if (!events || !events[type]) return this; events[type].keys.each(function(fn){ fn.create({'bind': this, 'delay': delay, 'arguments': args})(); }, this); return this; }, cloneEvents: function(from, type){ from = $(from); var fevents = from.retrieve('events'); if (!fevents) return this; if (!type){ for (var evType in fevents) this.cloneEvents(from, evType); } else if (fevents[type]){ fevents[type].keys.each(function(fn){ this.addEvent(type, fn); }, this); } return this; } }); Element.NativeEvents = { click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons mousewheel: 2, DOMMouseScroll: 2, //mouse wheel mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement keydown: 2, keypress: 2, keyup: 2, //keyboard focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, //form elements load: 1, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window error: 1, abort: 1, scroll: 1 //misc }; (function(){ var $check = function(event){ var related = event.relatedTarget; if (related == undefined) return true; if (related === false) return false; return ($type(this) != 'document' && related != this && related.prefix != 'xul' && !this.hasChild(related)); }; Element.Events = new Hash({ mouseenter: { base: 'mouseover', condition: $check }, mouseleave: { base: 'mouseout', condition: $check }, mousewheel: { base: (Browser.Engine.gecko) ? 'DOMMouseScroll' : 'mousewheel' } }); })(); /* Script: Element.Style.js Contains methods for interacting with the styles of Elements in a fashionable way. License: MIT-style license. */ Element.Properties.styles = {set: function(styles){ this.setStyles(styles); }}; Element.Properties.opacity = { set: function(opacity, novisibility){ if (!novisibility){ if (opacity == 0){ if (this.style.visibility != 'hidden') this.style.visibility = 'hidden'; } else { if (this.style.visibility != 'visible') this.style.visibility = 'visible'; } } if (!this.currentStyle || !this.currentStyle.hasLayout) this.style.zoom = 1; if (Browser.Engine.trident) this.style.filter = (opacity == 1) ? '' : 'alpha(opacity=' + opacity * 100 + ')'; this.style.opacity = opacity; this.store('opacity', opacity); }, get: function(){ return this.retrieve('opacity', 1); } }; Element.implement({ setOpacity: function(value){ return this.set('opacity', value, true); }, getOpacity: function(){ return this.get('opacity'); }, setStyle: function(property, value){ switch (property){ case 'opacity': return this.set('opacity', parseFloat(value)); case 'float': property = (Browser.Engine.trident) ? 'styleFloat' : 'cssFloat'; } property = property.camelCase(); if ($type(value) != 'string'){ var map = (Element.Styles.get(property) || '@').split(' '); value = $splat(value).map(function(val, i){ if (!map[i]) return ''; return ($type(val) == 'number') ? map[i].replace('@', Math.round(val)) : val; }).join(' '); } else if (value == String(Number(value))){ value = Math.round(value); } this.style[property] = value; return this; }, getStyle: function(property){ switch (property){ case 'opacity': return this.get('opacity'); case 'float': property = (Browser.Engine.trident) ? 'styleFloat' : 'cssFloat'; } property = property.camelCase(); var result = this.style[property]; if (!$chk(result)){ result = []; for (var style in Element.ShortStyles){ if (property != style) continue; for (var s in Element.ShortStyles[style]) result.push(this.getStyle(s)); return result.join(' '); } result = this.getComputedStyle(property); } if (result){ result = String(result); var color = result.match(/rgba?\([\d\s,]+\)/); if (color) result = result.replace(color[0], color[0].rgbToHex()); } if (Browser.Engine.presto || (Browser.Engine.trident && !$chk(parseInt(result)))){ if (property.test(/^(height|width)$/)){ var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'], size = 0; values.each(function(value){ size += this.getStyle('border-' + value + '-width').toInt() + this.getStyle('padding-' + value).toInt(); }, this); return this['offset' + property.capitalize()] - size + 'px'; } if (Browser.Engine.presto && String(result).test('px')) return result; if (property.test(/(border(.+)Width|margin|padding)/)) return '0px'; } return result; }, setStyles: function(styles){ for (var style in styles) this.setStyle(style, styles[style]); return this; }, getStyles: function(){ var result = {}; Array.each(arguments, function(key){ result[key] = this.getStyle(key); }, this); return result; } }); Element.Styles = new Hash({ left: '@px', top: '@px', bottom: '@px', right: '@px', width: '@px', height: '@px', maxWidth: '@px', maxHeight: '@px', minWidth: '@px', minHeight: '@px', backgroundColor: 'rgb(@, @, @)', backgroundPosition: '@px @px', color: 'rgb(@, @, @)', fontSize: '@px', letterSpacing: '@px', lineHeight: '@px', clip: 'rect(@px @px @px @px)', margin: '@px @px @px @px', padding: '@px @px @px @px', border: '@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)', borderWidth: '@px @px @px @px', borderStyle: '@ @ @ @', borderColor: 'rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)', zIndex: '@', 'zoom': '@', fontWeight: '@', textIndent: '@px', opacity: '@' }); Element.ShortStyles = {margin: {}, padding: {}, border: {}, borderWidth: {}, borderStyle: {}, borderColor: {}}; ['Top', 'Right', 'Bottom', 'Left'].each(function(direction){ var Short = Element.ShortStyles; var All = Element.Styles; ['margin', 'padding'].each(function(style){ var sd = style + direction; Short[style][sd] = All[sd] = '@px'; }); var bd = 'border' + direction; Short.border[bd] = All[bd] = '@px @ rgb(@, @, @)'; var bdw = bd + 'Width', bds = bd + 'Style', bdc = bd + 'Color'; Short[bd] = {}; Short.borderWidth[bdw] = Short[bd][bdw] = All[bdw] = '@px'; Short.borderStyle[bds] = Short[bd][bds] = All[bds] = '@'; Short.borderColor[bdc] = Short[bd][bdc] = All[bdc] = 'rgb(@, @, @)'; }); /* Script: Element.Dimensions.js Contains methods to work with size, scroll, or positioning of Elements and the window object. License: MIT-style license. Credits: - Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html). - Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html). */ (function(){ Element.implement({ scrollTo: function(x, y){ if (isBody(this)){ this.getWindow().scrollTo(x, y); } else { this.scrollLeft = x; this.scrollTop = y; } return this; }, getSize: function(){ if (isBody(this)) return this.getWindow().getSize(); return {x: this.offsetWidth, y: this.offsetHeight}; }, getScrollSize: function(){ if (isBody(this)) return this.getWindow().getScrollSize(); return {x: this.scrollWidth, y: this.scrollHeight}; }, getScroll: function(){ if (isBody(this)) return this.getWindow().getScroll(); return {x: this.scrollLeft, y: this.scrollTop}; }, getScrolls: function(){ var element = this, position = {x: 0, y: 0}; while (element && !isBody(element)){ position.x += element.scrollLeft; position.y += element.scrollTop; element = element.parentNode; } return position; }, getOffsetParent: function(){ var element = this; if (isBody(element)) return null; if (!Browser.Engine.trident) return element.offsetParent; while ((element = element.parentNode) && !isBody(element)){ if (styleString(element, 'position') != 'static') return element; } return null; }, getOffsets: function(){ var element = this, position = {x: 0, y: 0}; if (isBody(this)) return position; while (element && !isBody(element)){ position.x += element.offsetLeft; position.y += element.offsetTop; if (Browser.Engine.gecko){ if (!borderBox(element)){ position.x += leftBorder(element); position.y += topBorder(element); } var parent = element.parentNode; if (parent && styleString(parent, 'overflow') != 'visible'){ position.x += leftBorder(parent); position.y += topBorder(parent); } } else if (element != this && (Browser.Engine.trident || Browser.Engine.webkit)){ position.x += leftBorder(element); position.y += topBorder(element); } element = element.offsetParent; if (Browser.Engine.trident){ while (element && !element.currentStyle.hasLayout) element = element.offsetParent; } } if (Browser.Engine.gecko && !borderBox(this)){ position.x -= leftBorder(this); position.y -= topBorder(this); } return position; }, getPosition: function(relative){ if (isBody(this)) return {x: 0, y: 0}; var offset = this.getOffsets(), scroll = this.getScrolls(); var position = {x: offset.x - scroll.x, y: offset.y - scroll.y}; var relativePosition = (relative && (relative = $(relative))) ? relative.getPosition() : {x: 0, y: 0}; return {x: position.x - relativePosition.x, y: position.y - relativePosition.y}; }, getCoordinates: function(element){ if (isBody(this)) return this.getWindow().getCoordinates(); var position = this.getPosition(element), size = this.getSize(); var obj = {left: position.x, top: position.y, width: size.x, height: size.y}; obj.right = obj.left + obj.width; obj.bottom = obj.top + obj.height; return obj; }, computePosition: function(obj){ return {left: obj.x - styleNumber(this, 'margin-left'), top: obj.y - styleNumber(this, 'margin-top')}; }, position: function(obj){ return this.setStyles(this.computePosition(obj)); } }); Native.implement([Document, Window], { getSize: function(){ var win = this.getWindow(); if (Browser.Engine.presto || Browser.Engine.webkit) return {x: win.innerWidth, y: win.innerHeight}; var doc = getCompatElement(this); return {x: doc.clientWidth, y: doc.clientHeight}; }, getScroll: function(){ var win = this.getWindow(); var doc = getCompatElement(this); return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop}; }, getScrollSize: function(){ var doc = getCompatElement(this); var min = this.getSize(); return {x: Math.max(doc.scrollWidth, min.x), y: Math.max(doc.scrollHeight, min.y)}; }, getPosition: function(){ return {x: 0, y: 0}; }, getCoordinates: function(){ var size = this.getSize(); return {top: 0, left: 0, bottom: size.y, right: size.x, height: size.y, width: size.x}; } }); // private methods var styleString = Element.getComputedStyle; function styleNumber(element, style){ return styleString(element, style).toInt() || 0; }; function borderBox(element){ return styleString(element, '-moz-box-sizing') == 'border-box'; }; function topBorder(element){ return styleNumber(element, 'border-top-width'); }; function leftBorder(element){ return styleNumber(element, 'border-left-width'); }; function isBody(element){ return (/^(?:body|html)$/i).test(element.tagName); }; function getCompatElement(element){ var doc = element.getDocument(); return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; }; })(); //aliases Native.implement([Window, Document, Element], { getHeight: function(){ return this.getSize().y; }, getWidth: function(){ return this.getSize().x; }, getScrollTop: function(){ return this.getScroll().y; }, getScrollLeft: function(){ return this.getScroll().x; }, getScrollHeight: function(){ return this.getScrollSize().y; }, getScrollWidth: function(){ return this.getScrollSize().x; }, getTop: function(){ return this.getPosition().y; }, getLeft: function(){ return this.getPosition().x; } }); /* Script: Selectors.js Adds advanced CSS Querying capabilities for targeting elements. Also includes pseudoselectors support. License: MIT-style license. */ Native.implement([Document, Element], { getElements: function(expression, nocash){ expression = expression.split(','); var items, local = {}; for (var i = 0, l = expression.length; i < l; i++){ var selector = expression[i], elements = Selectors.Utils.search(this, selector, local); if (i != 0 && elements.item) elements = $A(elements); items = (i == 0) ? elements : (items.item) ? $A(items).concat(elements) : items.concat(elements); } return new Elements(items, {ddup: (expression.length > 1), cash: !nocash}); } }); Element.implement({ match: function(selector){ if (!selector) return true; var tagid = Selectors.Utils.parseTagAndID(selector); var tag = tagid[0], id = tagid[1]; if (!Selectors.Filters.byID(this, id) || !Selectors.Filters.byTag(this, tag)) return false; var parsed = Selectors.Utils.parseSelector(selector); return (parsed) ? Selectors.Utils.filter(this, parsed, {}) : true; } }); var Selectors = {Cache: {nth: {}, parsed: {}}}; Selectors.RegExps = { id: (/#([\w-]+)/), tag: (/^(\w+|\*)/), quick: (/^(\w+|\*)$/), splitter: (/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g), combined: (/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)["']?(.*?)["']?)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g) }; Selectors.Utils = { chk: function(item, uniques){ if (!uniques) return true; var uid = $uid(item); if (!uniques[uid]) return uniques[uid] = true; return false; }, parseNthArgument: function(argument){ if (Selectors.Cache.nth[argument]) return Selectors.Cache.nth[argument]; var parsed = argument.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/); if (!parsed) return false; var inta = parseInt(parsed[1]); var a = (inta || inta === 0) ? inta : 1; var special = parsed[2] || false; var b = parseInt(parsed[3]) || 0; if (a != 0){ b--; while (b < 1) b += a; while (b >= a) b -= a; } else { a = b; special = 'index'; } switch (special){ case 'n': parsed = {a: a, b: b, special: 'n'}; break; case 'odd': parsed = {a: 2, b: 0, special: 'n'}; break; case 'even': parsed = {a: 2, b: 1, special: 'n'}; break; case 'first': parsed = {a: 0, special: 'index'}; break; case 'last': parsed = {special: 'last-child'}; break; case 'only': parsed = {special: 'only-child'}; break; default: parsed = {a: (a - 1), special: 'index'}; } return Selectors.Cache.nth[argument] = parsed; }, parseSelector: function(selector){ if (Selectors.Cache.parsed[selector]) return Selectors.Cache.parsed[selector]; var m, parsed = {classes: [], pseudos: [], attributes: []}; while ((m = Selectors.RegExps.combined.exec(selector))){ var cn = m[1], an = m[2], ao = m[3], av = m[4], pn = m[5], pa = m[6]; if (cn){ parsed.classes.push(cn); } else if (pn){ var parser = Selectors.Pseudo.get(pn); if (parser) parsed.pseudos.push({parser: parser, argument: pa}); else parsed.attributes.push({name: pn, operator: '=', value: pa}); } else if (an){ parsed.attributes.push({name: an, operator: ao, value: av}); } } if (!parsed.classes.length) delete parsed.classes; if (!parsed.attributes.length) delete parsed.attributes; if (!parsed.pseudos.length) delete parsed.pseudos; if (!parsed.classes && !parsed.attributes && !parsed.pseudos) parsed = null; return Selectors.Cache.parsed[selector] = parsed; }, parseTagAndID: function(selector){ var tag = selector.match(Selectors.RegExps.tag); var id = selector.match(Selectors.RegExps.id); return [(tag) ? tag[1] : '*', (id) ? id[1] : false]; }, filter: function(item, parsed, local){ var i; if (parsed.classes){ for (i = parsed.classes.length; i--; i){ var cn = parsed.classes[i]; if (!Selectors.Filters.byClass(item, cn)) return false; } } if (parsed.attributes){ for (i = parsed.attributes.length; i--; i){ var att = parsed.attributes[i]; if (!Selectors.Filters.byAttribute(item, att.name, att.operator, att.value)) return false; } } if (parsed.pseudos){ for (i = parsed.pseudos.length; i--; i){ var psd = parsed.pseudos[i]; if (!Selectors.Filters.byPseudo(item, psd.parser, psd.argument, local)) return false; } } return true; }, getByTagAndID: function(ctx, tag, id){ if (id){ var item = (ctx.getElementById) ? ctx.getElementById(id, true) : Element.getElementById(ctx, id, true); return (item && Selectors.Filters.byTag(item, tag)) ? [item] : []; } else { return ctx.getElementsByTagName(tag); } }, search: function(self, expression, local){ var splitters = []; var selectors = expression.trim().replace(Selectors.RegExps.splitter, function(m0, m1, m2){ splitters.push(m1); return ':)' + m2; }).split(':)'); var items, match, filtered, item; for (var i = 0, l = selectors.length; i < l; i++){ var selector = selectors[i]; if (i == 0 && Selectors.RegExps.quick.test(selector)){ items = self.getElementsByTagName(selector); continue; } var splitter = splitters[i - 1]; var tagid = Selectors.Utils.parseTagAndID(selector); var tag = tagid[0], id = tagid[1]; if (i == 0){ items = Selectors.Utils.getByTagAndID(self, tag, id); } else { var uniques = {}, found = []; for (var j = 0, k = items.length; j < k; j++) found = Selectors.Getters[splitter](found, items[j], tag, id, uniques); items = found; } var parsed = Selectors.Utils.parseSelector(selector); if (parsed){ filtered = []; for (var m = 0, n = items.length; m < n; m++){ item = items[m]; if (Selectors.Utils.filter(item, parsed, local)) filtered.push(item); } items = filtered; } } return items; } }; Selectors.Getters = { ' ': function(found, self, tag, id, uniques){ var items = Selectors.Utils.getByTagAndID(self, tag, id); for (var i = 0, l = items.length; i < l; i++){ var item = items[i]; if (Selectors.Utils.chk(item, uniques)) found.push(item); } return found; }, '>': function(found, self, tag, id, uniques){ var children = Selectors.Utils.getByTagAndID(self, tag, id); for (var i = 0, l = children.length; i < l; i++){ var child = children[i]; if (child.parentNode == self && Selectors.Utils.chk(child, uniques)) found.push(child); } return found; }, '+': function(found, self, tag, id, uniques){ while ((self = self.nextSibling)){ if (self.nodeType == 1){ if (Selectors.Utils.chk(self, uniques) && Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self); break; } } return found; }, '~': function(found, self, tag, id, uniques){ while ((self = self.nextSibling)){ if (self.nodeType == 1){ if (!Selectors.Utils.chk(self, uniques)) break; if (Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self); } } return found; } }; Selectors.Filters = { byTag: function(self, tag){ return (tag == '*' || (self.tagName && self.tagName.toLowerCase() == tag)); }, byID: function(self, id){ return (!id || (self.id && self.id == id)); }, byClass: function(self, klass){ return (self.className && self.className.contains(klass, ' ')); }, byPseudo: function(self, parser, argument, local){ return parser.call(self, argument, local); }, byAttribute: function(self, name, operator, value){ var result = Element.prototype.getProperty.call(self, name); if (!result) return false; if (!operator || value == undefined) return true; switch (operator){ case '=': return (result == value); case '*=': return (result.contains(value)); case '^=': return (result.substr(0, value.length) == value); case '$=': return (result.substr(result.length - value.length) == value); case '!=': return (result != value); case '~=': return result.contains(value, ' '); case '|=': return result.contains(value, '-'); } return false; } }; Selectors.Pseudo = new Hash({ // w3c pseudo selectors empty: function(){ return !(this.innerText || this.textContent || '').length; }, not: function(selector){ return !Element.match(this, selector); }, contains: function(text){ return (this.innerText || this.textContent || '').contains(text); }, 'first-child': function(){ return Selectors.Pseudo.index.call(this, 0); }, 'last-child': function(){ var element = this; while ((element = element.nextSibling)){ if (element.nodeType == 1) return false; } return true; }, 'only-child': function(){ var prev = this; while ((prev = prev.previousSibling)){ if (prev.nodeType == 1) return false; } var next = this; while ((next = next.nextSibling)){ if (next.nodeType == 1) return false; } return true; }, 'nth-child': function(argument, local){ argument = (argument == undefined) ? 'n' : argument; var parsed = Selectors.Utils.parseNthArgument(argument); if (parsed.special != 'n') return Selectors.Pseudo[parsed.special].call(this, parsed.a, local); var count = 0; local.positions = local.positions || {}; var uid = $uid(this); if (!local.positions[uid]){ var self = this; while ((self = self.previousSibling)){ if (self.nodeType != 1) continue; count ++; var position = local.positions[$uid(self)]; if (position != undefined){ count = position + count; break; } } local.positions[uid] = count; } return (local.positions[uid] % parsed.a == parsed.b); }, // custom pseudo selectors index: function(index){ var element = this, count = 0; while ((element = element.previousSibling)){ if (element.nodeType == 1 && ++count > index) return false; } return (count == index); }, even: function(argument, local){ return Selectors.Pseudo['nth-child'].call(this, '2n+1', local); }, odd: function(argument, local){ return Selectors.Pseudo['nth-child'].call(this, '2n', local); } }); /* Script: Domready.js Contains the domready custom event. License: MIT-style license. */ Element.Events.domready = { onAdd: function(fn){ if (Browser.loaded) fn.call(this); } }; (function(){ var domready = function(){ if (Browser.loaded) return; Browser.loaded = true; window.fireEvent('domready'); document.fireEvent('domready'); }; switch (Browser.Engine.name){ case 'webkit': (function(){ (['loaded', 'complete'].contains(document.readyState)) ? domready() : arguments.callee.delay(50); })(); break; case 'trident': var temp = document.createElement('div'); (function(){ ($try(function(){ temp.doScroll('left'); return $(temp).inject(document.body).set('html', 'temp').dispose(); })) ? domready() : arguments.callee.delay(50); })(); break; default: window.addEvent('load', domready); document.addEvent('DOMContentLoaded', domready); } })(); /* Script: JSON.js JSON encoder and decoder. License: MIT-style license. See Also: <http://www.json.org/> */ var JSON = new Hash({ encode: function(obj){ switch ($type(obj)){ case 'string': return '"' + obj.replace(/[\x00-\x1f\\"]/g, JSON.$replaceChars) + '"'; case 'array': return '[' + String(obj.map(JSON.encode).filter($defined)) + ']'; case 'object': case 'hash': var string = []; Hash.each(obj, function(value, key){ var json = JSON.encode(value); if (json) string.push(JSON.encode(key) + ':' + json); }); return '{' + string + '}'; case 'number': case 'boolean': return String(obj); case false: return 'null'; } return null; }, $specialChars: {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'}, $replaceChars: function(chr){ return JSON.$specialChars[chr] || '\\u00' + Math.floor(chr.charCodeAt() / 16).toString(16) + (chr.charCodeAt() % 16).toString(16); }, decode: function(string, secure){ if ($type(string) != 'string' || !string.length) return null; if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null; return eval('(' + string + ')'); } }); Native.implement([Hash, Array, String, Number], { toJSON: function(){ return JSON.encode(this); } }); /* Script: Cookie.js Class for creating, loading, and saving browser Cookies. License: MIT-style license. Credits: Based on the functions by Peter-Paul Koch (http://quirksmode.org). */ var Cookie = new Class({ Implements: Options, options: { path: false, domain: false, duration: false, secure: false, document: document }, initialize: function(key, options){ this.key = key; this.setOptions(options); }, write: function(value){ value = encodeURIComponent(value); if (this.options.domain) value += '; domain=' + this.options.domain; if (this.options.path) value += '; path=' + this.options.path; if (this.options.duration){ var date = new Date(); date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000); value += '; expires=' + date.toGMTString(); } if (this.options.secure) value += '; secure'; this.options.document.cookie = this.key + '=' + value; return this; }, read: function(){ var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)'); return (value) ? decodeURIComponent(value[1]) : null; }, dispose: function(){ new Cookie(this.key, $merge(this.options, {duration: -1})).write(''); return this; } }); Cookie.write = function(key, value, options){ return new Cookie(key, options).write(value); }; Cookie.read = function(key){ return new Cookie(key).read(); }; Cookie.dispose = function(key, options){ return new Cookie(key, options).dispose(); }; /* Script: Swiff.js Wrapper for embedding SWF movies. Supports (and fixes) External Interface Communication. License: MIT-style license. Credits: Flash detection & Internet Explorer + Flash Player 9 fix inspired by SWFObject. */ var Swiff = new Class({ Implements: [Options], options: { id: null, height: 1, width: 1, container: null, properties: {}, params: { quality: 'high', allowScriptAccess: 'always', wMode: 'transparent', swLiveConnect: true }, callBacks: {}, vars: {} }, toElement: function(){ return this.object; }, initialize: function(path, options){ this.instance = 'Swiff_' + $time(); this.setOptions(options); options = this.options; var id = this.id = options.id || this.instance; var container = $(options.container); Swiff.CallBacks[this.instance] = {}; var params = options.params, vars = options.vars, callBacks = options.callBacks; var properties = $extend({height: options.height, width: options.width}, options.properties); var self = this; for (var callBack in callBacks){ Swiff.CallBacks[this.instance][callBack] = (function(option){ return function(){ return option.apply(self.object, arguments); }; })(callBacks[callBack]); vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack; } params.flashVars = Hash.toQueryString(vars); if (Browser.Engine.trident){ properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'; params.movie = path; } else { properties.type = 'application/x-shockwave-flash'; properties.data = path; } var build = '<object id="' + id + '"'; for (var property in properties) build += ' ' + property + '="' + properties[property] + '"'; build += '>'; for (var param in params){ if (params[param]) build += '<param name="' + param + '" value="' + params[param] + '" />'; } build += '</object>'; this.object = ((container) ? container.empty() : new Element('div')).set('html', build).firstChild; }, replaces: function(element){ element = $(element, true); element.parentNode.replaceChild(this.toElement(), element); return this; }, inject: function(element){ $(element, true).appendChild(this.toElement()); return this; }, remote: function(){ return Swiff.remote.apply(Swiff, [this.toElement()].extend(arguments)); } }); Swiff.CallBacks = {}; Swiff.remote = function(obj, fn){ var rs = obj.CallFunction('<invoke name="' + fn + '" returntype="javascript">' + __flash__argumentsToXML(arguments, 2) + '</invoke>'); return eval(rs); }; /* Script: Fx.js Contains the basic animation logic to be extended by all other Fx Classes. License: MIT-style license. */ var Fx = new Class({ Implements: [Chain, Events, Options], options: { /* onStart: $empty, onCancel: $empty, onComplete: $empty, */ fps: 50, unit: false, duration: 500, link: 'ignore', transition: function(p){ return -(Math.cos(Math.PI * p) - 1) / 2; } }, initialize: function(options){ this.subject = this.subject || this; this.setOptions(options); this.options.duration = Fx.Durations[this.options.duration] || this.options.duration.toInt(); var wait = this.options.wait; if (wait === false) this.options.link = 'cancel'; }, step: function(){ var time = $time(); if (time < this.time + this.options.duration){ var delta = this.options.transition((time - this.time) / this.options.duration); this.set(this.compute(this.from, this.to, delta)); } else { this.set(this.compute(this.from, this.to, 1)); this.complete(); } }, set: function(now){ return now; }, compute: function(from, to, delta){ return Fx.compute(from, to, delta); }, check: function(caller){ if (!this.timer) return true; switch (this.options.link){ case 'cancel': this.cancel(); return true; case 'chain': this.chain(caller.bind(this, Array.slice(arguments, 1))); return false; } return false; }, start: function(from, to){ if (!this.check(arguments.callee, from, to)) return this; this.from = from; this.to = to; this.time = 0; this.startTimer(); this.onStart(); return this; }, complete: function(){ if (this.stopTimer()) this.onComplete(); return this; }, cancel: function(){ if (this.stopTimer()) this.onCancel(); return this; }, onStart: function(){ this.fireEvent('start', this.subject); }, onComplete: function(){ this.fireEvent('complete', this.subject); if (!this.callChain()) this.fireEvent('chainComplete', this.subject); }, onCancel: function(){ this.fireEvent('cancel', this.subject).clearChain(); }, pause: function(){ this.stopTimer(); return this; }, resume: function(){ this.startTimer(); return this; }, stopTimer: function(){ if (!this.timer) return false; this.time = $time() - this.time; this.timer = $clear(this.timer); return true; }, startTimer: function(){ if (this.timer) return false; this.time = $time() - this.time; this.timer = this.step.periodical(Math.round(1000 / this.options.fps), this); return true; } }); Fx.compute = function(from, to, delta){ return (to - from) * delta + from; }; Fx.Durations = {'short': 250, 'normal': 500, 'long': 1000}; /* Script: Fx.CSS.js Contains the CSS animation logic. Used by Fx.Tween, Fx.Morph, Fx.Elements. License: MIT-style license. */ Fx.CSS = new Class({ Extends: Fx, //prepares the base from/to object prepare: function(element, property, values){ values = $splat(values); var values1 = values[1]; if (!$chk(values1)){ values[1] = values[0]; values[0] = element.getStyle(property); } var parsed = values.map(this.parse); return {from: parsed[0], to: parsed[1]}; }, //parses a value into an array parse: function(value){ value = $lambda(value)(); value = (typeof value == 'string') ? value.split(' ') : $splat(value); return value.map(function(val){ val = String(val); var found = false; Fx.CSS.Parsers.each(function(parser, key){ if (found) return; var parsed = parser.parse(val); if ($chk(parsed)) found = {value: parsed, parser: parser}; }); found = found || {value: val, parser: Fx.CSS.Parsers.String}; return found; }); }, //computes by a from and to prepared objects, using their parsers. compute: function(from, to, delta){ var computed = []; (Math.min(from.length, to.length)).times(function(i){ computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser}); }); computed.$family = {name: 'fx:css:value'}; return computed; }, //serves the value as settable serve: function(value, unit){ if ($type(value) != 'fx:css:value') value = this.parse(value); var returned = []; value.each(function(bit){ returned = returned.concat(bit.parser.serve(bit.value, unit)); }); return returned; }, //renders the change to an element render: function(element, property, value, unit){ element.setStyle(property, this.serve(value, unit)); }, //searches inside the page css to find the values for a selector search: function(selector){ if (Fx.CSS.Cache[selector]) return Fx.CSS.Cache[selector]; var to = {}; Array.each(document.styleSheets, function(sheet, j){ var href = sheet.href; if (href && href.contains('://') && !href.contains(document.domain)) return; var rules = sheet.rules || sheet.cssRules; Array.each(rules, function(rule, i){ if (!rule.style) return; var selectorText = (rule.selectorText) ? rule.selectorText.replace(/^\w+/, function(m){ return m.toLowerCase(); }) : null; if (!selectorText || !selectorText.test('^' + selector + '$')) return; Element.Styles.each(function(value, style){ if (!rule.style[style] || Element.ShortStyles[style]) return; value = String(rule.style[style]); to[style] = (value.test(/^rgb/)) ? value.rgbToHex() : value; }); }); }); return Fx.CSS.Cache[selector] = to; } }); Fx.CSS.Cache = {}; Fx.CSS.Parsers = new Hash({ Color: { parse: function(value){ if (value.match(/^#[0-9a-f]{3,6}$/i)) return value.hexToRgb(true); return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value[1], value[2], value[3]] : false; }, compute: function(from, to, delta){ return from.map(function(value, i){ return Math.round(Fx.compute(from[i], to[i], delta)); }); }, serve: function(value){ return value.map(Number); } }, Number: { parse: parseFloat, compute: Fx.compute, serve: function(value, unit){ return (unit) ? value + unit : value; } }, String: { parse: $lambda(false), compute: $arguments(1), serve: $arguments(0) } }); /* Script: Fx.Tween.js Formerly Fx.Style, effect to transition any CSS property for an element. License: MIT-style license. */ Fx.Tween = new Class({ Extends: Fx.CSS, initialize: function(element, options){ this.element = this.subject = $(element); this.parent(options); }, set: function(property, now){ if (arguments.length == 1){ now = property; property = this.property || this.options.property; } this.render(this.element, property, now, this.options.unit); return this; }, start: function(property, from, to){ if (!this.check(arguments.callee, property, from, to)) return this; var args = Array.flatten(arguments); this.property = this.options.property || args.shift(); var parsed = this.prepare(this.element, this.property, args); return this.parent(parsed.from, parsed.to); } }); Element.Properties.tween = { set: function(options){ var tween = this.retrieve('tween'); if (tween) tween.cancel(); return this.eliminate('tween').store('tween:options', $extend({link: 'cancel'}, options)); }, get: function(options){ if (options || !this.retrieve('tween')){ if (options || !this.retrieve('tween:options')) this.set('tween', options); this.store('tween', new Fx.Tween(this, this.retrieve('tween:options'))); } return this.retrieve('tween'); } }; Element.implement({ tween: function(property, from, to){ this.get('tween').start(arguments); return this; }, fade: function(how){ var fade = this.get('tween'), o = 'opacity', toggle; how = $pick(how, 'toggle'); switch (how){ case 'in': fade.start(o, 1); break; case 'out': fade.start(o, 0); break; case 'show': fade.set(o, 1); break; case 'hide': fade.set(o, 0); break; case 'toggle': var flag = this.retrieve('fade:flag', this.get('opacity') == 1); fade.start(o, (flag) ? 0 : 1); this.store('fade:flag', !flag); toggle = true; break; default: fade.start(o, arguments); } if (!toggle) this.eliminate('fade:flag'); return this; }, highlight: function(start, end){ if (!end){ end = this.retrieve('highlight:original', this.getStyle('background-color')); end = (end == 'transparent') ? '#fff' : end; } var tween = this.get('tween'); tween.start('background-color', start || '#ffff88', end).chain(function(){ this.setStyle('background-color', this.retrieve('highlight:original')); tween.callChain(); }.bind(this)); return this; } }); /* Script: Fx.Morph.js Formerly Fx.Styles, effect to transition any number of CSS properties for an element using an object of rules, or CSS based selector rules. License: MIT-style license. */ Fx.Morph = new Class({ Extends: Fx.CSS, initialize: function(element, options){ this.element = this.subject = $(element); this.parent(options); }, set: function(now){ if (typeof now == 'string') now = this.search(now); for (var p in now) this.render(this.element, p, now[p], this.options.unit); return this; }, compute: function(from, to, delta){ var now = {}; for (var p in from) now[p] = this.parent(from[p], to[p], delta); return now; }, start: function(properties){ if (!this.check(arguments.callee, properties)) return this; if (typeof properties == 'string') properties = this.search(properties); var from = {}, to = {}; for (var p in properties){ var parsed = this.prepare(this.element, p, properties[p]); from[p] = parsed.from; to[p] = parsed.to; } return this.parent(from, to); } }); Element.Properties.morph = { set: function(options){ var morph = this.retrieve('morph'); if (morph) morph.cancel(); return this.eliminate('morph').store('morph:options', $extend({link: 'cancel'}, options)); }, get: function(options){ if (options || !this.retrieve('morph')){ if (options || !this.retrieve('morph:options')) this.set('morph', options); this.store('morph', new Fx.Morph(this, this.retrieve('morph:options'))); } return this.retrieve('morph'); } }; Element.implement({ morph: function(props){ this.get('morph').start(props); return this; } }); /* Script: Fx.Transitions.js Contains a set of advanced transitions to be used with any of the Fx Classes. License: MIT-style license. Credits: Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified and optimized to be used with MooTools. */ (function(){ var old = Fx.prototype.initialize; Fx.prototype.initialize = function(options){ old.call(this, options); var trans = this.options.transition; if (typeof trans == 'string' && (trans = trans.split(':'))){ var base = Fx.Transitions; base = base[trans[0]] || base[trans[0].capitalize()]; if (trans[1]) base = base['ease' + trans[1].capitalize() + (trans[2] ? trans[2].capitalize() : '')]; this.options.transition = base; } }; })(); Fx.Transition = function(transition, params){ params = $splat(params); return $extend(transition, { easeIn: function(pos){ return transition(pos, params); }, easeOut: function(pos){ return 1 - transition(1 - pos, params); }, easeInOut: function(pos){ return (pos <= 0.5) ? transition(2 * pos, params) / 2 : (2 - transition(2 * (1 - pos), params)) / 2; } }); }; Fx.Transitions = new Hash({ linear: $arguments(0) }); Fx.Transitions.extend = function(transitions){ for (var transition in transitions) Fx.Transitions[transition] = new Fx.Transition(transitions[transition]); }; Fx.Transitions.extend({ Pow: function(p, x){ return Math.pow(p, x[0] || 6); }, Expo: function(p){ return Math.pow(2, 8 * (p - 1)); }, Circ: function(p){ return 1 - Math.sin(Math.acos(p)); }, Sine: function(p){ return 1 - Math.sin((1 - p) * Math.PI / 2); }, Back: function(p, x){ x = x[0] || 1.618; return Math.pow(p, 2) * ((x + 1) * p - x); }, Bounce: function(p){ var value; for (var a = 0, b = 1; 1; a += b, b /= 2){ if (p >= (7 - 4 * a) / 11){ value = - Math.pow((11 - 6 * a - 11 * p) / 4, 2) + b * b; break; } } return value; }, Elastic: function(p, x){ return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3); } }); ['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){ Fx.Transitions[transition] = new Fx.Transition(function(p){ return Math.pow(p, [i + 2]); }); }); /* Script: Request.js Powerful all purpose Request Class. Uses XMLHTTPRequest. License: MIT-style license. */ var Request = new Class({ Implements: [Chain, Events, Options], options: { /*onRequest: $empty, onSuccess: $empty, onFailure: $empty, onException: $empty,*/ url: '', data: '', headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' }, async: true, format: false, method: 'post', link: 'ignore', isSuccess: null, emulation: true, urlEncoded: true, encoding: 'utf-8', evalScripts: false, evalResponse: false }, initialize: function(options){ this.xhr = new Browser.Request(); this.setOptions(options); this.options.isSuccess = this.options.isSuccess || this.isSuccess; this.headers = new Hash(this.options.headers); }, onStateChange: function(){ if (this.xhr.readyState != 4 || !this.running) return; this.running = false; this.status = 0; $try(function(){ this.status = this.xhr.status; }.bind(this)); if (this.options.isSuccess.call(this, this.status)){ this.response = {text: this.xhr.responseText, xml: this.xhr.responseXML}; this.success(this.response.text, this.response.xml); } else { this.response = {text: null, xml: null}; this.failure(); } this.xhr.onreadystatechange = $empty; }, isSuccess: function(){ return ((this.status >= 200) && (this.status < 300)); }, processScripts: function(text){ if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return $exec(text); return text.stripScripts(this.options.evalScripts); }, success: function(text, xml){ this.onSuccess(this.processScripts(text), xml); }, onSuccess: function(){ this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain(); }, failure: function(){ this.onFailure(); }, onFailure: function(){ this.fireEvent('complete').fireEvent('failure', this.xhr); }, setHeader: function(name, value){ this.headers.set(name, value); return this; }, getHeader: function(name){ return $try(function(){ return this.xhr.getResponseHeader(name); }.bind(this)); }, check: function(caller){ if (!this.running) return true; switch (this.options.link){ case 'cancel': this.cancel(); return true; case 'chain': this.chain(caller.bind(this, Array.slice(arguments, 1))); return false; } return false; }, send: function(options){ if (!this.check(arguments.callee, options)) return this; this.running = true; var type = $type(options); if (type == 'string' || type == 'element') options = {data: options}; var old = this.options; options = $extend({data: old.data, url: old.url, method: old.method}, options); var data = options.data, url = options.url, method = options.method; switch ($type(data)){ case 'element': data = $(data).toQueryString(); break; case 'object': case 'hash': data = Hash.toQueryString(data); } if (this.options.format){ var format = 'format=' + this.options.format; data = (data) ? format + '&' + data : format; } if (this.options.emulation && ['put', 'delete'].contains(method)){ var _method = '_method=' + method; data = (data) ? _method + '&' + data : _method; method = 'post'; } if (this.options.urlEncoded && method == 'post'){ var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : ''; this.headers.set('Content-type', 'application/x-www-form-urlencoded' + encoding); } if (data && method == 'get'){ url = url + (url.contains('?') ? '&' : '?') + data; data = null; } this.xhr.open(method.toUpperCase(), url, this.options.async); this.xhr.onreadystatechange = this.onStateChange.bind(this); this.headers.each(function(value, key){ if (!$try(function(){ this.xhr.setRequestHeader(key, value); return true; }.bind(this))) this.fireEvent('exception', [key, value]); }, this); this.fireEvent('request'); this.xhr.send(data); if (!this.options.async) this.onStateChange(); return this; }, cancel: function(){ if (!this.running) return this; this.running = false; this.xhr.abort(); this.xhr.onreadystatechange = $empty; this.xhr = new Browser.Request(); this.fireEvent('cancel'); return this; } }); (function(){ var methods = {}; ['get', 'post', 'put', 'delete', 'GET', 'POST', 'PUT', 'DELETE'].each(function(method){ methods[method] = function(){ var params = Array.link(arguments, {url: String.type, data: $defined}); return this.send($extend(params, {method: method.toLowerCase()})); }; }); Request.implement(methods); })(); Element.Properties.send = { set: function(options){ var send = this.retrieve('send'); if (send) send.cancel(); return this.eliminate('send').store('send:options', $extend({ data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action') }, options)); }, get: function(options){ if (options || !this.retrieve('send')){ if (options || !this.retrieve('send:options')) this.set('send', options); this.store('send', new Request(this.retrieve('send:options'))); } return this.retrieve('send'); } }; Element.implement({ send: function(url){ var sender = this.get('send'); sender.send({data: this, url: url || sender.options.url}); return this; } }); /* Script: Request.HTML.js Extends the basic Request Class with additional methods for interacting with HTML responses. License: MIT-style license. */ Request.HTML = new Class({ Extends: Request, options: { update: false, evalScripts: true, filter: false }, processHTML: function(text){ var match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i); text = (match) ? match[1] : text; var container = new Element('div'); return $try(function(){ var root = '<root>' + text + '</root>', doc; if (Browser.Engine.trident){ doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = false; doc.loadXML(root); } else { doc = new DOMParser().parseFromString(root, 'text/xml'); } root = doc.getElementsByTagName('root')[0]; for (var i = 0, k = root.childNodes.length; i < k; i++){ var child = Element.clone(root.childNodes[i], true, true); if (child) container.grab(child); } return container; }) || container.set('html', text); }, success: function(text){ var options = this.options, response = this.response; response.html = text.stripScripts(function(script){ response.javascript = script; }); var temp = this.processHTML(response.html); response.tree = temp.childNodes; response.elements = temp.getElements('*'); if (options.filter) response.tree = response.elements.filter(options.filter); if (options.update) $(options.update).empty().adopt(response.tree); if (options.evalScripts) $exec(response.javascript); this.onSuccess(response.tree, response.elements, response.html, response.javascript); } }); Element.Properties.load = { set: function(options){ var load = this.retrieve('load'); if (load) send.cancel(); return this.eliminate('load').store('load:options', $extend({data: this, link: 'cancel', update: this, method: 'get'}, options)); }, get: function(options){ if (options || ! this.retrieve('load')){ if (options || !this.retrieve('load:options')) this.set('load', options); this.store('load', new Request.HTML(this.retrieve('load:options'))); } return this.retrieve('load'); } }; Element.implement({ load: function(){ this.get('load').send(Array.link(arguments, {data: Object.type, url: String.type})); return this; } }); /* Script: Request.JSON.js Extends the basic Request Class with additional methods for sending and receiving JSON data. License: MIT-style license. */ Request.JSON = new Class({ Extends: Request, options: { secure: true }, initialize: function(options){ this.parent(options); this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'}); }, success: function(text){ this.response.json = JSON.decode(text, this.options.secure); this.onSuccess(this.response.json, text); } }); /* Script: Assets.js Provides methods to dynamically load JavaScript, CSS, and Image files into the document. License: MIT-style license. */ var Asset = new Hash({ javascript: function(source, properties){ properties = $extend({ onload: $empty, document: document, check: $lambda(true) }, properties); var script = new Element('script', {'src': source, 'type': 'text/javascript'}); var load = properties.onload.bind(script), check = properties.check, doc = properties.document; delete properties.onload; delete properties.check; delete properties.document; script.addEvents({ load: load, readystatechange: function(){ if (['loaded', 'complete'].contains(this.readyState)) load(); } }).setProperties(properties); if (Browser.Engine.webkit419) var checker = (function(){ if (!$try(check)) return; $clear(checker); load(); }).periodical(50); return script.inject(doc.head); }, css: function(source, properties){ return new Element('link', $merge({ 'rel': 'stylesheet', 'media': 'screen', 'type': 'text/css', 'href': source }, properties)).inject(document.head); }, image: function(source, properties){ properties = $merge({ 'onload': $empty, 'onabort': $empty, 'onerror': $empty }, properties); var image = new Image(); var element = $(image) || new Element('img'); ['load', 'abort', 'error'].each(function(name){ var type = 'on' + name; var event = properties[type]; delete properties[type]; image[type] = function(){ if (!image) return; if (!element.parentNode){ element.width = image.width; element.height = image.height; } image = image.onload = image.onabort = image.onerror = null; event.delay(1, element, element); element.fireEvent(name, element, 1); }; }); image.src = element.src = source; if (image && image.complete) image.onload.delay(1); return element.setProperties(properties); }, images: function(sources, options){ options = $merge({ onComplete: $empty, onProgress: $empty }, options); if (!sources.push) sources = [sources]; var images = []; var counter = 0; sources.each(function(source){ var img = new Asset.image(source, { 'onload': function(){ options.onProgress.call(this, counter, sources.indexOf(source)); counter++; if (counter == sources.length) options.onComplete(); } }); images.push(img); }); return new Elements(images); } }); //MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License. /* Script: Drag.js The base Drag Class. Can be used to drag and resize Elements using mouse events. License: MIT-style license. */ var Drag = new Class({ Implements: [Events, Options], options: {/* onBeforeStart: $empty, onStart: $empty, onDrag: $empty, onCancel: $empty, onComplete: $empty,*/ snap: 6, unit: 'px', grid: false, style: true, limit: false, handle: false, invert: false, preventDefault: false, modifiers: {x: 'left', y: 'top'} }, initialize: function(){ var params = Array.link(arguments, {'options': Object.type, 'element': $defined}); this.element = $(params.element); this.document = this.element.getDocument(); this.setOptions(params.options || {}); var htype = $type(this.options.handle); this.handles = (htype == 'array' || htype == 'collection') ? $$(this.options.handle) : $(this.options.handle) || this.element; this.mouse = {'now': {}, 'pos': {}}; this.value = {'start': {}, 'now': {}}; this.selection = (Browser.Engine.trident) ? 'selectstart' : 'mousedown'; this.bound = { start: this.start.bind(this), check: this.check.bind(this), drag: this.drag.bind(this), stop: this.stop.bind(this), cancel: this.cancel.bind(this), eventStop: $lambda(false) }; this.attach(); }, attach: function(){ this.handles.addEvent('mousedown', this.bound.start); return this; }, detach: function(){ this.handles.removeEvent('mousedown', this.bound.start); return this; }, start: function(event){ if (this.options.preventDefault) event.preventDefault(); this.fireEvent('beforeStart', this.element); this.mouse.start = event.page; var limit = this.options.limit; this.limit = {'x': [], 'y': []}; for (var z in this.options.modifiers){ if (!this.options.modifiers[z]) continue; if (this.options.style) this.value.now[z] = this.element.getStyle(this.options.modifiers[z]).toInt(); else this.value.now[z] = this.element[this.options.modifiers[z]]; if (this.options.invert) this.value.now[z] *= -1; this.mouse.pos[z] = event.page[z] - this.value.now[z]; if (limit && limit[z]){ for (var i = 2; i--; i){ if ($chk(limit[z][i])) this.limit[z][i] = $lambda(limit[z][i])(); } } } if ($type(this.options.grid) == 'number') this.options.grid = {'x': this.options.grid, 'y': this.options.grid}; this.document.addEvents({mousemove: this.bound.check, mouseup: this.bound.cancel}); this.document.addEvent(this.selection, this.bound.eventStop); }, check: function(event){ if (this.options.preventDefault) event.preventDefault(); var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2))); if (distance > this.options.snap){ this.cancel(); this.document.addEvents({ mousemove: this.bound.drag, mouseup: this.bound.stop }); this.fireEvent('start', this.element).fireEvent('snap', this.element); } }, drag: function(event){ if (this.options.preventDefault) event.preventDefault(); this.mouse.now = event.page; for (var z in this.options.modifiers){ if (!this.options.modifiers[z]) continue; this.value.now[z] = this.mouse.now[z] - this.mouse.pos[z]; if (this.options.invert) this.value.now[z] *= -1; if (this.options.limit && this.limit[z]){ if ($chk(this.limit[z][1]) && (this.value.now[z] > this.limit[z][1])){ this.value.now[z] = this.limit[z][1]; } else if ($chk(this.limit[z][0]) && (this.value.now[z] < this.limit[z][0])){ this.value.now[z] = this.limit[z][0]; } } if (this.options.grid[z]) this.value.now[z] -= (this.value.now[z] % this.options.grid[z]); if (this.options.style) this.element.setStyle(this.options.modifiers[z], this.value.now[z] + this.options.unit); else this.element[this.options.modifiers[z]] = this.value.now[z]; } this.fireEvent('drag', this.element); }, cancel: function(event){ this.document.removeEvent('mousemove', this.bound.check); this.document.removeEvent('mouseup', this.bound.cancel); if (event){ this.document.removeEvent(this.selection, this.bound.eventStop); this.fireEvent('cancel', this.element); } }, stop: function(event){ this.document.removeEvent(this.selection, this.bound.eventStop); this.document.removeEvent('mousemove', this.bound.drag); this.document.removeEvent('mouseup', this.bound.stop); if (event) this.fireEvent('complete', this.element); } }); Element.implement({ makeResizable: function(options){ return new Drag(this, $merge({modifiers: {'x': 'width', 'y': 'height'}}, options)); } }); /* Script: Drag.Move.js A Drag extension that provides support for the constraining of draggables to containers and droppables. License: MIT-style license. */ Drag.Move = new Class({ Extends: Drag, options: { droppables: [], container: false }, initialize: function(element, options){ this.parent(element, options); this.droppables = $$(this.options.droppables); this.container = $(this.options.container); if (this.container && $type(this.container) != 'element') this.container = $(this.container.getDocument().body); element = this.element; var current = element.getStyle('position'); var position = (current != 'static') ? current : 'absolute'; if (element.getStyle('left') == 'auto' || element.getStyle('top') == 'auto') element.position(element.getPosition(element.offsetParent)); element.setStyle('position', position); this.addEvent('start', function(){ this.checkDroppables(); }, true); }, start: function(event){ if (this.container){ var el = this.element, cont = this.container, ccoo = cont.getCoordinates(el.offsetParent), cps = {}, ems = {}; ['top', 'right', 'bottom', 'left'].each(function(pad){ cps[pad] = cont.getStyle('padding-' + pad).toInt(); ems[pad] = el.getStyle('margin-' + pad).toInt(); }, this); var width = el.offsetWidth + ems.left + ems.right, height = el.offsetHeight + ems.top + ems.bottom; var x = [ccoo.left + cps.left, ccoo.right - cps.right - width]; var y = [ccoo.top + cps.top, ccoo.bottom - cps.bottom - height]; this.options.limit = {x: x, y: y}; } this.parent(event); }, checkAgainst: function(el){ el = el.getCoordinates(); var now = this.mouse.now; return (now.x > el.left && now.x < el.right && now.y < el.bottom && now.y > el.top); }, checkDroppables: function(){ var overed = this.droppables.filter(this.checkAgainst, this).getLast(); if (this.overed != overed){ if (this.overed) this.fireEvent('leave', [this.element, this.overed]); if (overed){ this.overed = overed; this.fireEvent('enter', [this.element, overed]); } else { this.overed = null; } } }, drag: function(event){ this.parent(event); if (this.droppables.length) this.checkDroppables(); }, stop: function(event){ this.checkDroppables(); this.fireEvent('drop', [this.element, this.overed]); this.overed = null; return this.parent(event); } }); Element.implement({ makeDraggable: function(options){ return new Drag.Move(this, options); } }); /* Script: Sortables.js Class for creating a drag and drop sorting interface for lists of items. License: MIT-style license. */ var Sortables = new Class({ Implements: [Events, Options], options: {/* onSort: $empty, onStart: $empty, onComplete: $empty,*/ snap: 4, opacity: 1, clone: false, revert: false, handle: false, constrain: false }, initialize: function(lists, options){ this.setOptions(options); this.elements = []; this.lists = []; this.idle = true; this.addLists($$($(lists) || lists)); if (!this.options.clone) this.options.revert = false; if (this.options.revert) this.effect = new Fx.Morph(null, $merge({duration: 250, link: 'cancel'}, this.options.revert)); }, attach: function(){ this.addLists(this.lists); return this; }, detach: function(){ this.lists = this.removeLists(this.lists); return this; }, addItems: function(){ Array.flatten(arguments).each(function(element){ this.elements.push(element); var start = element.retrieve('sortables:start', this.start.bindWithEvent(this, element)); (this.options.handle ? element.getElement(this.options.handle) || element : element).addEvent('mousedown', start); }, this); return this; }, addLists: function(){ Array.flatten(arguments).each(function(list){ this.lists.push(list); this.addItems(list.getChildren()); }, this); return this; }, removeItems: function(){ var elements = []; Array.flatten(arguments).each(function(element){ elements.push(element); this.elements.erase(element); var start = element.retrieve('sortables:start'); (this.options.handle ? element.getElement(this.options.handle) || element : element).removeEvent('mousedown', start); }, this); return $$(elements); }, removeLists: function(){ var lists = []; Array.flatten(arguments).each(function(list){ lists.push(list); this.lists.erase(list); this.removeItems(list.getChildren()); }, this); return $$(lists); }, getClone: function(event, element){ if (!this.options.clone) return new Element('div').inject(document.body); if ($type(this.options.clone) == 'function') return this.options.clone.call(this, event, element, this.list); return element.clone(true).setStyles({ 'margin': '0px', 'position': 'absolute', 'visibility': 'hidden', 'width': element.getStyle('width') }).inject(this.list).position(element.getPosition(element.getOffsetParent())); }, getDroppables: function(){ var droppables = this.list.getChildren(); if (!this.options.constrain) droppables = this.lists.concat(droppables).erase(this.list); return droppables.erase(this.clone).erase(this.element); }, insert: function(dragging, element){ var where = 'inside'; if (this.lists.contains(element)){ this.list = element; this.drag.droppables = this.getDroppables(); } else { where = this.element.getAllPrevious().contains(element) ? 'before' : 'after'; } this.element.inject(element, where); this.fireEvent('sort', [this.element, this.clone]); }, start: function(event, element){ if (!this.idle) return; this.idle = false; this.element = element; this.opacity = element.get('opacity'); this.list = element.getParent(); this.clone = this.getClone(event, element); this.drag = new Drag.Move(this.clone, { snap: this.options.snap, container: this.options.constrain && this.element.getParent(), droppables: this.getDroppables(), onSnap: function(){ event.stop(); this.clone.setStyle('visibility', 'visible'); this.element.set('opacity', this.options.opacity || 0); this.fireEvent('start', [this.element, this.clone]); }.bind(this), onEnter: this.insert.bind(this), onCancel: this.reset.bind(this), onComplete: this.end.bind(this) }); this.clone.inject(this.element, 'before'); this.drag.start(event); }, end: function(){ this.drag.detach(); this.element.set('opacity', this.opacity); if (this.effect){ var dim = this.element.getStyles('width', 'height'); var pos = this.clone.computePosition(this.element.getPosition(this.clone.offsetParent)); this.effect.element = this.clone; this.effect.start({ top: pos.top, left: pos.left, width: dim.width, height: dim.height, opacity: 0.25 }).chain(this.reset.bind(this)); } else { this.reset(); } }, reset: function(){ this.idle = true; this.clone.destroy(); this.fireEvent('complete', this.element); }, serialize: function(){ var params = Array.link(arguments, {modifier: Function.type, index: $defined}); var serial = this.lists.map(function(list){ return list.getChildren().map(params.modifier || function(element){ return element.get('id'); }, this); }, this); var index = params.index; if (this.lists.length == 1) index = 0; return $chk(index) && index >= 0 && index < this.lists.length ? serial[index] : serial; } }); //MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License. /* Script: Fx.Slide.js Effect to slide an element in and out of view. License: MIT-style license. */ Fx.Slide = new Class({ Extends: Fx, options: { mode: 'vertical', wrapper_class: '' }, initialize: function(element, options){ this.addEvent('complete', function(){ this.open = (this.wrapper['offset' + this.layout.capitalize()] != 0); if (this.open && Browser.Engine.webkit419) this.element.dispose().inject(this.wrapper); }, true); this.element = this.subject = $(element); this.parent(options); var wrapper = this.element.retrieve('wrapper'); this.wrapper = wrapper || new Element('div', { 'class': this.options.wrapper_class, styles: $extend(this.element.getStyles('margin', 'position'), {'overflow': 'hidden'}) }).wraps(this.element); this.element.store('wrapper', this.wrapper).setStyle('margin', 0); this.now = []; this.open = true; }, vertical: function(){ this.margin = 'margin-top'; this.layout = 'height'; this.offset = this.element.offsetHeight; }, horizontal: function(){ this.margin = 'margin-left'; this.layout = 'width'; this.offset = this.element.offsetWidth; }, set: function(now){ this.element.setStyle(this.margin, now[0]); this.wrapper.setStyle(this.layout, now[1]); return this; }, compute: function(from, to, delta){ var now = []; var x = 2; x.times(function(i){ now[i] = Fx.compute(from[i], to[i], delta); }); return now; }, start: function(how, mode){ if (!this.check(arguments.callee, how, mode)) return this; this[mode || this.options.mode](); var margin = this.element.getStyle(this.margin).toInt(); var layout = this.wrapper.getStyle(this.layout).toInt(); var caseIn = [[margin, layout], [0, this.offset]]; var caseOut = [[margin, layout], [-this.offset, 0]]; var start; switch (how){ case 'in': start = caseIn; break; case 'out': start = caseOut; break; case 'toggle': start = (this.wrapper['offset' + this.layout.capitalize()] == 0) ? caseIn : caseOut; } return this.parent(start[0], start[1]); }, slideIn: function(mode){ return this.start('in', mode); }, slideOut: function(mode){ return this.start('out', mode); }, hide: function(mode){ this[mode || this.options.mode](); this.open = false; return this.set([-this.offset, 0]); }, show: function(mode){ this[mode || this.options.mode](); this.open = true; return this.set([0, this.offset]); }, toggle: function(mode){ return this.start('toggle', mode); } }); Element.Properties.slide = { set: function(options){ var slide = this.retrieve('slide'); if (slide) slide.cancel(); return this.eliminate('slide').store('slide:options', $extend({link: 'cancel'}, options)); }, get: function(options){ if (options || !this.retrieve('slide')){ if (options || !this.retrieve('slide:options')) this.set('slide', options); this.store('slide', new Fx.Slide(this, this.retrieve('slide:options'))); } return this.retrieve('slide'); } }; Element.implement({ slide: function(how, mode){ how = how || 'toggle'; var slide = this.get('slide'), toggle; switch (how){ case 'hide': slide.hide(mode); break; case 'show': slide.show(mode); break; case 'toggle': var flag = this.retrieve('slide:flag', slide.open); slide[(flag) ? 'slideOut' : 'slideIn'](mode); this.store('slide:flag', !flag); toggle = true; break; default: slide.start(how, mode); } if (!toggle) this.eliminate('slide:flag'); return this; } }); Fx.Scroll = new Class({ Extends: Fx, options: { offset: {'x': 0, 'y': 0}, wheelStops: true }, initialize: function(element, options){ this.element = this.subject = $(element); this.parent(options); var cancel = this.cancel.bind(this, false); if ($type(this.element) != 'element') this.element = $(this.element.getDocument().body); var stopper = this.element; if (this.options.wheelStops){ this.addEvent('start', function(){ stopper.addEvent('mousewheel', cancel); }, true); this.addEvent('complete', function(){ stopper.removeEvent('mousewheel', cancel); }, true); } }, set: function(){ var now = Array.flatten(arguments); this.element.scrollTo(now[0], now[1]); }, compute: function(from, to, delta){ var now = []; var x = 2; x.times(function(i){ now.push(Fx.compute(from[i], to[i], delta)); }); return now; }, start: function(x, y){ if (!this.check(arguments.callee, x, y)) return this; var offsetSize = this.element.getSize(), scrollSize = this.element.getScrollSize(); var scroll = this.element.getScroll(), values = {x: x, y: y}; for (var z in values){ var max = scrollSize[z] - offsetSize[z]; if ($chk(values[z])) values[z] = ($type(values[z]) == 'number') ? values[z].limit(0, max) : max; else values[z] = scroll[z]; values[z] += this.options.offset[z]; } return this.parent([scroll.x, scroll.y], [values.x, values.y]); }, toTop: function(){ return this.start(false, 0); }, toLeft: function(){ return this.start(0, false); }, toRight: function(){ return this.start('right', false); }, toBottom: function(){ return this.start(false, 'bottom'); }, toElement: function(el){ var position = $(el).getPosition(this.element); return this.start(position.x, position.y); } }); /* --- script: Element.Forms.js description: Extends the Element native object to include methods useful in managing inputs. license: MIT-style license authors: - Aaron Newton requires: - core:1.2.4/Element - /MooTools.More provides: [Element.Forms] ... */ Element.implement({ tidy: function(){ this.set('value', this.get('value').tidy()); }, getTextInRange: function(start, end){ return this.get('value').substring(start, end); }, getSelectedText: function(){ if (this.setSelectionRange) return this.getTextInRange(this.getSelectionStart(), this.getSelectionEnd()); return document.selection.createRange().text; }, getSelectedRange: function() { if ($defined(this.selectionStart)) return {start: this.selectionStart, end: this.selectionEnd}; var pos = {start: 0, end: 0}; var range = this.getDocument().selection.createRange(); if (!range || range.parentElement() != this) return pos; var dup = range.duplicate(); if (this.type == 'text') { pos.start = 0 - dup.moveStart('character', -100000); pos.end = pos.start + range.text.length; } else { var value = this.get('value'); var offset = value.length; dup.moveToElementText(this); dup.setEndPoint('StartToEnd', range); if(dup.text.length) offset -= value.match(/[\n\r]*$/)[0].length; pos.end = offset - dup.text.length; dup.setEndPoint('StartToStart', range); pos.start = offset - dup.text.length; } return pos; }, getSelectionStart: function(){ return this.getSelectedRange().start; }, getSelectionEnd: function(){ return this.getSelectedRange().end; }, setCaretPosition: function(pos){ if (pos == 'end') pos = this.get('value').length; this.selectRange(pos, pos); return this; }, getCaretPosition: function(){ return this.getSelectedRange().start; }, selectRange: function(start, end){ if (this.setSelectionRange) { this.focus(); this.setSelectionRange(start, end); } else { var value = this.get('value'); var diff = value.substr(start, end - start).replace(/\r/g, '').length; start = value.substr(0, start).replace(/\r/g, '').length; var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', start + diff); range.moveStart('character', start); range.select(); } return this; }, insertAtCursor: function(value, select){ var pos = this.getSelectedRange(); var text = this.get('value'); this.set('value', text.substring(0, pos.start) + value + text.substring(pos.end, text.length)); if ($pick(select, true)) this.selectRange(pos.start, pos.start + value.length); else this.setCaretPosition(pos.start + value.length); return this; }, insertAroundCursor: function(options, select){ options = $extend({ before: '', defaultMiddle: '', after: '' }, options); var value = this.getSelectedText() || options.defaultMiddle; var pos = this.getSelectedRange(); var text = this.get('value'); if (pos.start == pos.end){ this.set('value', text.substring(0, pos.start) + options.before + value + options.after + text.substring(pos.end, text.length)); this.selectRange(pos.start + options.before.length, pos.end + options.before.length + value.length); } else { var current = text.substring(pos.start, pos.end); this.set('value', text.substring(0, pos.start) + options.before + current + options.after + text.substring(pos.end, text.length)); var selStart = pos.start + options.before.length; if ($pick(select, true)) this.selectRange(selStart, selStart + current.length); else this.setCaretPosition(selStart + text.length); } return this; } }); /* Script: Slider.js Class for creating horizontal and vertical slider controls. License: MIT-style license. */ var Slider = new Class({ Implements: [Events, Options], options: {/* onChange: $empty, onComplete: $empty,*/ onTick: function(position){ if(this.options.snap) position = this.toPosition(this.step); this.knob.setStyle(this.property, position); }, snap: false, offset: 0, range: false, wheel: false, steps: 100, mode: 'horizontal' }, initialize: function(element, knob, options){ this.setOptions(options); this.element = $(element); this.knob = $(knob); this.previousChange = this.previousEnd = this.step = -1; this.element.addEvent('mousedown', this.clickedElement.bind(this)); if (this.options.wheel) this.element.addEvent('mousewheel', this.scrolledElement.bindWithEvent(this)); var offset, limit = {}, modifiers = {'x': false, 'y': false}; switch (this.options.mode){ case 'vertical': this.axis = 'y'; this.property = 'top'; offset = 'offsetHeight'; break; case 'horizontal': this.axis = 'x'; this.property = 'left'; offset = 'offsetWidth'; } this.half = this.knob[offset] / 2; this.full = this.element[offset] - this.knob[offset] + (this.options.offset * 2); this.min = $chk(this.options.range[0]) ? this.options.range[0] : 0; this.max = $chk(this.options.range[1]) ? this.options.range[1] : this.options.steps; this.range = this.max - this.min; this.steps = this.options.steps || this.full; this.stepSize = Math.abs(this.range) / this.steps; this.stepWidth = this.stepSize * this.full / Math.abs(this.range) ; this.knob.setStyle('position', 'relative').setStyle(this.property, - this.options.offset); modifiers[this.axis] = this.property; limit[this.axis] = [- this.options.offset, this.full - this.options.offset]; this.drag = new Drag(this.knob, { snap: 0, limit: limit, modifiers: modifiers, onDrag: this.draggedKnob.bind(this), onStart: this.draggedKnob.bind(this), onComplete: function(){ this.draggedKnob(); this.end(); }.bind(this) }); if (this.options.snap) { this.drag.options.grid = Math.ceil(this.stepWidth); this.drag.options.limit[this.axis][1] = this.full; } }, set: function(step){ if (!((this.range > 0) ^ (step < this.min))) step = this.min; if (!((this.range > 0) ^ (step > this.max))) step = this.max; this.step = Math.round(step); this.checkStep(); this.end(); this.fireEvent('tick', this.toPosition(this.step)); return this; }, clickedElement: function(event){ var dir = this.range < 0 ? -1 : 1; var position = event.page[this.axis] - this.element.getPosition()[this.axis] - this.half; position = position.limit(-this.options.offset, this.full -this.options.offset); this.step = Math.round(this.min + dir * this.toStep(position)); this.checkStep(); this.end(); this.fireEvent('tick', position); }, scrolledElement: function(event){ var mode = (this.options.mode == 'horizontal') ? (event.wheel < 0) : (event.wheel > 0); this.set(mode ? this.step - this.stepSize : this.step + this.stepSize); event.stop(); }, draggedKnob: function(){ var dir = this.range < 0 ? -1 : 1; var position = this.drag.value.now[this.axis]; position = position.limit(-this.options.offset, this.full -this.options.offset); this.step = Math.round(this.min + dir * this.toStep(position)); this.checkStep(); }, checkStep: function(){ if (this.previousChange != this.step){ this.previousChange = this.step; this.fireEvent('change', this.step); } }, end: function(){ if (this.previousEnd !== this.step){ this.previousEnd = this.step; this.fireEvent('complete', this.step + ''); } }, toStep: function(position){ var step = (position + this.options.offset) * this.stepSize / this.full * this.steps; return this.options.steps ? Math.round(step -= step % this.stepSize) : step; }, toPosition: function(step){ return (this.full * Math.abs(this.min - step)) / (this.steps * this.stepSize) - this.options.offset; } });
JavaScript
/** * This script contains the grid control. * The plugin should be applied to a DIV element. * Grid table will be built inside this element. * The options object should be specified in the followingi format: * { * columns: [ * {title: 'Id', field: 'id', type: 'text', width: '170'}, * {title: 'Name', field: 'name', type: 'text', width: '170'} * ], * data: [ * [1, "First row"] * [2, {display: "Second row", value: any_custom_data}] * ], * scrollable: true, * allowAutoRowAdding: false, * sortable: true, * scrollable: true, * name: 'myGrid' // This value will be use in hidden input names. * } * The "type" property of column specifies a column editor to be used for the column. * The "data" property is not required. However if the data is not provided, the DOM element * the plugin is applied to should contain a table markup with THEAD and TBODY elements. Head columns * should match the data provided in the "columns" property. If the table already exists, the "data" * element is ignored. Cells can contain a hidden input element with the "cell-value" class. * See jquery.backend.grid.editors.js for the list of supported editors. * The editor class name is calculated as the column type name + "Editor", so that * "text" is converted to "textEditor". */ (function( $, undefined ) { jQuery.widget( "ui.grid", { options: { allowAutoRowAdding: true, name: 'grid', dataFieldName: null, sortable: false, scrollable: false, scrollableViewportClass: null, rowsDeletable: false, deleteRowMessage: 'Do you really want to delete this row?', useDataSource: false, focusFirst: false }, /** * Updates table column widths. */ alignColumns: function(row) { if (this.options.useDataSource) return; var widths = [], self = this; this.headTable.find('th div.ui-grid-head-content').each(function(index, div){ widths.push(jQuery(div).outerWidth()); }); if (row === undefined) { this.bodyTable.find('tr:first-child').each(function(rowIndex, row) { $(row).find('td').each(function(index, td) { if (index < (widths.length-1)) { var tweak = 0, $td = jQuery(td); if (Browser.Engine.webkit && !self.isChrome && index > 0) tweak = 1; $td.css('width', (widths[index] + tweak) + 'px'); $td.find('span.cell-content').css('width', (widths[index] + tweak - 18) + 'px'); } }); }) } else { row.find('td').each(function(index, td) { if (index < (widths.length-1)) { var tweak = 0; if (Browser.Engine.webkit && index > 0) tweak = 1; jQuery(td).css('width', (widths[index] + tweak) + 'px'); } }) } }, /** * Adds new row to the table. * @param array data Optional data array. If the second parameter is required, pass false to this parameter. * @param string position Specifies the new row position. * Possible values: 'top', 'bottom', 'above', 'below'. 'bottom' is the default value. */ addRow: function(data, position) { if (!this.options.allowAutoRowAdding) return null; if (this._isNoSearchResults()) return false; var position = position === undefined ? 'bottom' : position; if (data == undefined || data === false) { data = []; for (var index=0; index<this.options.columns.length; index++) data.push(''); } var row = this._buildRow(data, position), offset = 'bottom'; if (position == 'top') offset = 'top'; else if (position == 'above' || position == 'below') { if (this.currentRow === undefined || !this.currentRow[0].parentNode) offset = 'bottom'; else offset = 'relative'; } this.alignColumns(row); if (!this.options.useDataSource) this._updateScroller(offset); this._fixBottomBorder(); this._assignRowEventHandlers(row); this._setCurrentRow(jQuery(row)); if (this.options.useDataSource) { var recordCount = parseInt(this.element.find('.pagination .row_count').text()); if (recordCount != NaN) this.element.find('.pagination .row_count').text(recordCount+1); } return row; }, /** * Deletes a current row */ deleteRow: function() { var self = this; if (!this.currentRow) return false; var currentPage = 0, row = this.currentRow; if (self.options.useDataSource) currentPage = self._getCurrentPage(); var cell = this.currentRow.find('td:first'), rowIndex = this.bodyTable.children('tr').index(this.currentRow), cellIndex = this.currentRow.children('td').index(cell); if (cell.length && !this.options.useDataSource) this._navigateUp(cell); self._deleteRow(row, true, function(){ if (self.options.useDataSource) { if (cell) { var row = (currentPage == self._getCurrentPage()) ? self.bodyTable.find('tr:eq('+rowIndex+')') : self.bodyTable.find('tr:last'); if (!row.length) row = self.bodyTable.find('tr:last'); if (row.length) { self._initRow(row) row.find('td:eq('+cellIndex+')').trigger('navigateTo'); } } } }); }, appendRow: function(currentCell, ev) { var self = this; if (!this.options.useDataSource) return false; if (self.disableRowAdding !== undefined && self.disableRowAdding) return false; this._hideEditors(); var cell = currentCell !== undefined ? currentCell : ((ev !== undefined && ev.target !== undefined) ? jQuery(ev.target).closest('table.ui-grid-body tr td') : null); var index = (cell && cell !== null && cell.length) ? cell.parent().children('td').index(cell) : 0; self._createRowInTheEnd(function(nextRow){ if (!nextRow.length) return; self._initRow(nextRow); if (index !== null) nextRow.find('td:eq('+index+')').trigger('navigateTo', ['left']); }); return true; }, rebuild: function() { this._build(); }, focusFirst: function() { if (this._hasRows()) { var firstRow = this.bodyTable.find('tr:first'); this._initRow(firstRow); window.setTimeout(function(){ firstRow.find('td.ui-grid-cell-navigatable:first').trigger('navigateTo'); }, 100); } }, _create: function() { jQuery(this.element).data('ui.grid', this); this.isChrome = jQuery('body').hasClass('chrome'); this._build(); this.dragStarted = false; var self = this; jQuery(window).bind('phpr_widget_response_data', function(event, data){ self._handleWidgetResponseData(data); }); }, _build: function() { if (this.options.columns === undefined) { this._trace('Data grid has no columns. Exiting.'); return; } if (this.element.find('input.grid-table-disabled').length) { if (this.headTable !== undefined && this.headTable && !this.options.useDataSource) this.headTable.remove(); return; } this.element.addClass('ui-grid'); this.existingTable = this.element.find('table'); this.actionName = this.element.find('input.grid-event-handler-name').attr('value'); if (this.options.useDataSource) this.container = this.element.find('.ui-grid-table-container'); this._buildHead(); this._buildBody(); if (this.options.useDataSource && this.built === undefined) { var columnGroupsTitleHeight = this.headTable.find('.ui-column-group-row').height(); if (columnGroupsTitleHeight > 0) columnGroupsTitleHeight += 1; this.container.css('height', (this.bodyTable.find('tr:first').height()*(this.options.pageSize+1)+2)+columnGroupsTitleHeight+'px'); var scroller = this.element.find('.ui-grid-h-scroll'); scroller.scrollLeft(0); this._bindSearch(); } if (!this.options.useDataSource) { this.alignColumns(); var self = this; window.setTimeout(function(){ self._updateScroller(); }, 200); jQuery(window).bind('resize', function(){ self.alignColumns(); }); } if (this.built === undefined && this.options.focusFirst) this.focusFirst(); this.built = true; }, _updateScroller: function(direction){ if (this.options.scrollable) this.scroller.update(direction); }, _buildHead: function() { if (!this.options.useDataSource) { this.headTable = jQuery('<table class="ui-grid-head"></table>'); var row = jQuery('<tr></tr>') this.headTable.append(jQuery('<thead></thead>').append(row)); jQuery.each(this.options.columns, function(index, columnData){ var cell = jQuery('<th></th>'), content = jQuery('<div class="ui-grid-head-content"></div>'); cell.append(content); content.text(columnData.title); if (columnData.width !== undefined) cell.css('width', columnData.width + 'px'); if (columnData.align !== undefined) cell.addClass(columnData.align); row.append(cell); }); this.element.find('table').find('thead').remove(); this.element.prepend(this.headTable); } else this.headTable = this.element.find('table').find('thead'); if (this.built === undefined) this._initHeaderCheckboxes(); }, _buildBody: function() { var self = this; this.bodyTable = this.existingTable.length ? this.existingTable.find('tbody') : jQuery('<table class="ui-grid-body"></table>'); if (!this.existingTable.length) { jQuery.each(this.options.data, function(rowIndex, rowData) { self._buildRow(rowData); }); } else { this.bodyTable.addClass('ui-grid-body'); if (!this.options.useDataSource || this.built === undefined) this.bodyTable.bind('mouseover', function(ev){ if (ev.target !== undefined) self._initRow(jQuery(ev.target).closest('tr')); }); } if (this.options.scrollable) { this.scrollablePanel = this.element.find('div.backend_scroller'); this.scroller = new BackendVScroller(this.scrollablePanel[0], { slider_height_tweak: 0, auto_hide_slider: true, position_threshold: 9 }); this.viewport = this.scrollablePanel; this.overview = this.bodyTable; this.scrollablePanel.bind('onScroll', function(){ self._hideRowMenu(); self._hideEditors(); }); this.scrollablePanel.bind('onBeforeWheel', function(event){ if (self._scrollingPaused !== undefined && self._scrollingPaused) event.preventDefault(); }); } else this.headTable.after(this.bodyTable); if ((!this.options.useDataSource || this.built === undefined) && !this._hasRows()) this.addRow(); this._assignRowEventHandlers(); if (this.options.sortable) { this.dragging = false; this.bodyTable.addClass('ui-grid-draggable'); jQuery(document).bind('mousemove', function(event){self._mouseMove(event);}); jQuery(document).bind('mouseup', function(event){self._mouseUp(event);}); } if (this.built === undefined) { this.bodyTable.bind('mouseleave', function(event){ self._hideRowMenu(event); }) this._assignBodyEventHandlers(); this._assignDocumentHandlers(); } this._fixBottomBorder(); }, _buildRow: function(rowData, position) { var row = jQuery('<tr></tr>'), self = this, position = position === undefined ? 'bottom' : position; this.rowsAdded = this.rowsAdded === undefined ? 1 : this.rowsAdded+1; jQuery.each(rowData, function(cellIndex, cellData){ var cell = jQuery('<td></td>').data('ui.grid', self); self._getColumnEditor(cellIndex).initContent(cell, cellData, row, cellIndex, self.options.columns[cellIndex], -1*self.rowsAdded); row[0].rowDataIndex = -1*self.rowsAdded; if (self.options.columns[cellIndex].align !== undefined) cell.addClass(self.options.columns[cellIndex].align); if (self.options.columns[cellIndex].cell_css_class !== undefined) cell.addClass(self.options.columns[cellIndex].cell_css_class); if (self.options.rowsDeletable && rowData.length == cellIndex+1) self._createRowMenu(row, cell, self); if (self.options.columns[cellIndex].default_text !== undefined) cell.find('span.cell-content').text(self.options.columns[cellIndex].default_text); row.append(cell); }); row[0].grid_initialized = true; if (position == 'bottom') self.bodyTable.append(row); else if (position == 'top') self.bodyTable.prepend(row); else if (position == 'above' || position == 'below') { if (self.currentRow === undefined || !self.currentRow[0].parentNode) self.bodyTable.append(row); else { if (position == 'above') row.insertBefore(self.currentRow); else row.insertAfter(self.currentRow); } } this._markRowSearchUpdated(-1*self.rowsAdded); return row; }, _fixBottomBorder: function() { if (this.options.scrollable) { if (this.viewport.height() > this.overview[0].offsetHeight) this.bodyTable.closest('table').removeClass('no-bottom-border'); else this.bodyTable.closest('table').addClass('no-bottom-border'); } else if (this.options.useDataSource) { if (this.bodyTable.find('tr').length == this.options.pageSize) this.bodyTable.closest('table').addClass('no-bottom-border'); else this.bodyTable.closest('table').removeClass('no-bottom-border'); } }, _hasRows: function() { var tbody = this.bodyTable[0].tagName == 'TBODY' ? this.bodyTable : this.bodyTable.find('tbody'), i = 0; if (!tbody.length) return false; for (i=0; i< tbody[0].childNodes.length; i++) if (tbody[0].childNodes[i].nodeName == 'TR') return true; return false; }, _initRow: function(row) { if (row[0].grid_initialized !== undefined && row[0].grid_initialized) return; row[0].grid_initialized = true; var block_delete_input = row.find('input.block_delete_message'); if (block_delete_input.length && block_delete_input.val() != '') row[0].block_delete_message = block_delete_input.val(); var cells = row.find('td'), self = this; $.each(cells, function(cellIndex, cellElement){ var cell = jQuery(cellElement), valueInput = cell.find('input.cell-value'), internalInput = cell.find('input.internal-value'), rowDataIndex = cell.find('input.row-index').val(), cellData = { display: cell.text().trim(), value: valueInput.length ? valueInput.attr('value') : cell.text(), internal: internalInput.val() }; cell.data('ui.grid', self); cell.text(''); row[0].rowDataIndex = rowDataIndex; self._getColumnEditor(cellIndex).initContent(cell, cellData, row, cellIndex, self.options.columns[cellIndex], rowDataIndex); if (self.options.rowsDeletable && cells.length == cellIndex+1) self._createRowMenu(row, cell, self); }); }, _createRowMenu: function(row, cell, grid) { var contentContainer = cell.find('.cell-content-container'); menu = jQuery('<span class="ui-grid-menu"></span>'), deleteLink = jQuery('<a class="menu-delete">Delete</a>').attr('tabindex', 0).bind('click', {grid: grid}, function(ev){ ev.stopImmediatePropagation(); grid._deleteRow(row); return false; }); menu.append(deleteLink); contentContainer.append(menu); }, _assignRowEventHandlers: function(row) { if (this.options.sortable || this.options.rowsDeletable) { if (row === undefined) row = this.bodyTable.find('tr'); var self = this; if (this.options.sortable) { row.bind('mousedown', function(event){ self._dragStart(event); }); } if (this.options.rowsDeletable) { row.bind('mouseenter', function(event){self._rowMouseEnter(event);}); row.bind('mouseleave', function(event){self._rowMouseLeave(event);}); } } }, _assignDocumentHandlers: function() { var self = this; jQuery(document).bind('keydown.grid', function(ev){ return self._handleGridKeys(ev); }) }, _handleGridKeys: function(ev) { var self = this; if (self.options.useDataSource) { if (self.element.closest('html').length == 0) return; if ((ev.metaKey || ev.ctrlKey) && ev.keyCode == 73) { if (self.appendRow(null, ev)) { ev.preventDefault(); return false; } } } }, _assignBodyEventHandlers: function() { var self = this; this.bodyTable.bind('keydown', function(ev){ if (ev.keyCode == 9) { if (self._isNoSearchResults()) return false; if (ev.target !== undefined && jQuery(ev.target).hasClass('cell-content-container')) { if (!ev.shiftKey) self._navigateRight(jQuery(ev.target).parent(), false); else self._navigateLeft(jQuery(ev.target).parent(), false); ev.preventDefault(); return false; } } if ((ev.metaKey || ev.ctrlKey)) { if (ev.target !== undefined) { if (self._isNoSearchResults()) return false; var cell = jQuery(ev.target).closest('table.ui-grid-body tr td'); if (ev.keyCode == 68) { if (!self.options.rowsDeletable) return false; if (self._isNoSearchResults()) return false; var row = jQuery(ev.target).closest('table.ui-grid-body tr'), cellIndex = row.children('td').index(cell), rowIndex = self.bodyTable.children('tr').index(row), currentPage = 0; if (self.options.useDataSource) currentPage = self._getCurrentPage(); if (cell.length && !self.options.useDataSource) self._navigateUp(cell); if (row.length) self._deleteRow(row, true, function(){ if (self.options.useDataSource) { if (cell) { var row = (currentPage == self._getCurrentPage()) ? self.bodyTable.find('tr:eq('+rowIndex+')') : self.bodyTable.find('tr:last'); if (!row.length) row = self.bodyTable.find('tr:last'); if (row.length) { self._initRow(row) row.find('td:eq('+cellIndex+')').trigger('navigateTo'); } } } }); ev.preventDefault(); return false; } else if (ev.keyCode == 73) { if (!self.options.allowAutoRowAdding) return false; if (self.options.useDataSource) return false; self.addRow(false, 'above'); if (cell.length) self._navigateUp(cell); ev.preventDefault(); return false; } } } }) }, _deleteRow: function(row, noMessage, onComplete) { if (this._isNoSearchResults()) return false; row.addClass('ui-selected'); if (noMessage === undefined || noMessage === false) if (!confirm(this.options.deleteRowMessage)) { row.removeClass('ui-selected'); return; } if (row[0].block_delete_message !== undefined) { alert(row[0].block_delete_message); return; } if (!this.options.useDataSource) { row.remove(); this._hideRowMenu(); if (!this.bodyTable[0].rows.length) this.addRow(); this.alignColumns(); this._updateScroller(); this._fixBottomBorder(); } else { var self = this; this._gotoPage(this._getCurrentPage(), { data: {'phpr_delete_row': row[0].rowDataIndex}, 'onComplete': function(){ if (!self.bodyTable[0].rows.length) self.addRow(); if (onComplete !== undefined) onComplete(); } }); } }, _bindSearch: function() { this.searchField = jQuery('#' + this.element.attr('id') + '_search_field') if (this.searchField.length) { var self = this; new InputChangeTracker(this.searchField.attr('id'), {regexp_mask: '^.*$'}).addEvent('change', function(){ self._updateSearch(); }); this.searchField.bind('keydown', function(ev){ if (ev.keyCode == 13) self._updateSearch(); }) } }, _hideEditors: function() { this.element.trigger('hideEditors'); }, _scrollToCell: function(cell) { var scroller = this.element.find('.ui-grid-h-scroll'); if (scroller.length) { cellPosition = cell.position(); if (cellPosition.left < 0) { var tweak = cell.is(':first-child') ? -1 : 0; scroller.scrollLeft(scroller.scrollLeft() + cellPosition.left + tweak); } else { var offsetRight = scroller.width() - (cellPosition.left + cell.width()); if (offsetRight < 0) scroller.scrollLeft(scroller.scrollLeft() - offsetRight); } } }, _pauseScrolling: function() { this._scrollingPaused = true; this.element.find('.ui-grid-h-scroll').addClass('no-scroll'); }, _resumeScrolling: function() { this._scrollingPaused = false; this.element.find('.ui-grid-h-scroll').removeClass('no-scroll'); }, _disableRowAdding: function() { this.disableRowAdding = true; }, _enableRowAdding: function() { this.disableRowAdding = false; }, /* * Row menus */ _rowMouseEnter: function(event){ var self = this; jQuery(event.currentTarget).find('span.ui-grid-menu').removeClass('menu-visible'); this._clearMenuTimer(); this.menuTimer = window.setInterval(function(){ self._displayRowMenu(event); }, 200); }, _displayRowMenu: function(event) { this._clearMenuTimer(); var row = jQuery(event.currentTarget); if (row.hasClass('ui-no-menu')) return; var menu = row.find('span.ui-grid-menu'); if (!menu.length) return; menu.css('left', 'auto'); var rowHeight = row.outerHeight(), scroller = this.element.find('.ui-grid-h-scroll'); if (scroller.length) { var cell = row.find('td:last'), scrollerWidth = scroller.width(), cellWidth = cell.width(), fixMenuPosition = function() { var cellPosition = cell.position(), cellOffset = cellPosition.left - scrollerWidth; if ((cellOffset + cellWidth) > 0) menu.css('left', (-1*cellOffset - 21) + 'px'); else menu.css('left', 'auto'); }; scroller.bind('scroll.grid', fixMenuPosition); fixMenuPosition(); } menu.css('height', rowHeight-1); menu.addClass('menu-visible'); this.currentMenu = menu; }, _rowMouseLeave: function(event) { this._clearMenuTimer(); }, _hideRowMenu: function(event) { this._clearMenuTimer(); if (!this.currentMenu) return; var scroller = this.element.find('.ui-grid-h-scroll'); scroller.unbind('.grid'); this.currentMenu.removeClass('menu-visible'); this.currentMenu = null; }, _disableRowMenu: function(cell) { this._clearMenuTimer(); this._hideRowMenu(); jQuery(cell).closest('tr').addClass('ui-no-menu'); }, _enableRowMenu: function(cell) { jQuery(cell).closest('tr').removeClass('ui-no-menu'); }, _clearMenuTimer: function() { if (this.menuTimer) { window.clearInterval(this.menuTimer); this.menuTimer = null; } }, /* * Drag support */ _dragStart: function(event) { if (event.target.tagName == 'INPUT' || event.target.tagName == 'SELECT') return; this.dragging = true; this.dragStartOffset = event.pageY; this.dragPrevOffset = 0; this.dragRow = event.currentTarget; this.dragStarted = false; this.bodyTable.disableSelection(); if (this.options.scrollable) { this.viewportOffset = this.viewport.offset(); this.viewportHeight = this.viewport.height(); this.overviewHeight = this.overview.height(); } }, _mouseMove: function(event) { if (!this.dragging) return; if (!this.dragStarted) { this.element.trigger('hideEditors'); this.dragStarted = true; this.bodyTable.addClass('drag'); jQuery(this.dragRow).addClass('ui-selected'); } if (this.options.scrollable) { if (this.viewportOffset.top > event.pageY) { // var scrollOffset = Math.max(this.scrollablePanel.scrollTop() - this.viewportOffset.top + event.pageY, 0); this.scroller.update_position(this.scrollablePanel.scrollTop()-50); } else if (event.pageY > (this.viewportOffset.top + this.viewportHeight)) { // var // bottom = this.viewportOffset.top + this.viewportHeight, // scrollOffset = Math.min(this.scrollablePanel.scrollTop() + event.pageY - bottom, this.overviewHeight-this.viewportHeight); this.scroller.update_position(this.scrollablePanel.scrollTop()+50); } } var offset = event.pageY - this.dragStartOffset; if (offset != this.dragPrevOffset) { var movingDown = offset > this.dragPrevOffset; this.dragPrevOffset = offset; var currentRow = this._findDragHoverRow(this.dragRow, event.pageY); if (currentRow !== null && currentRow !== undefined) { if (movingDown) this.dragRow.parentNode.insertBefore(this.dragRow, currentRow.nextSibling); else this.dragRow.parentNode.insertBefore(this.dragRow, currentRow); } } this.alignColumns(); }, _findDragHoverRow: function(currentRow, y) { var rows = this.bodyTable[0].rows; for (var i=0; i<rows.length; i++) { var row = rows[i], rowTop = jQuery(row).offset().top, rowHeight = row.offsetHeight; if ((y > rowTop) && (y < (rowTop + rowHeight))) { if (row == currentRow) return null; return row; } } }, _mouseUp: function(event) { if (this.dragTimeout) window.clearTimeout(this.dragTimeout); if (!this.dragging) return; this.bodyTable.enableSelection(); this.bodyTable.removeClass('drag'); this.dragging = false; jQuery(this.dragRow).removeClass('ui-selected'); event.stopImmediatePropagation(); }, /* * Navigation */ _getColumnEditor: function(cellIndex) { if (this.editors === undefined) this.editors = []; if (this.editors[cellIndex] !== undefined) return this.editors[cellIndex]; var columConfiguration = this.options.columns[cellIndex], editorName = columConfiguration.type + 'Editor'; return this.editors[editorName] = new jQuery.ui.grid.editors[editorName](); }, _navigateRight: function(fromCell, selectAll) { selectAll = selectAll === undefined ? false : selectAll; var next = fromCell.nextAll('td.ui-grid-cell-navigatable'); if (next.length) { jQuery(next[0]).trigger('navigateTo', ['right', selectAll]); return true; } else { var self = this, row = fromCell.parent(); this._createFindNextRow(row, function(nextRow){ if (!nextRow.length) return false; self._initRow(nextRow); var cell = nextRow.find('td.ui-grid-cell-navigatable:first'); cell.trigger('navigateTo', ['right', selectAll]); }); return true; } return false; }, _navigateLeft: function(fromCell, selectAll) { selectAll = selectAll === undefined ? false : selectAll; var prev = fromCell.prevAll('td.ui-grid-cell-navigatable'); if (prev.length) { jQuery(prev[0]).trigger('navigateTo', ['left', selectAll]); return true; } else { var row = fromCell.closest('tr'); this._createFindPrevRow(row, function(prevRow){ if (!prevRow.length) return; self._initRow(prevRow); var cell = prevRow.find('td.ui-grid-cell-navigatable:last'); cell.trigger('navigateTo', ['left', selectAll]); }); return true; } return false; }, _navigateDown: function(fromCell) { var self = this, row = fromCell.parent(), index = row.children('td').index(fromCell); this._createFindNextRow(row, function(nextRow){ if (!nextRow.length) return; self._initRow(nextRow); nextRow.find('td:eq('+index+')').trigger('navigateTo', ['left']); }); }, _navigateUp: function(fromCell) { var self = this, row = fromCell.parent(), index = row.children('td').index(fromCell); this._createFindPrevRow(row, function(prevRow){ if (!prevRow.length) return; self._initRow(prevRow); prevRow.find('td:eq('+index+')').trigger('navigateTo', ['left']); }); }, _setCurrentRow: function(row) { if (this.currentRow !== undefined && this.currentRow != row) this.currentRow.removeClass('current-row'); this.currentRow = row; this.currentRow.addClass('current-row'); }, _createFindNextRow: function(currentRow, callback) { this._hideRowMenu(); if (!currentRow.is(':last-child')) return callback(currentRow.next('tr')); if (!this.options.useDataSource || this.bodyTable.find('tr').length < this.options.pageSize) return callback(this.addRow()); var self = this; /* * If the row is last on this page, but the page is not last, * go to the first row of the next page. */ if (!this._isLastPage()) { this._gotoPage(this._getCurrentPage() + 1, {onComplete: function(){ var row = self.bodyTable.find('tr:first'); if (row.length) callback(row); }}); } else { /* * If the row is last on this page, and the page is last, * create new record in the data source and go to the next page. */ this.rowsAdded = this.rowsAdded === undefined ? 1 : this.rowsAdded+1; this._gotoPage(this._getCurrentPage() + 1, {data: {'phpr_append_row': 1, 'phpr_new_row_key': -1*this.rowsAdded}, onComplete: function(){ var row = self.bodyTable.find('tr:first'); if (row.length) callback(row); }}); } }, _createFindPrevRow: function(currentRow, callback) { this._hideRowMenu(); if (!currentRow.is(':first-child')) return callback(currentRow.prev('tr')); if (!this.options.useDataSource) return; /* * Go to the previous page */ var self = this; if (!this._isFirstPage()) { this._gotoPage(this._getCurrentPage() - 1, {onComplete: function(){ var row = self.bodyTable.find('tr:last'); if (row.length) callback(row); }}); } }, _createRowInTheEnd: function(callback) { this.rowsAdded = this.rowsAdded === undefined ? 1 : this.rowsAdded+1; if (this._isLastPage() && this.bodyTable.find('tr').length < this.options.pageSize) return callback(this.addRow()); this._gotoPage('last', {data: {'phpr_append_row': 1, 'phpr_new_row_key': -1*this.rowsAdded}, onComplete: function(){ var row = self.bodyTable.find('tr:last'); if (row.length) callback(row); }}); }, _isLastPage: function() { return this.element.find('.grid-is-last-page').val() === '1'; }, _isFirstPage: function() { return this.element.find('.grid-is-first-page').val() === '1'; }, _getCurrentPage: function() { return parseInt(this.element.find('.grid-current-page').val()); }, _getTotalRowCount: function() { return parseInt(this.element.find('.grid-total-record-count').val()); }, /* * Server response handling */ _handleWidgetResponseData: function(data) { if (this.element.parent().length == 0) return; if (data.widget === undefined || data.widget != 'grid') return; if (this.options.name != data.name) return; var self = this; handleError = function() { errorFieldName = self.options.name+'['+data.row+']['+data.column+']', errorField = self.bodyTable.find('input.cell-value[name="'+errorFieldName+'"]'); if (!errorField.length) return; self._markErrorField(errorField); self._scrollToCell(errorField.closest('td')); } var searchEnabled = false; if (this.searchField !== undefined) { if (this.searchField.val().length) { this.searchField.val(''); searchEnabled = true; } } if (this.options.useDataSource && (searchEnabled || (data.page_index !== undefined && this._getCurrentPage() != data.page_index))) { this._gotoPage(data.page_index, {onComplete: function(){ handleError(); }}); } else handleError(); }, _markErrorField: function(field) { if (this._errorRow !== undefined) { this._errorRow.removeClass('grid-error'); this._errorCell.removeClass('grid-error'); } this._errorRow = field.closest('tr'); this._errorCell = field.closest('td'); this._errorRow.addClass('grid-error'); this._errorCell.addClass('grid-error'); if (this.options.scrollable) { var offset = this._errorCell.position().top - this._errorCell.height() + this.scrollablePanel.scrollTop(); if (offset < 0) offset = 0; this.scroller.update_position(offset); } this._errorCell.trigger('navigateTo'); }, /* * Datasource support */ _gotoPage: function(pageIndex, options) { var self = this; if (options === undefined) options = {}; if (options.data === undefined) options.data = {}; this._disableRowMenu(); var searchUpdatedRows = this.searchUpdatedRows !== undefined ? this.searchUpdatedRows : []; if (options.data.phpr_new_row_key !== undefined) searchUpdatedRows.push(options.data.phpr_new_row_key); if (this.rowsAdded === undefined) this.rowsAdded = 1; var searchTerm = this.searchField !== undefined ? this.searchField.val() : null, data = $merge({ 'phpr_custom_event_name': 'on_navigate_to_page', 'phpr_event_field': this.options.dataFieldName, 'phpr_page_index': pageIndex, 'phpr_grid_search': searchTerm, 'phpr_grid_records_added': this.rowsAdded, 'phpr_grid_search_updated_records': searchUpdatedRows.join(',') }, options.data); new Request.Phpr({ url: location.pathname, handler: this.actionName+'onFormWidgetEvent', extraFields: data, update: 'multi', loadIndicator: {show: false}, onBeforePost: LightLoadingIndicator.show.pass('Loading...'), onComplete: LightLoadingIndicator.hide, onAfterUpdate: function() { self.rebuild(); self._dropHeaderCheckboxes(); if (options.onComplete !== undefined) options.onComplete(); self._enableRowMenu(); if (!self._hasRows() && self.searchField !== undefined && self.searchField.val().length) self._showNoSearchResults(); else self._hideNoSearchResults(); self.rowsAdded += self._getTotalRowCount(); var message = self.element.find('.grid-message-text').val(); if (message.length) alert(message); }, onFailure: function(xhr) { alert(xhr.responseText.replace('@AJAX-ERROR@', '').replace(/(<([^>]+)>)/ig,"")); }, }).post(this.element.closest('form')[0]); return false; }, updateData: function(serverEvent) { if (this.searchField !== undefined) this.searchField.val(''); this.searchUpdatedRows = []; this._gotoPage(0, {data: {'phpr_grid_event': serverEvent}}); }, /* * Search support */ _updateSearch: function() { this.searchUpdatedRows = []; this._gotoPage(0); }, _markRowSearchUpdated: function(recordIndex) { if (this.searchUpdatedRows == undefined) this.searchUpdatedRows = []; this.searchUpdatedRows.push(recordIndex); }, _showNoSearchResults: function() { this.noSearchResultsVisible = true; if (this.noSearchResultsMessage === undefined) { this.noSearchResultsMessage = jQuery('<p class="ui-no-records noData"></p>').text('No records found'); this.container.append(this.noSearchResultsMessage); this.noSearchResultsMessage.css('top', Math.round(this.container.height()/2-19)); this.noSearchResultsMessage.css('left', Math.round(this.container.width()/2-100)); } this.noSearchResultsMessage.css('display', 'block'); this.existingTable.css('display', 'none'); }, _hideNoSearchResults: function() { this.noSearchResultsVisible = false; if (this.noSearchResultsMessage === undefined) return; this.noSearchResultsMessage.css('display', 'none'); this.existingTable.css('display', 'table'); }, _isNoSearchResults: function() { return this.noSearchResultsVisible; }, /* * Header checkboxes support */ _initHeaderCheckboxes: function() { var self = this; this.headTable.find('th.checkbox-cell input').each(function(index, input) { input.addEvent('click', function() { var headCell = jQuery(input).closest('th'); var cellIndex = headCell.parent().children('th').index(headCell); var columnInfo = self.options.columns[cellIndex]; self.bodyTable.find('tr').find('td:eq('+cellIndex+')').each(function(rowIndex, cell){ if (input.checked) jQuery(cell).find('div.checkbox').addClass('checked'); else jQuery(cell).find('div.checkbox').removeClass('checked'); jQuery(cell).find('.cell-value').val(input.checked ? 1 : 0); if (columnInfo.checked_class !== undefined) { var row = jQuery(cell).parent(); if (input.checked) row.addClass(columnInfo.checked_class); else row.removeClass(columnInfo.checked_class); } }); }) }) }, _dropHeaderCheckboxes: function() { this.headTable.find('th.checkbox-cell input').each(function(index, input) { input.cb_uncheck(); }); }, /* * Tracing */ _trace: function(message) { if (window.console) console.log(message); return; } }); })( jQuery );
JavaScript
/** * This script contains grid control column editor classes. */ (function( $, undefined ) { jQuery.ui.grid = {editors: {}}; jQuery.ui.grid.editors.editorBase = jQuery.Class.create({ initialize: function() { }, /** * Initializes the cell content during the table building procedure. * @param object cell Specifies a DOM td element corresponding to the cell. * @param mixed cellContent Specifies the text content - either a string, * or an object with "display" and "value" fields. * @param array row Current table row. * @param integer cellIndex Current cell index. * @param integer rowDataIndex Current cell data element index. * @param mixed columnInfo Column confiruation object. * The method should set the cell inner content, */ initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { if (cell.find('.cell-content-container').length == 0) cell.append(jQuery('<div/>').addClass('cell-content-container').attr('tabindex', 0)); this.createCellValueElement(cell, cellIndex, rowDataIndex); this.renderContent(cell, cellContent, row, cellIndex); }, /** * Creates a hiden input element for holding the cell value. * @param object cell Specifies a DOM td element corresponding to the cell. * @param integer cellIndex Specifies a cell index. * @param integer rowDataIndex Specifies a row data index. */ createCellValueElement: function(cell, cellIndex, rowDataIndex) { var grid = cell.data('ui.grid'), contentContainer = cell.find('.cell-content-container'); contentContainer.append(jQuery('<input type="hidden" class="cell-value"></input>').attr( 'name', grid.options.name+'['+rowDataIndex+']['+grid.options.columns[cellIndex].field+']' )); contentContainer.append(jQuery('<input type="hidden" class="internal-value"></input>').attr( 'name', grid.options.name+'['+rowDataIndex+']['+grid.options.columns[cellIndex].field+'_internal]' )); }, /** * Renders cell content in read-only mode. * @param object cell Specifies a DOM td element corresponding to the cell. * @param mixed cellContent Specifies the text content - either a string, * or an object with "display" and "value" fields. * @param array row Current table row. * @param integer cellIndex Current cell index. * The method should set the cell inner content, */ renderContent: function(cell, cellContent, row, cellIndex) { if (jQuery.type(cellContent) !== 'object') { this.setCellValue(cell, cellContent); this.setCellDisplayText(cell, cellContent); } else { this.setCellValue(cell, cellContent.value); this.setCellInternalValue(cell, cellContent.internal); this.setCellDisplayText(cell, cellContent.display); } }, /** * Sets cell hidden value. * @param object cell Specifies the cell DOM td element. * @param string value Specifies the value to set. */ setCellValue: function(cell, value) { cell.find('input.cell-value').attr('value', value); this.markCellRowSearchUpdated(cell); }, /** * Sets cell internal hidden value. * @param object cell Specifies the cell DOM td element. * @param string value Specifies the value to set. */ setCellInternalValue: function(cell, value) { cell.find('input.internal-value').attr('value', value); this.markCellRowSearchUpdated(cell); }, /** * Sets cell display value. * @param object cell Specifies the cell DOM td element. * @param string text Specifies the text to set. */ setCellDisplayText: function(cell, text) { var span = cell.find('span.cell-content'); if (span.length == 0) { var contentContainer = cell.find('.cell-content-container'); span = jQuery('<span class="cell-content"></span>').text(text); contentContainer.append(span); } else span.text(text); }, /** * Returns cell display value. * @param object cell Specifies the cell DOM td element. * @return string Cell display value. */ getCellDisplayText: function(cell) { return cell.find('span.cell-content').text(); }, /** * Returns cell hidden value. * @param object cell Specifies the cell DOM td element. * @return string Cell hidden value. */ getCellValue: function(cell) { return cell.find('input.cell-value').attr('value'); }, /** * Hides cell display value. * @param object cell Specifies the cell DOM td element. */ hideCellDisplayText: function(cell) { return cell.find('span.cell-content').hide(); }, /** * Shows cell display value. * @param object cell Specifies the cell DOM td element. */ showCellDisplayText: function(cell) { return cell.find('span.cell-content').show(); }, /** * Displays the cell editor, if applicable. * @param object cell Specifies the cell DOM td element. */ displayEditor: function(cell) { this.getGrid(cell)._setCurrentRow(cell.closest('tr')); }, /** * Hides the cell editor, if applicable. * @param object cell Specifies the cell DOM td element. * @param object editor Specifies the editor DOM element, if applicable. */ hideEditor: function(cell, editor) { }, /** * Sets or returns the editor visibility state. * @param object cell Specifies the cell DOM td element. * @param boolean value Optional visibility state value. * If omitted, the function will return the current visibility state. * @return boolean */ editorVisible: function(cell, value) { if (value === undefined) return cell.data('ui.grid.editor_visible') ? true : false; cell.data('ui.grid.editor_visible', value); return value; }, /** * Returns parent grid object. * @param object cell Specifies the cell DOM td element. */ getGrid: function(cell) { return cell.data('ui.grid'); }, /** * Binds standard content container keys. * @param object contentContainer Specifies the content containier jQuery object. * @param boolean allAsClick Indicates whether any key (but arrows, tab and return) should trigger the click event. * @param boolean returnAsClick Indicates whether Return key should trigger the click event. */ bindContentContainerKeys: function(contentContainer, allAsClick, returnAsClick) { var self = this, cell = contentContainer.parent(); contentContainer.bind('keydown', function(ev){ if (self.editorVisible(cell)) return; switch (ev.keyCode) { case 32 : ev.preventDefault(); cell.trigger('click'); break; case 38 : ev.preventDefault(); self.getGrid(cell)._navigateUp(cell); break; case 40 : ev.preventDefault(); self.getGrid(cell)._navigateDown(cell); break; case 39 : case 37 : ev.preventDefault(); if (ev.keyCode == 39) self.getGrid(cell)._navigateRight(cell); else self.getGrid(cell)._navigateLeft(cell); break; case 13 : if (returnAsClick === undefined || returnAsClick === false) return; ev.preventDefault(); cell.trigger('click'); break; case 9 : break; default : if (!ev.shiftKey && !ev.ctrlKey && !ev.altKey && !ev.metaKey) { ev.preventDefault(); cell.trigger('click'); } else self.getGrid(cell)._handleGridKeys(ev); break; } }); }, markCellRowSearchUpdated: function(cell) { var grid = this.getGrid(cell), row = cell.closest('tr'); if (row.length && grid) grid._markRowSearchUpdated(row[0].rowDataIndex); } }); /* * Popup editor */ jQuery.ui.grid.editors.popupEditor = jQuery.Class.create(jQuery.ui.grid.editors.editorBase, { initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { var self = this; this.base('initContent', cell, cellContent, row, cellIndex, columnInfo, rowDataIndex); cell.addClass('ui-grid-cell-clickable'); this.bindPopupTrigger(cell, columnInfo, rowDataIndex); }, bindPopupTrigger: function(cell, columnInfo, rowDataIndex) { var self = this; cell.addClass('ui-grid-cell-focusable'); cell.addClass('ui-grid-cell-navigatable'); this.contentContainer = cell.find('.cell-content-container'); this.bindContentContainerKeys(this.contentContainer, false, true); this.contentContainer.bind('focus', function(ev){ self.getGrid(cell)._setCurrentRow(cell.closest('tr')); }); cell.bind('navigateTo', function(event, direction, selectAll){ self.contentContainer.focus(); }); cell.bind('click', function(){ var grid = self.getGrid(cell); grid._scrollToCell(cell); self.buildPopup(cell, columnInfo, rowDataIndex, self); return false; }) }, getZIndex: function(element) { var zElement = element.parents().filter(function(){ var css = jQuery(this).css('z-index'); return css !== undefined && css != 'auto'; }); return parseInt(zElement.css('z-index')); }, buildPopup: function(cell, columnInfo, rowDataIndex, editor) { var zIndex = this.getZIndex(cell), grid = this.getGrid(cell); self = this; /* * Build the overlay */ var overlay = jQuery('<div class="ui-grid-overlay ui-overlay"/>'); if (zIndex) overlay.css('z-index', zIndex+1); jQuery(grid.element).append(overlay); jQuery.ui.grid.popupOverlay = overlay; /* * Build the popup window */ var tmp = jQuery('<div/>').css('display', 'none'); jQuery(grid.element).append(tmp); grid._hideRowMenu(); cell.find('.cell-content-container').blur(); new Request.Phpr({ url: location.pathname, handler: grid.actionName+'onFormWidgetEvent', extraFields: { 'phpr_custom_event_name': 'on_show_popup_editor', 'phpr_event_field': grid.options.dataFieldName, 'phpr_popup_column': columnInfo.field, 'phpr_grid_row_index': rowDataIndex }, update: tmp[0], loadIndicator: {show: false}, onSuccess: function() { editor.displayPopup(tmp, zIndex, cell, grid); }, onFailure: function(xhr) { alert(xhr.responseText.replace('@AJAX-ERROR@', '').replace(/(<([^>]+)>)/ig,"")); tmp.remove(); overlay.remove(); jQuery.ui.grid.popupOverlay = undefined; }, }).post(cell.closest('form')[0]); }, displayPopup: function(dataContainer, zIndex, cell, grid) { var container = jQuery('<div class="ui-popup-container"/>').css({ 'z-index': zIndex+2, 'visibility': 'hidden' }), handle = jQuery('<div class="ui-popup-handle"/>'), content = jQuery('<div class="ui-popup-content-container"/>'), containerOffset = jQuery(grid.element).offset(), cellOffset = cell.offset(), docHeight = jQuery(document).height(), docWidth = jQuery(document).width(), cellHeightOffset = docHeight - cellOffset.top, cellWidthOffset = docWidth - cellOffset.left, popupContent = dataContainer.children().first(); jQuery.ui.grid.popupContainer = container; jQuery.ui.grid.popupCell = cell; content.append(popupContent); container.append(content); container.append(handle); dataContainer.remove(); jQuery(grid.element).append(container); var containerHeight = container.outerHeight(), containerWidth = container.outerWidth(), showBelow = cellHeightOffset > (containerHeight+40), showRight = cellWidthOffset > (containerWidth+50); if ((cellOffset.top - cell.height() + 15 - containerHeight) < 0) showBelow = true; var contentTop = showBelow ? (cellOffset.top - containerOffset.top + cell.height() + 5 + 'px') : (cellOffset.top - containerOffset.top - cell.height() + 15 - containerHeight + 'px'); var contentLeft = showRight ? (cellOffset.left - containerOffset.left + container.width() + 40 - containerWidth + 'px') : (cellOffset.left - containerOffset.left - container.width() + 40 + 'px'); container.css({ top: contentTop, left: contentLeft, visibility: 'visible' }); if (!showBelow) container.addClass('above'); if (showRight) container.addClass('right'); cell.addClass('popup-focused'); popupContent[0].fireEvent('popupLoaded'); window.fireEvent('popupLoaded', popupContent[0]); popupContent.data('ui.gridEditor', this); popupContent.data('ui.gridCell', cell); grid._hideEditors(); grid._disableRowAdding(); jQuery(document).bind('keydown.gridpopup', function(ev){ if (ev.keyCode == 27) popupContent[0].fireEvent('onEscape'); }); } }); /* * Single-line text editor. This editor has optional autocomplete parameter, which could be set in the column configuration object. * The parameter value could be either "predefined" or "remote". If the predefined option is specified, the column configuration * object should also have the "options" array with a list of available values. */ jQuery.ui.grid.editors.textEditor = jQuery.Class.create(jQuery.ui.grid.editors.popupEditor, { initialize: function() { this.base('initialize'); }, initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { var self = this; this.base('initContent', cell, cellContent, row, cellIndex, columnInfo, rowDataIndex); cell.addClass('ui-grid-cell-navigatable'); cell.addClass('ui-grid-cell-editable'); cell.find('.cell-content-container').bind('focus.grid', function(event){ self.displayEditor(cell, null, false, columnInfo); }) cell.bind('click.grid navigateTo', function(event, direction, selectAll){ selectAll = selectAll === undefined ? false : selectAll; self.displayEditor(cell, direction, selectAll, columnInfo); }); if (columnInfo.editor_class !== undefined) { cell.data('grid.rowDataIndex', rowDataIndex); } }, bindPopupTrigger: function(cell, columnInfo, rowDataIndex) {}, displayEditor: function(cell, navigationDirection, selectAll, columnInfo) { if (this.editorVisible(cell) || this.getGrid(cell).dragStarted) return; this.editorVisible(cell, true); var grid = this.getGrid(cell); grid._scrollToCell(cell); var self = this, editor = jQuery('<input type="text" class="cell-editor"/>') .attr('value', this.getCellValue(cell)) .css('height', cell.height()+'px'), editorContainer = jQuery('<div class="cell-editor-container"/>'), autocomplete = columnInfo.autocomplete !== undefined ? columnInfo.autocomplete : false; grid._disableRowMenu(cell); editorContainer.append(editor); editor.data('gridContainer', editorContainer); /* * Setup autocompletion */ if (autocomplete !== false) { var options = { appendTo: grid.element, position: { my: "left top", at: "left bottom", collision: "none", of: cell }, open: function(){ grid._pauseScrolling(); var autocompleteObj = grid.element.find('.ui-autocomplete'), widthFix = 1, fixLeft = false; if (cell.is(':first-child')) { widthFix++; fixLeft = true; } var autocompleteWidth = cell.outerWidth()+widthFix; if (autocompleteWidth < 200) autocompleteWidth = 200; autocompleteObj.outerWidth(autocompleteWidth); if (fixLeft > 0) autocompleteObj.css('margin-left', '-1px'); }, close: function(){ grid._resumeScrolling(); }, minLength: (columnInfo.minLength === undefined ? 1 : columnInfo.minLength) }; if (autocomplete == 'predefined') options.source = columnInfo.options; else if (autocomplete == 'remote') { var row = cell.closest('tr'), form = cell.closest('form'), action = form.attr('action'); options.source = function(request, response) { self.autocomplete(request, response, columnInfo, cell, row, action, form, grid); } } editor.autocomplete(options); } /* * Setup editor events */ this.hideCellDisplayText(cell); editor.bind('blur', function(){ window.setTimeout(function(){ self.hideEditor(cell, editor); }, 200) }); grid.element.bind('hideEditors', function(){ self.hideEditor(cell, editor); }) editor.keyup(function(ev){ self.setCellValue(cell, editor.val()); }); editor.bind('keydown', function(ev){ switch (ev.keyCode) { case 38 : if (autocomplete === false) grid._navigateUp(cell); break; case 40 : if (autocomplete === false) grid._navigateDown(cell); break; case 39 : case 37 : var sel = jQuery(editor).caret(); if (sel.end === undefined) sel.end = 0; if (ev.keyCode == 39) { if (sel.end == editor.attr('value').length) { ev.preventDefault(); grid._navigateRight(cell); } } else { if (sel.start === undefined) { ev.preventDefault(); grid._navigateLeft(cell); } } break; case 9 : if (!ev.shiftKey) { if (grid._navigateRight(cell, true)) ev.preventDefault(); } else { if (grid._navigateLeft(cell, true)) ev.preventDefault(); } break; case 27 : self.hideEditor(cell, editor); break; case 73 : if (ev.metaKey || ev.ctrlKey) grid.appendRow(cell, ev); break; } }); /* * Create button for the popup editor */ if (columnInfo.editor_class !== undefined) { var button = jQuery('<a href="#" class="ui-grid-cell-button"></a>'), knob = jQuery('<span></span>'), heightTweak = -1, row = cell.parent(); if (row.is(':last-child') && grid.bodyTable.hasClass('no-bottom-border')) heightTweak = 0; button.css({ 'height': cell.outerHeight() + heightTweak + 'px', }) .append(knob); button.click(function(){ self.hideEditor(cell, editor); self.buildPopup(cell, columnInfo, cell.data('grid.rowDataIndex'), self); return false; }); editorContainer.append(button); cell.addClass('popup-button-container'); editor.bind('keydown', function(ev){ if (ev.keyCode == 13 && !ev.ctrlKey) { button.trigger('click'); editorContainer.blur(); ev.preventDefault(); return false; } }); } /* * Append the editor, and focus it */ cell.append(editorContainer); editor.focus(); /* * Set the caret position and display the eidtor */ if (!selectAll) { if (navigationDirection !== undefined && navigationDirection === 'left') { var len = editor.attr('value').length; editor.caret(len, len); } else editor.caret(0, 0); } else { var len = editor.attr('value').length; editor.caret(0, len); } this.base('displayEditor', cell); }, hideEditor: function(cell, editor) { this.editorVisible(cell, false); var self = this, grid = self.getGrid(cell); this.setCellDisplayText(cell, editor.attr('value')); this.setCellValue(cell, editor.attr('value')); if (editor.data('gridContainer')) editor.data('gridContainer').remove(); else editor.remove(); this.showCellDisplayText(cell); if (grid) grid._enableRowMenu(cell); }, autocomplete: function (request, response, columnInfo, cell, row, url, form, grid) { var formData = form.serialize(), rowData = {}, custom_values = columnInfo.autocomplete_custom_values === undefined ? false : true; row.find('input.cell-value').each(function(index, input){ var $input = jQuery(input), match = /[^\]]+\[[^\]]+\]\[\-?[0-9]+\]\[([^\]]+)\]/.exec($input.attr('name')); if (match !== null) { var field_name = 'autocomplete_row_data['+match[1]+']', field_value = $input.attr('value'); rowData[field_name] = field_value; } }); formData += '&'+ jQuery.param(rowData)+ '&autocomplete_term='+encodeURIComponent(request.term)+ '&autocomplete_column='+columnInfo.field+ '&autocomplete_custom_values='+custom_values+ '&phpr_custom_event_name=on_autocomplete'+ '&phpr_event_field='+ grid.options.dataFieldName+ '&phpr_no_cookie_update=1'; var lastXhr = jQuery.ajax({ 'type': 'POST', 'url': url, 'data': formData, success: function( data, status, xhr ) { if ( xhr === lastXhr ) { response(data); } }, dataType: 'json', headers: { 'PHPR-REMOTE-EVENT': 1, 'PHPR-POSTBACK': 1, 'PHPR-EVENT-HANDLER': 'ev{'+grid.actionName+'onFormWidgetEvent}', 'PHPR-CUSTOM-EVENT-NAME': 'on_autocomplete', 'PHPR-EVENT-FIELD': grid.options.dataFieldName } }); } }); /* * Drop-down cell editor. This editor requires the option_keys and option_values properties * to be set in the column configuration object: {option_keys: [0, 1], option_values: ['Option 1', 'Option 2']} * Other supported options: allowDeselect (boolean), default_text: string */ jQuery.ui.grid.editors.dropdownEditor = jQuery.Class.create(jQuery.ui.grid.editors.editorBase, { initialize: function() { this.base('initialize'); }, initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { var self = this; this.ignoreFocus = false; this.base('initContent', cell, cellContent, row, cellIndex, columnInfo, rowDataIndex); cell.addClass('ui-grid-cell-navigatable'); cell.addClass('ui-grid-cell-editable'); cell.addClass('ui-grid-cell-focusable'); this.contentContainer = cell.find('.cell-content-container'); this.bindContentContainerKeys(this.contentContainer, true, false); this.contentContainer.bind('focus', function(ev){ if (ev.originalEvent !== undefined) self.displayEditor(cell, null, columnInfo); else self.getGrid(cell)._setCurrentRow(cell.closest('tr')); }); cell.bind('click.grid', function(event, direction, selectAll){ self.displayEditor(cell, direction, columnInfo); }); cell.bind('navigateTo', function(event, direction, selectAll){ self.contentContainer.focus(); }); }, displayEditor: function(cell, navigationDirection, columnInfo) { if (this.editorVisible(cell) || this.getGrid(cell).dragStarted) return; var grid = this.getGrid(cell); grid._scrollToCell(cell); var self = this, gridOffset = grid.element.offset(), cellOffset = cell.offset(), offsetLeft = cellOffset.left-gridOffset.left-2, offsetTop = cellOffset.top-gridOffset.top-3; if (!cell.is(':first-child')) offsetLeft++; if (!grid.options.scrollable) offsetLeft++; grid._hideEditors(); this.editorVisible(cell, true); this.hideCellDisplayText(cell); var select = jQuery('<select>'), selectContainer = jQuery('<div class="ui-grid-select-container">'); selectContainer.css({ 'left': offsetLeft+'px', 'top': offsetTop+'px', 'width': (cell.width()+2)+'px', 'height': (cell.height()+2)+'px' }); if (columnInfo.default_text !== undefined) select.attr('data-placeholder', columnInfo.default_text); if (columnInfo.allow_deselect !== undefined || columnInfo.default_text !== undefined) select.append(jQuery('<option>').attr('value', '').text('')); var valueFound = false, currentValue = this.getCellValue(cell); jQuery.each(columnInfo.option_keys, function(index, value){ select.append(jQuery('<option></option>').attr('value', value).text(columnInfo.option_values[index])); if (currentValue == value) valueFound = true; }); if (!valueFound) select.append(jQuery('<option></option>').attr('value', currentValue).text(currentValue)); select.val(currentValue); selectContainer.append(select); grid.element.append(selectContainer); select.bind('change', function(){ self.setCellDisplayText(cell, select.find('option:selected').text()); self.setCellValue(cell, select.val()); self.hideEditor(cell, select); self.ignoreFocus = true; self.contentContainer.focus(); self.ignoreFocus = false; }) cell.css('overflow', 'visible'); var options = {allow_single_deselect: false}; if (columnInfo.allowDeselect !== undefined) options.allow_single_deselect = columnInfo.allowDeselect; jQuery(select).chosen(options); grid._disableRowMenu(cell); grid._pauseScrolling(); var container = selectContainer.find('.chzn-container'); container.css('height', (cell.height()+2)+'px'); container.bind('keydown', function(ev){ switch (ev.keyCode) { case 9 : self.hideEditor(cell, select); if (!ev.shiftKey) { if (self.getGrid(cell)._navigateRight(cell, true)) ev.preventDefault(); } else { if (self.getGrid(cell)._navigateLeft(cell, true)) ev.preventDefault(); } break; case 27 : self.hideEditor(cell, select); ev.preventDefault(); self.ignoreFocus = true; self.contentContainer.focus(); self.ignoreFocus = false; break; } }); window.setTimeout(function(){ jQuery(document).bind('mousedown.gridDropdown', function(e) { self.hideEditor(cell, select); }); }, 300); this.base('displayEditor', cell); this.getGrid(cell).element.bind('hideEditors', function(){ self.hideEditor(cell, select); }); window.setTimeout(function(){ container.trigger('mousedown'); }, 60); }, hideEditor: function(cell, editor) { var grid = this.getGrid(cell); if (grid === undefined) return; grid._enableRowMenu(cell); grid._resumeScrolling(); jQuery(document).unbind('.gridDropdown'); editor.parent().remove(); this.editorVisible(cell, false); cell.find('.chzn-container').remove(); cell.css('overflow', ''); var self = this; this.showCellDisplayText(cell); } }); /* * Checkbox cell editor */ jQuery.ui.grid.editors.checkboxEditor = jQuery.Class.create(jQuery.ui.grid.editors.editorBase, { initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { var self = this; this.base('initContent', cell, cellContent, row, cellIndex, columnInfo, rowDataIndex); cell.addClass('cell-checkbox'); cell.addClass('ui-grid-cell-navigatable'); this.hideCellDisplayText(cell); var editor = jQuery('<div class="checkbox"/>') .attr('tabindex', 0) .bind('click', function(){ var curValue = self.getCellValue(cell); if (curValue == 1) { self.setCellValue(cell, 0); jQuery(this).removeClass('checked'); self.getGrid(cell)._dropHeaderCheckboxes(); if (columnInfo.checked_class !== undefined) row.removeClass(columnInfo.checked_class); } else { self.setCellValue(cell, 1); jQuery(this).addClass('checked'); if (columnInfo.checked_class !== undefined) row.addClass(columnInfo.checked_class); } }) .bind('focus', function(ev){ self.getGrid(cell)._setCurrentRow(cell.closest('tr')); }) .bind('keydown', function(ev){ switch (ev.keyCode) { case 32 : case 13 : editor.trigger('click'); break; case 38 : self.getGrid(cell)._navigateUp(cell); break; case 40 : self.getGrid(cell)._navigateDown(cell); break; case 39 : case 37 : ev.preventDefault(); if (ev.keyCode == 39) self.getGrid(cell)._navigateRight(cell); else self.getGrid(cell)._navigateLeft(cell); break; case 9 : if (!ev.shiftKey) { if (self.getGrid(cell)._navigateRight(cell, true)) ev.preventDefault(); } else { if (self.getGrid(cell)._navigateLeft(cell, true)) ev.preventDefault(); } break; default: self.getGrid(cell)._handleGridKeys(ev); break; } }); if (this.getCellValue(cell) == 1) editor.addClass('checked'); var contentContainer = cell.find('.cell-content-container'); contentContainer.append(editor); cell.bind('click navigateTo', function(ev, direction, selectAll){ editor.focus(); }); } }); jQuery.ui.grid.hidePopup = function() { if (!jQuery.ui.grid.popupContainer !== undefined && jQuery.ui.grid.popupOverlay !== undefined) { hide_tooltips(); jQuery.ui.grid.popupContainer.remove(); jQuery.ui.grid.popupOverlay.remove(); jQuery.ui.grid.popupCell.removeClass('popup-focused'); jQuery.ui.grid.popupCell.data('ui.grid')._enableRowAdding(); if (jQuery.ui.grid.popupCell.hasClass('ui-grid-cell-focusable')) jQuery.ui.grid.popupCell.find('.cell-content-container').focus(); jQuery(document).unbind('keydown.gridpopup'); } } })( jQuery );
JavaScript
/** * This script contains the grid control. * The plugin should be applied to a DIV element. * Grid table will be built inside this element. * The options object should be specified in the followingi format: * { * columns: [ * {title: 'Id', field: 'id', type: 'text', width: '170'}, * {title: 'Name', field: 'name', type: 'text', width: '170'} * ], * data: [ * [1, "First row"] * [2, {display: "Second row", value: any_custom_data}] * ], * scrollable: true, * allowAutoRowAdding: false, * sortable: true, * scrollable: true, * name: 'myGrid' // This value will be use in hidden input names. * } * The "type" property of column specifies a column editor to be used for the column. * The "data" property is not required. However if the data is not provided, the DOM element * the plugin is applied to should contain a table markup with THEAD and TBODY elements. Head columns * should match the data provided in the "columns" property. If the table already exists, the "data" * element is ignored. Cells can contain a hidden input element with the "cell-value" class. * See jquery.backend.grid.editors.js for the list of supported editors. * The editor class name is calculated as the column type name + "Editor", so that * "text" is converted to "textEditor". */ (function( $, undefined ) { jQuery.widget( "ui.grid", { options: { allowAutoRowAdding: true, name: 'grid', dataFieldName: null, sortable: false, scrollable: false, scrollableViewportClass: null, rowsDeletable: false, deleteRowMessage: 'Do you really want to delete this row?', useDataSource: false, focusFirst: false }, /** * Updates table column widths. */ alignColumns: function(row) { if (this.options.useDataSource) return; var widths = [], self = this; this.headTable.find('th div.ui-grid-head-content').each(function(index, div){ widths.push(jQuery(div).outerWidth()); }); if (row === undefined) { this.bodyTable.find('tr:first-child').each(function(rowIndex, row) { $(row).find('td').each(function(index, td) { if (index < (widths.length-1)) { var tweak = 0, $td = jQuery(td); if (Browser.Engine.webkit && !self.isChrome && index > 0) tweak = 1; $td.css('width', (widths[index] + tweak) + 'px'); $td.find('span.cell-content').css('width', (widths[index] + tweak - 18) + 'px'); } }); }) } else { row.find('td').each(function(index, td) { if (index < (widths.length-1)) { var tweak = 0; if (Browser.Engine.webkit && index > 0) tweak = 1; jQuery(td).css('width', (widths[index] + tweak) + 'px'); } }) } }, /** * Adds new row to the table. * @param array data Optional data array. If the second parameter is required, pass false to this parameter. * @param string position Specifies the new row position. * Possible values: 'top', 'bottom', 'above', 'below'. 'bottom' is the default value. */ addRow: function(data, position) { if (!this.options.allowAutoRowAdding) return null; if (this._isNoSearchResults()) return false; var position = position === undefined ? 'bottom' : position; if (data == undefined || data === false) { data = []; for (var index=0; index<this.options.columns.length; index++) data.push(''); } var row = this._buildRow(data, position), offset = 'bottom'; if (position == 'top') offset = 'top'; else if (position == 'above' || position == 'below') { if (this.currentRow === undefined || !this.currentRow[0].parentNode) offset = 'bottom'; else offset = 'relative'; } this.alignColumns(row); if (!this.options.useDataSource) this._updateScroller(offset); this._fixBottomBorder(); this._assignRowEventHandlers(row); this._setCurrentRow(jQuery(row)); if (this.options.useDataSource) { var recordCount = parseInt(this.element.find('.pagination .row_count').text()); if (recordCount != NaN) this.element.find('.pagination .row_count').text(recordCount+1); } return row; }, /** * Deletes a current row */ deleteRow: function() { var self = this; if (!this.currentRow) return false; var currentPage = 0, row = this.currentRow; if (self.options.useDataSource) currentPage = self._getCurrentPage(); var cell = this.currentRow.find('td:first'), rowIndex = this.bodyTable.children('tr').index(this.currentRow), cellIndex = this.currentRow.children('td').index(cell); if (cell.length && !this.options.useDataSource) this._navigateUp(cell); self._deleteRow(row, true, function(){ if (self.options.useDataSource) { if (cell) { var row = (currentPage == self._getCurrentPage()) ? self.bodyTable.find('tr:eq('+rowIndex+')') : self.bodyTable.find('tr:last'); if (!row.length) row = self.bodyTable.find('tr:last'); if (row.length) { self._initRow(row) row.find('td:eq('+cellIndex+')').trigger('navigateTo'); } } } }); }, appendRow: function(currentCell, ev) { var self = this; if (!this.options.useDataSource) return false; if (self.disableRowAdding !== undefined && self.disableRowAdding) return false; this._hideEditors(); var cell = currentCell !== undefined ? currentCell : ((ev !== undefined && ev.target !== undefined) ? jQuery(ev.target).closest('table.ui-grid-body tr td') : null); var index = (cell && cell !== null && cell.length) ? cell.parent().children('td').index(cell) : 0; self._createRowInTheEnd(function(nextRow){ if (!nextRow.length) return; self._initRow(nextRow); if (index !== null) nextRow.find('td:eq('+index+')').trigger('navigateTo', ['left']); }); return true; }, rebuild: function() { this._build(); }, focusFirst: function() { if (this._hasRows()) { var firstRow = this.bodyTable.find('tr:first'); this._initRow(firstRow); window.setTimeout(function(){ firstRow.find('td.ui-grid-cell-navigatable:first').trigger('navigateTo'); }, 100); } }, _create: function() { jQuery(this.element).data('ui.grid', this); this.isChrome = jQuery('body').hasClass('chrome'); this._build(); this.dragStarted = false; var self = this; jQuery(window).bind('phpr_widget_response_data', function(event, data){ self._handleWidgetResponseData(data); }); }, _build: function() { if (this.options.columns === undefined) { this._trace('Data grid has no columns. Exiting.'); return; } if (this.element.find('input.grid-table-disabled').length) { if (this.headTable !== undefined && this.headTable && !this.options.useDataSource) this.headTable.remove(); return; } this.element.addClass('ui-grid'); this.existingTable = this.element.find('table'); this.actionName = this.element.find('input.grid-event-handler-name').attr('value'); if (this.options.useDataSource) this.container = this.element.find('.ui-grid-table-container'); this._buildHead(); this._buildBody(); if (this.options.useDataSource && this.built === undefined) { var columnGroupsTitleHeight = this.headTable.find('.ui-column-group-row').height(); if (columnGroupsTitleHeight > 0) columnGroupsTitleHeight += 1; this.container.css('height', (this.bodyTable.find('tr:first').height()*(this.options.pageSize+1)+2)+columnGroupsTitleHeight+'px'); var scroller = this.element.find('.ui-grid-h-scroll'); scroller.scrollLeft(0); this._bindSearch(); } if (!this.options.useDataSource) { this.alignColumns(); var self = this; window.setTimeout(function(){ self._updateScroller(); }, 200); jQuery(window).bind('resize', function(){ self.alignColumns(); }); } if (this.built === undefined && this.options.focusFirst) this.focusFirst(); this.built = true; }, _updateScroller: function(direction){ if (this.options.scrollable) this.scroller.update(direction); }, _buildHead: function() { if (!this.options.useDataSource) { this.headTable = jQuery('<table class="ui-grid-head"></table>'); var row = jQuery('<tr></tr>') this.headTable.append(jQuery('<thead></thead>').append(row)); jQuery.each(this.options.columns, function(index, columnData){ var cell = jQuery('<th></th>'), content = jQuery('<div class="ui-grid-head-content"></div>'); cell.append(content); content.text(columnData.title); if (columnData.width !== undefined) cell.css('width', columnData.width + 'px'); if (columnData.align !== undefined) cell.addClass(columnData.align); row.append(cell); }); this.element.find('table').find('thead').remove(); this.element.prepend(this.headTable); } else this.headTable = this.element.find('table').find('thead'); if (this.built === undefined) this._initHeaderCheckboxes(); }, _buildBody: function() { var self = this; this.bodyTable = this.existingTable.length ? this.existingTable.find('tbody') : jQuery('<table class="ui-grid-body"></table>'); if (!this.existingTable.length) { jQuery.each(this.options.data, function(rowIndex, rowData) { self._buildRow(rowData); }); } else { this.bodyTable.addClass('ui-grid-body'); if (!this.options.useDataSource || this.built === undefined) this.bodyTable.bind('mouseover', function(ev){ if (ev.target !== undefined) self._initRow(jQuery(ev.target).closest('tr')); }); } if (this.options.scrollable) { this.scrollablePanel = this.element.find('div.backend_scroller'); this.scroller = new BackendVScroller(this.scrollablePanel[0], { slider_height_tweak: 0, auto_hide_slider: true, position_threshold: 9 }); this.viewport = this.scrollablePanel; this.overview = this.bodyTable; this.scrollablePanel.bind('onScroll', function(){ self._hideRowMenu(); self._hideEditors(); }); this.scrollablePanel.bind('onBeforeWheel', function(event){ if (self._scrollingPaused !== undefined && self._scrollingPaused) event.preventDefault(); }); } else this.headTable.after(this.bodyTable); if ((!this.options.useDataSource || this.built === undefined) && !this._hasRows()) this.addRow(); this._assignRowEventHandlers(); if (this.options.sortable) { this.dragging = false; this.bodyTable.addClass('ui-grid-draggable'); jQuery(document).bind('mousemove', function(event){self._mouseMove(event);}); jQuery(document).bind('mouseup', function(event){self._mouseUp(event);}); } if (this.built === undefined) { this.bodyTable.bind('mouseleave', function(event){ self._hideRowMenu(event); }) this._assignBodyEventHandlers(); this._assignDocumentHandlers(); } this._fixBottomBorder(); }, _buildRow: function(rowData, position) { var row = jQuery('<tr></tr>'), self = this, position = position === undefined ? 'bottom' : position; this.rowsAdded = this.rowsAdded === undefined ? 1 : this.rowsAdded+1; jQuery.each(rowData, function(cellIndex, cellData){ var cell = jQuery('<td></td>').data('ui.grid', self); self._getColumnEditor(cellIndex).initContent(cell, cellData, row, cellIndex, self.options.columns[cellIndex], -1*self.rowsAdded); row[0].rowDataIndex = -1*self.rowsAdded; if (self.options.columns[cellIndex].align !== undefined) cell.addClass(self.options.columns[cellIndex].align); if (self.options.columns[cellIndex].cell_css_class !== undefined) cell.addClass(self.options.columns[cellIndex].cell_css_class); if (self.options.rowsDeletable && rowData.length == cellIndex+1) self._createRowMenu(row, cell, self); if (self.options.columns[cellIndex].default_text !== undefined) cell.find('span.cell-content').text(self.options.columns[cellIndex].default_text); row.append(cell); }); row[0].grid_initialized = true; if (position == 'bottom') self.bodyTable.append(row); else if (position == 'top') self.bodyTable.prepend(row); else if (position == 'above' || position == 'below') { if (self.currentRow === undefined || !self.currentRow[0].parentNode) self.bodyTable.append(row); else { if (position == 'above') row.insertBefore(self.currentRow); else row.insertAfter(self.currentRow); } } this._markRowSearchUpdated(-1*self.rowsAdded); return row; }, _fixBottomBorder: function() { if (this.options.scrollable) { if (this.viewport.height() > this.overview[0].offsetHeight) this.bodyTable.closest('table').removeClass('no-bottom-border'); else this.bodyTable.closest('table').addClass('no-bottom-border'); } else if (this.options.useDataSource) { if (this.bodyTable.find('tr').length == this.options.pageSize) this.bodyTable.closest('table').addClass('no-bottom-border'); else this.bodyTable.closest('table').removeClass('no-bottom-border'); } }, _hasRows: function() { var tbody = this.bodyTable[0].tagName == 'TBODY' ? this.bodyTable : this.bodyTable.find('tbody'), i = 0; if (!tbody.length) return false; for (i=0; i< tbody[0].childNodes.length; i++) if (tbody[0].childNodes[i].nodeName == 'TR') return true; return false; }, _initRow: function(row) { if (row[0].grid_initialized !== undefined && row[0].grid_initialized) return; row[0].grid_initialized = true; var block_delete_input = row.find('input.block_delete_message'); if (block_delete_input.length && block_delete_input.val() != '') row[0].block_delete_message = block_delete_input.val(); var cells = row.find('td'), self = this; $.each(cells, function(cellIndex, cellElement){ var cell = jQuery(cellElement), valueInput = cell.find('input.cell-value'), internalInput = cell.find('input.internal-value'), rowDataIndex = cell.find('input.row-index').val(), cellData = { display: cell.text().trim(), value: valueInput.length ? valueInput.attr('value') : cell.text(), internal: internalInput.val() }; cell.data('ui.grid', self); cell.text(''); row[0].rowDataIndex = rowDataIndex; self._getColumnEditor(cellIndex).initContent(cell, cellData, row, cellIndex, self.options.columns[cellIndex], rowDataIndex); if (self.options.rowsDeletable && cells.length == cellIndex+1) self._createRowMenu(row, cell, self); }); }, _createRowMenu: function(row, cell, grid) { var contentContainer = cell.find('.cell-content-container'); menu = jQuery('<span class="ui-grid-menu"></span>'), deleteLink = jQuery('<a class="menu-delete">Delete</a>').attr('tabindex', 0).bind('click', {grid: grid}, function(ev){ ev.stopImmediatePropagation(); grid._deleteRow(row); return false; }); menu.append(deleteLink); contentContainer.append(menu); }, _assignRowEventHandlers: function(row) { if (this.options.sortable || this.options.rowsDeletable) { if (row === undefined) row = this.bodyTable.find('tr'); var self = this; if (this.options.sortable) { row.bind('mousedown', function(event){ self._dragStart(event); }); } if (this.options.rowsDeletable) { row.bind('mouseenter', function(event){self._rowMouseEnter(event);}); row.bind('mouseleave', function(event){self._rowMouseLeave(event);}); } } }, _assignDocumentHandlers: function() { var self = this; jQuery(document).bind('keydown.grid', function(ev){ return self._handleGridKeys(ev); }) }, _handleGridKeys: function(ev) { var self = this; if (self.options.useDataSource) { if (self.element.closest('html').length == 0) return; if ((ev.metaKey || ev.ctrlKey) && ev.keyCode == 73) { if (self.appendRow(null, ev)) { ev.preventDefault(); return false; } } } }, _assignBodyEventHandlers: function() { var self = this; this.bodyTable.bind('keydown', function(ev){ if (ev.keyCode == 9) { if (self._isNoSearchResults()) return false; if (ev.target !== undefined && jQuery(ev.target).hasClass('cell-content-container')) { if (!ev.shiftKey) self._navigateRight(jQuery(ev.target).parent(), false); else self._navigateLeft(jQuery(ev.target).parent(), false); ev.preventDefault(); return false; } } if ((ev.metaKey || ev.ctrlKey)) { if (ev.target !== undefined) { if (self._isNoSearchResults()) return false; var cell = jQuery(ev.target).closest('table.ui-grid-body tr td'); if (ev.keyCode == 68) { if (!self.options.rowsDeletable) return false; if (self._isNoSearchResults()) return false; var row = jQuery(ev.target).closest('table.ui-grid-body tr'), cellIndex = row.children('td').index(cell), rowIndex = self.bodyTable.children('tr').index(row), currentPage = 0; if (self.options.useDataSource) currentPage = self._getCurrentPage(); if (cell.length && !self.options.useDataSource) self._navigateUp(cell); if (row.length) self._deleteRow(row, true, function(){ if (self.options.useDataSource) { if (cell) { var row = (currentPage == self._getCurrentPage()) ? self.bodyTable.find('tr:eq('+rowIndex+')') : self.bodyTable.find('tr:last'); if (!row.length) row = self.bodyTable.find('tr:last'); if (row.length) { self._initRow(row) row.find('td:eq('+cellIndex+')').trigger('navigateTo'); } } } }); ev.preventDefault(); return false; } else if (ev.keyCode == 73) { if (!self.options.allowAutoRowAdding) return false; if (self.options.useDataSource) return false; self.addRow(false, 'above'); if (cell.length) self._navigateUp(cell); ev.preventDefault(); return false; } } } }) }, _deleteRow: function(row, noMessage, onComplete) { if (this._isNoSearchResults()) return false; row.addClass('ui-selected'); if (noMessage === undefined || noMessage === false) if (!confirm(this.options.deleteRowMessage)) { row.removeClass('ui-selected'); return; } if (row[0].block_delete_message !== undefined) { alert(row[0].block_delete_message); return; } if (!this.options.useDataSource) { row.remove(); this._hideRowMenu(); if (!this.bodyTable[0].rows.length) this.addRow(); this.alignColumns(); this._updateScroller(); this._fixBottomBorder(); } else { var self = this; this._gotoPage(this._getCurrentPage(), { data: {'phpr_delete_row': row[0].rowDataIndex}, 'onComplete': function(){ if (!self.bodyTable[0].rows.length) self.addRow(); if (onComplete !== undefined) onComplete(); } }); } }, _bindSearch: function() { this.searchField = jQuery('#' + this.element.attr('id') + '_search_field') if (this.searchField.length) { var self = this; new InputChangeTracker(this.searchField.attr('id'), {regexp_mask: '^.*$'}).addEvent('change', function(){ self._updateSearch(); }); this.searchField.bind('keydown', function(ev){ if (ev.keyCode == 13) self._updateSearch(); }) } }, _hideEditors: function() { this.element.trigger('hideEditors'); }, _scrollToCell: function(cell) { var scroller = this.element.find('.ui-grid-h-scroll'); if (scroller.length) { cellPosition = cell.position(); if (cellPosition.left < 0) { var tweak = cell.is(':first-child') ? -1 : 0; scroller.scrollLeft(scroller.scrollLeft() + cellPosition.left + tweak); } else { var offsetRight = scroller.width() - (cellPosition.left + cell.width()); if (offsetRight < 0) scroller.scrollLeft(scroller.scrollLeft() - offsetRight); } } }, _pauseScrolling: function() { this._scrollingPaused = true; this.element.find('.ui-grid-h-scroll').addClass('no-scroll'); }, _resumeScrolling: function() { this._scrollingPaused = false; this.element.find('.ui-grid-h-scroll').removeClass('no-scroll'); }, _disableRowAdding: function() { this.disableRowAdding = true; }, _enableRowAdding: function() { this.disableRowAdding = false; }, /* * Row menus */ _rowMouseEnter: function(event){ var self = this; jQuery(event.currentTarget).find('span.ui-grid-menu').removeClass('menu-visible'); this._clearMenuTimer(); this.menuTimer = window.setInterval(function(){ self._displayRowMenu(event); }, 200); }, _displayRowMenu: function(event) { this._clearMenuTimer(); var row = jQuery(event.currentTarget); if (row.hasClass('ui-no-menu')) return; var menu = row.find('span.ui-grid-menu'); if (!menu.length) return; menu.css('left', 'auto'); var rowHeight = row.outerHeight(), scroller = this.element.find('.ui-grid-h-scroll'); if (scroller.length) { var cell = row.find('td:last'), scrollerWidth = scroller.width(), cellWidth = cell.width(), fixMenuPosition = function() { var cellPosition = cell.position(), cellOffset = cellPosition.left - scrollerWidth; if ((cellOffset + cellWidth) > 0) menu.css('left', (-1*cellOffset - 21) + 'px'); else menu.css('left', 'auto'); }; scroller.bind('scroll.grid', fixMenuPosition); fixMenuPosition(); } menu.css('height', rowHeight-1); menu.addClass('menu-visible'); this.currentMenu = menu; }, _rowMouseLeave: function(event) { this._clearMenuTimer(); }, _hideRowMenu: function(event) { this._clearMenuTimer(); if (!this.currentMenu) return; var scroller = this.element.find('.ui-grid-h-scroll'); scroller.unbind('.grid'); this.currentMenu.removeClass('menu-visible'); this.currentMenu = null; }, _disableRowMenu: function(cell) { this._clearMenuTimer(); this._hideRowMenu(); jQuery(cell).closest('tr').addClass('ui-no-menu'); }, _enableRowMenu: function(cell) { jQuery(cell).closest('tr').removeClass('ui-no-menu'); }, _clearMenuTimer: function() { if (this.menuTimer) { window.clearInterval(this.menuTimer); this.menuTimer = null; } }, /* * Drag support */ _dragStart: function(event) { if (event.target.tagName == 'INPUT' || event.target.tagName == 'SELECT') return; this.dragging = true; this.dragStartOffset = event.pageY; this.dragPrevOffset = 0; this.dragRow = event.currentTarget; this.dragStarted = false; this.bodyTable.disableSelection(); if (this.options.scrollable) { this.viewportOffset = this.viewport.offset(); this.viewportHeight = this.viewport.height(); this.overviewHeight = this.overview.height(); } }, _mouseMove: function(event) { if (!this.dragging) return; if (!this.dragStarted) { this.element.trigger('hideEditors'); this.dragStarted = true; this.bodyTable.addClass('drag'); jQuery(this.dragRow).addClass('ui-selected'); } if (this.options.scrollable) { if (this.viewportOffset.top > event.pageY) { // var scrollOffset = Math.max(this.scrollablePanel.scrollTop() - this.viewportOffset.top + event.pageY, 0); this.scroller.update_position(this.scrollablePanel.scrollTop()-50); } else if (event.pageY > (this.viewportOffset.top + this.viewportHeight)) { // var // bottom = this.viewportOffset.top + this.viewportHeight, // scrollOffset = Math.min(this.scrollablePanel.scrollTop() + event.pageY - bottom, this.overviewHeight-this.viewportHeight); this.scroller.update_position(this.scrollablePanel.scrollTop()+50); } } var offset = event.pageY - this.dragStartOffset; if (offset != this.dragPrevOffset) { var movingDown = offset > this.dragPrevOffset; this.dragPrevOffset = offset; var currentRow = this._findDragHoverRow(this.dragRow, event.pageY); if (currentRow !== null && currentRow !== undefined) { if (movingDown) this.dragRow.parentNode.insertBefore(this.dragRow, currentRow.nextSibling); else this.dragRow.parentNode.insertBefore(this.dragRow, currentRow); } } this.alignColumns(); }, _findDragHoverRow: function(currentRow, y) { var rows = this.bodyTable[0].rows; for (var i=0; i<rows.length; i++) { var row = rows[i], rowTop = jQuery(row).offset().top, rowHeight = row.offsetHeight; if ((y > rowTop) && (y < (rowTop + rowHeight))) { if (row == currentRow) return null; return row; } } }, _mouseUp: function(event) { if (this.dragTimeout) window.clearTimeout(this.dragTimeout); if (!this.dragging) return; this.bodyTable.enableSelection(); this.bodyTable.removeClass('drag'); this.dragging = false; jQuery(this.dragRow).removeClass('ui-selected'); event.stopImmediatePropagation(); }, /* * Navigation */ _getColumnEditor: function(cellIndex) { if (this.editors === undefined) this.editors = []; if (this.editors[cellIndex] !== undefined) return this.editors[cellIndex]; var columConfiguration = this.options.columns[cellIndex], editorName = columConfiguration.type + 'Editor'; return this.editors[editorName] = new jQuery.ui.grid.editors[editorName](); }, _navigateRight: function(fromCell, selectAll) { selectAll = selectAll === undefined ? false : selectAll; var next = fromCell.nextAll('td.ui-grid-cell-navigatable'); if (next.length) { jQuery(next[0]).trigger('navigateTo', ['right', selectAll]); return true; } else { var self = this, row = fromCell.parent(); this._createFindNextRow(row, function(nextRow){ if (!nextRow.length) return false; self._initRow(nextRow); var cell = nextRow.find('td.ui-grid-cell-navigatable:first'); cell.trigger('navigateTo', ['right', selectAll]); }); return true; } return false; }, _navigateLeft: function(fromCell, selectAll) { selectAll = selectAll === undefined ? false : selectAll; var prev = fromCell.prevAll('td.ui-grid-cell-navigatable'); if (prev.length) { jQuery(prev[0]).trigger('navigateTo', ['left', selectAll]); return true; } else { var row = fromCell.closest('tr'); this._createFindPrevRow(row, function(prevRow){ if (!prevRow.length) return; self._initRow(prevRow); var cell = prevRow.find('td.ui-grid-cell-navigatable:last'); cell.trigger('navigateTo', ['left', selectAll]); }); return true; } return false; }, _navigateDown: function(fromCell) { var self = this, row = fromCell.parent(), index = row.children('td').index(fromCell); this._createFindNextRow(row, function(nextRow){ if (!nextRow.length) return; self._initRow(nextRow); nextRow.find('td:eq('+index+')').trigger('navigateTo', ['left']); }); }, _navigateUp: function(fromCell) { var self = this, row = fromCell.parent(), index = row.children('td').index(fromCell); this._createFindPrevRow(row, function(prevRow){ if (!prevRow.length) return; self._initRow(prevRow); prevRow.find('td:eq('+index+')').trigger('navigateTo', ['left']); }); }, _setCurrentRow: function(row) { if (this.currentRow !== undefined && this.currentRow != row) this.currentRow.removeClass('current-row'); this.currentRow = row; this.currentRow.addClass('current-row'); }, _createFindNextRow: function(currentRow, callback) { this._hideRowMenu(); if (!currentRow.is(':last-child')) return callback(currentRow.next('tr')); if (!this.options.useDataSource || this.bodyTable.find('tr').length < this.options.pageSize) return callback(this.addRow()); var self = this; /* * If the row is last on this page, but the page is not last, * go to the first row of the next page. */ if (!this._isLastPage()) { this._gotoPage(this._getCurrentPage() + 1, {onComplete: function(){ var row = self.bodyTable.find('tr:first'); if (row.length) callback(row); }}); } else { /* * If the row is last on this page, and the page is last, * create new record in the data source and go to the next page. */ this.rowsAdded = this.rowsAdded === undefined ? 1 : this.rowsAdded+1; this._gotoPage(this._getCurrentPage() + 1, {data: {'phpr_append_row': 1, 'phpr_new_row_key': -1*this.rowsAdded}, onComplete: function(){ var row = self.bodyTable.find('tr:first'); if (row.length) callback(row); }}); } }, _createFindPrevRow: function(currentRow, callback) { this._hideRowMenu(); if (!currentRow.is(':first-child')) return callback(currentRow.prev('tr')); if (!this.options.useDataSource) return; /* * Go to the previous page */ var self = this; if (!this._isFirstPage()) { this._gotoPage(this._getCurrentPage() - 1, {onComplete: function(){ var row = self.bodyTable.find('tr:last'); if (row.length) callback(row); }}); } }, _createRowInTheEnd: function(callback) { this.rowsAdded = this.rowsAdded === undefined ? 1 : this.rowsAdded+1; if (this._isLastPage() && this.bodyTable.find('tr').length < this.options.pageSize) return callback(this.addRow()); this._gotoPage('last', {data: {'phpr_append_row': 1, 'phpr_new_row_key': -1*this.rowsAdded}, onComplete: function(){ var row = self.bodyTable.find('tr:last'); if (row.length) callback(row); }}); }, _isLastPage: function() { return this.element.find('.grid-is-last-page').val() === '1'; }, _isFirstPage: function() { return this.element.find('.grid-is-first-page').val() === '1'; }, _getCurrentPage: function() { return parseInt(this.element.find('.grid-current-page').val()); }, _getTotalRowCount: function() { return parseInt(this.element.find('.grid-total-record-count').val()); }, /* * Server response handling */ _handleWidgetResponseData: function(data) { if (this.element.parent().length == 0) return; if (data.widget === undefined || data.widget != 'grid') return; if (this.options.name != data.name) return; var self = this; handleError = function() { errorFieldName = self.options.name+'['+data.row+']['+data.column+']', errorField = self.bodyTable.find('input.cell-value[name="'+errorFieldName+'"]'); if (!errorField.length) return; self._markErrorField(errorField); self._scrollToCell(errorField.closest('td')); } var searchEnabled = false; if (this.searchField !== undefined) { if (this.searchField.val().length) { this.searchField.val(''); searchEnabled = true; } } if (this.options.useDataSource && (searchEnabled || (data.page_index !== undefined && this._getCurrentPage() != data.page_index))) { this._gotoPage(data.page_index, {onComplete: function(){ handleError(); }}); } else handleError(); }, _markErrorField: function(field) { if (this._errorRow !== undefined) { this._errorRow.removeClass('grid-error'); this._errorCell.removeClass('grid-error'); } this._errorRow = field.closest('tr'); this._errorCell = field.closest('td'); this._errorRow.addClass('grid-error'); this._errorCell.addClass('grid-error'); if (this.options.scrollable) { var offset = this._errorCell.position().top - this._errorCell.height() + this.scrollablePanel.scrollTop(); if (offset < 0) offset = 0; this.scroller.update_position(offset); } this._errorCell.trigger('navigateTo'); }, /* * Datasource support */ _gotoPage: function(pageIndex, options) { var self = this; if (options === undefined) options = {}; if (options.data === undefined) options.data = {}; this._disableRowMenu(); var searchUpdatedRows = this.searchUpdatedRows !== undefined ? this.searchUpdatedRows : []; if (options.data.phpr_new_row_key !== undefined) searchUpdatedRows.push(options.data.phpr_new_row_key); if (this.rowsAdded === undefined) this.rowsAdded = 1; var searchTerm = this.searchField !== undefined ? this.searchField.val() : null, data = $merge({ 'phpr_custom_event_name': 'on_navigate_to_page', 'phpr_event_field': this.options.dataFieldName, 'phpr_page_index': pageIndex, 'phpr_grid_search': searchTerm, 'phpr_grid_records_added': this.rowsAdded, 'phpr_grid_search_updated_records': searchUpdatedRows.join(',') }, options.data); new Request.Phpr({ url: location.pathname, handler: this.actionName+'onFormWidgetEvent', extraFields: data, update: 'multi', loadIndicator: {show: false}, onBeforePost: LightLoadingIndicator.show.pass('Loading...'), onComplete: LightLoadingIndicator.hide, onAfterUpdate: function() { self.rebuild(); self._dropHeaderCheckboxes(); if (options.onComplete !== undefined) options.onComplete(); self._enableRowMenu(); if (!self._hasRows() && self.searchField !== undefined && self.searchField.val().length) self._showNoSearchResults(); else self._hideNoSearchResults(); self.rowsAdded += self._getTotalRowCount(); var message = self.element.find('.grid-message-text').val(); if (message.length) alert(message); }, onFailure: function(xhr) { alert(xhr.responseText.replace('@AJAX-ERROR@', '').replace(/(<([^>]+)>)/ig,"")); }, }).post(this.element.closest('form')[0]); return false; }, updateData: function(serverEvent) { if (this.searchField !== undefined) this.searchField.val(''); this.searchUpdatedRows = []; this._gotoPage(0, {data: {'phpr_grid_event': serverEvent}}); }, /* * Search support */ _updateSearch: function() { this.searchUpdatedRows = []; this._gotoPage(0); }, _markRowSearchUpdated: function(recordIndex) { if (this.searchUpdatedRows == undefined) this.searchUpdatedRows = []; this.searchUpdatedRows.push(recordIndex); }, _showNoSearchResults: function() { this.noSearchResultsVisible = true; if (this.noSearchResultsMessage === undefined) { this.noSearchResultsMessage = jQuery('<p class="ui-no-records noData"></p>').text('No records found'); this.container.append(this.noSearchResultsMessage); this.noSearchResultsMessage.css('top', Math.round(this.container.height()/2-19)); this.noSearchResultsMessage.css('left', Math.round(this.container.width()/2-100)); } this.noSearchResultsMessage.css('display', 'block'); this.existingTable.css('display', 'none'); }, _hideNoSearchResults: function() { this.noSearchResultsVisible = false; if (this.noSearchResultsMessage === undefined) return; this.noSearchResultsMessage.css('display', 'none'); this.existingTable.css('display', 'table'); }, _isNoSearchResults: function() { return this.noSearchResultsVisible; }, /* * Header checkboxes support */ _initHeaderCheckboxes: function() { var self = this; this.headTable.find('th.checkbox-cell input').each(function(index, input) { input.addEvent('click', function() { var headCell = jQuery(input).closest('th'); var cellIndex = headCell.parent().children('th').index(headCell); var columnInfo = self.options.columns[cellIndex]; self.bodyTable.find('tr').find('td:eq('+cellIndex+')').each(function(rowIndex, cell){ if (input.checked) jQuery(cell).find('div.checkbox').addClass('checked'); else jQuery(cell).find('div.checkbox').removeClass('checked'); jQuery(cell).find('.cell-value').val(input.checked ? 1 : 0); if (columnInfo.checked_class !== undefined) { var row = jQuery(cell).parent(); if (input.checked) row.addClass(columnInfo.checked_class); else row.removeClass(columnInfo.checked_class); } }); }) }) }, _dropHeaderCheckboxes: function() { this.headTable.find('th.checkbox-cell input').each(function(index, input) { input.cb_uncheck(); }); }, /* * Tracing */ _trace: function(message) { if (window.console) console.log(message); return; } }); })( jQuery );
JavaScript
/** * This script contains grid control column editor classes. */ (function( $, undefined ) { jQuery.ui.grid = {editors: {}}; jQuery.ui.grid.editors.editorBase = jQuery.Class.create({ initialize: function() { }, /** * Initializes the cell content during the table building procedure. * @param object cell Specifies a DOM td element corresponding to the cell. * @param mixed cellContent Specifies the text content - either a string, * or an object with "display" and "value" fields. * @param array row Current table row. * @param integer cellIndex Current cell index. * @param integer rowDataIndex Current cell data element index. * @param mixed columnInfo Column confiruation object. * The method should set the cell inner content, */ initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { if (cell.find('.cell-content-container').length == 0) cell.append(jQuery('<div/>').addClass('cell-content-container').attr('tabindex', 0)); this.createCellValueElement(cell, cellIndex, rowDataIndex); this.renderContent(cell, cellContent, row, cellIndex); }, /** * Creates a hiden input element for holding the cell value. * @param object cell Specifies a DOM td element corresponding to the cell. * @param integer cellIndex Specifies a cell index. * @param integer rowDataIndex Specifies a row data index. */ createCellValueElement: function(cell, cellIndex, rowDataIndex) { var grid = cell.data('ui.grid'), contentContainer = cell.find('.cell-content-container'); contentContainer.append(jQuery('<input type="hidden" class="cell-value"></input>').attr( 'name', grid.options.name+'['+rowDataIndex+']['+grid.options.columns[cellIndex].field+']' )); contentContainer.append(jQuery('<input type="hidden" class="internal-value"></input>').attr( 'name', grid.options.name+'['+rowDataIndex+']['+grid.options.columns[cellIndex].field+'_internal]' )); }, /** * Renders cell content in read-only mode. * @param object cell Specifies a DOM td element corresponding to the cell. * @param mixed cellContent Specifies the text content - either a string, * or an object with "display" and "value" fields. * @param array row Current table row. * @param integer cellIndex Current cell index. * The method should set the cell inner content, */ renderContent: function(cell, cellContent, row, cellIndex) { if (jQuery.type(cellContent) !== 'object') { this.setCellValue(cell, cellContent); this.setCellDisplayText(cell, cellContent); } else { this.setCellValue(cell, cellContent.value); this.setCellInternalValue(cell, cellContent.internal); this.setCellDisplayText(cell, cellContent.display); } }, /** * Sets cell hidden value. * @param object cell Specifies the cell DOM td element. * @param string value Specifies the value to set. */ setCellValue: function(cell, value) { cell.find('input.cell-value').attr('value', value); this.markCellRowSearchUpdated(cell); }, /** * Sets cell internal hidden value. * @param object cell Specifies the cell DOM td element. * @param string value Specifies the value to set. */ setCellInternalValue: function(cell, value) { cell.find('input.internal-value').attr('value', value); this.markCellRowSearchUpdated(cell); }, /** * Sets cell display value. * @param object cell Specifies the cell DOM td element. * @param string text Specifies the text to set. */ setCellDisplayText: function(cell, text) { var span = cell.find('span.cell-content'); if (span.length == 0) { var contentContainer = cell.find('.cell-content-container'); span = jQuery('<span class="cell-content"></span>').text(text); contentContainer.append(span); } else span.text(text); }, /** * Returns cell display value. * @param object cell Specifies the cell DOM td element. * @return string Cell display value. */ getCellDisplayText: function(cell) { return cell.find('span.cell-content').text(); }, /** * Returns cell hidden value. * @param object cell Specifies the cell DOM td element. * @return string Cell hidden value. */ getCellValue: function(cell) { return cell.find('input.cell-value').attr('value'); }, /** * Hides cell display value. * @param object cell Specifies the cell DOM td element. */ hideCellDisplayText: function(cell) { return cell.find('span.cell-content').hide(); }, /** * Shows cell display value. * @param object cell Specifies the cell DOM td element. */ showCellDisplayText: function(cell) { return cell.find('span.cell-content').show(); }, /** * Displays the cell editor, if applicable. * @param object cell Specifies the cell DOM td element. */ displayEditor: function(cell) { this.getGrid(cell)._setCurrentRow(cell.closest('tr')); }, /** * Hides the cell editor, if applicable. * @param object cell Specifies the cell DOM td element. * @param object editor Specifies the editor DOM element, if applicable. */ hideEditor: function(cell, editor) { }, /** * Sets or returns the editor visibility state. * @param object cell Specifies the cell DOM td element. * @param boolean value Optional visibility state value. * If omitted, the function will return the current visibility state. * @return boolean */ editorVisible: function(cell, value) { if (value === undefined) return cell.data('ui.grid.editor_visible') ? true : false; cell.data('ui.grid.editor_visible', value); return value; }, /** * Returns parent grid object. * @param object cell Specifies the cell DOM td element. */ getGrid: function(cell) { return cell.data('ui.grid'); }, /** * Binds standard content container keys. * @param object contentContainer Specifies the content containier jQuery object. * @param boolean allAsClick Indicates whether any key (but arrows, tab and return) should trigger the click event. * @param boolean returnAsClick Indicates whether Return key should trigger the click event. */ bindContentContainerKeys: function(contentContainer, allAsClick, returnAsClick) { var self = this, cell = contentContainer.parent(); contentContainer.bind('keydown', function(ev){ if (self.editorVisible(cell)) return; switch (ev.keyCode) { case 32 : ev.preventDefault(); cell.trigger('click'); break; case 38 : ev.preventDefault(); self.getGrid(cell)._navigateUp(cell); break; case 40 : ev.preventDefault(); self.getGrid(cell)._navigateDown(cell); break; case 39 : case 37 : ev.preventDefault(); if (ev.keyCode == 39) self.getGrid(cell)._navigateRight(cell); else self.getGrid(cell)._navigateLeft(cell); break; case 13 : if (returnAsClick === undefined || returnAsClick === false) return; ev.preventDefault(); cell.trigger('click'); break; case 9 : break; default : if (!ev.shiftKey && !ev.ctrlKey && !ev.altKey && !ev.metaKey) { ev.preventDefault(); cell.trigger('click'); } else self.getGrid(cell)._handleGridKeys(ev); break; } }); }, markCellRowSearchUpdated: function(cell) { var grid = this.getGrid(cell), row = cell.closest('tr'); if (row.length && grid) grid._markRowSearchUpdated(row[0].rowDataIndex); } }); /* * Popup editor */ jQuery.ui.grid.editors.popupEditor = jQuery.Class.create(jQuery.ui.grid.editors.editorBase, { initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { var self = this; this.base('initContent', cell, cellContent, row, cellIndex, columnInfo, rowDataIndex); cell.addClass('ui-grid-cell-clickable'); this.bindPopupTrigger(cell, columnInfo, rowDataIndex); }, bindPopupTrigger: function(cell, columnInfo, rowDataIndex) { var self = this; cell.addClass('ui-grid-cell-focusable'); cell.addClass('ui-grid-cell-navigatable'); this.contentContainer = cell.find('.cell-content-container'); this.bindContentContainerKeys(this.contentContainer, false, true); this.contentContainer.bind('focus', function(ev){ self.getGrid(cell)._setCurrentRow(cell.closest('tr')); }); cell.bind('navigateTo', function(event, direction, selectAll){ self.contentContainer.focus(); }); cell.bind('click', function(){ var grid = self.getGrid(cell); grid._scrollToCell(cell); self.buildPopup(cell, columnInfo, rowDataIndex, self); return false; }) }, getZIndex: function(element) { var zElement = element.parents().filter(function(){ var css = jQuery(this).css('z-index'); return css !== undefined && css != 'auto'; }); return parseInt(zElement.css('z-index')); }, buildPopup: function(cell, columnInfo, rowDataIndex, editor) { var zIndex = this.getZIndex(cell), grid = this.getGrid(cell); self = this; /* * Build the overlay */ var overlay = jQuery('<div class="ui-grid-overlay ui-overlay"/>'); if (zIndex) overlay.css('z-index', zIndex+1); jQuery(grid.element).append(overlay); jQuery.ui.grid.popupOverlay = overlay; /* * Build the popup window */ var tmp = jQuery('<div/>').css('display', 'none'); jQuery(grid.element).append(tmp); grid._hideRowMenu(); cell.find('.cell-content-container').blur(); new Request.Phpr({ url: location.pathname, handler: grid.actionName+'onFormWidgetEvent', extraFields: { 'phpr_custom_event_name': 'on_show_popup_editor', 'phpr_event_field': grid.options.dataFieldName, 'phpr_popup_column': columnInfo.field, 'phpr_grid_row_index': rowDataIndex }, update: tmp[0], loadIndicator: {show: false}, onSuccess: function() { editor.displayPopup(tmp, zIndex, cell, grid); }, onFailure: function(xhr) { alert(xhr.responseText.replace('@AJAX-ERROR@', '').replace(/(<([^>]+)>)/ig,"")); tmp.remove(); overlay.remove(); jQuery.ui.grid.popupOverlay = undefined; }, }).post(cell.closest('form')[0]); }, displayPopup: function(dataContainer, zIndex, cell, grid) { var container = jQuery('<div class="ui-popup-container"/>').css({ 'z-index': zIndex+2, 'visibility': 'hidden' }), handle = jQuery('<div class="ui-popup-handle"/>'), content = jQuery('<div class="ui-popup-content-container"/>'), containerOffset = jQuery(grid.element).offset(), cellOffset = cell.offset(), docHeight = jQuery(document).height(), docWidth = jQuery(document).width(), cellHeightOffset = docHeight - cellOffset.top, cellWidthOffset = docWidth - cellOffset.left, popupContent = dataContainer.children().first(); jQuery.ui.grid.popupContainer = container; jQuery.ui.grid.popupCell = cell; content.append(popupContent); container.append(content); container.append(handle); dataContainer.remove(); jQuery(grid.element).append(container); var containerHeight = container.outerHeight(), containerWidth = container.outerWidth(), showBelow = cellHeightOffset > (containerHeight+40), showRight = cellWidthOffset > (containerWidth+50); if ((cellOffset.top - cell.height() + 15 - containerHeight) < 0) showBelow = true; var contentTop = showBelow ? (cellOffset.top - containerOffset.top + cell.height() + 5 + 'px') : (cellOffset.top - containerOffset.top - cell.height() + 15 - containerHeight + 'px'); var contentLeft = showRight ? (cellOffset.left - containerOffset.left + container.width() + 40 - containerWidth + 'px') : (cellOffset.left - containerOffset.left - container.width() + 40 + 'px'); container.css({ top: contentTop, left: contentLeft, visibility: 'visible' }); if (!showBelow) container.addClass('above'); if (showRight) container.addClass('right'); cell.addClass('popup-focused'); popupContent[0].fireEvent('popupLoaded'); window.fireEvent('popupLoaded', popupContent[0]); popupContent.data('ui.gridEditor', this); popupContent.data('ui.gridCell', cell); grid._hideEditors(); grid._disableRowAdding(); jQuery(document).bind('keydown.gridpopup', function(ev){ if (ev.keyCode == 27) popupContent[0].fireEvent('onEscape'); }); } }); /* * Single-line text editor. This editor has optional autocomplete parameter, which could be set in the column configuration object. * The parameter value could be either "predefined" or "remote". If the predefined option is specified, the column configuration * object should also have the "options" array with a list of available values. */ jQuery.ui.grid.editors.textEditor = jQuery.Class.create(jQuery.ui.grid.editors.popupEditor, { initialize: function() { this.base('initialize'); }, initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { var self = this; this.base('initContent', cell, cellContent, row, cellIndex, columnInfo, rowDataIndex); cell.addClass('ui-grid-cell-navigatable'); cell.addClass('ui-grid-cell-editable'); cell.find('.cell-content-container').bind('focus.grid', function(event){ self.displayEditor(cell, null, false, columnInfo); }) cell.bind('click.grid navigateTo', function(event, direction, selectAll){ selectAll = selectAll === undefined ? false : selectAll; self.displayEditor(cell, direction, selectAll, columnInfo); }); if (columnInfo.editor_class !== undefined) { cell.data('grid.rowDataIndex', rowDataIndex); } }, bindPopupTrigger: function(cell, columnInfo, rowDataIndex) {}, displayEditor: function(cell, navigationDirection, selectAll, columnInfo) { if (this.editorVisible(cell) || this.getGrid(cell).dragStarted) return; this.editorVisible(cell, true); var grid = this.getGrid(cell); grid._scrollToCell(cell); var self = this, editor = jQuery('<input type="text" class="cell-editor"/>') .attr('value', this.getCellValue(cell)) .css('height', cell.height()+'px'), editorContainer = jQuery('<div class="cell-editor-container"/>'), autocomplete = columnInfo.autocomplete !== undefined ? columnInfo.autocomplete : false; grid._disableRowMenu(cell); editorContainer.append(editor); editor.data('gridContainer', editorContainer); /* * Setup autocompletion */ if (autocomplete !== false) { var options = { appendTo: grid.element, position: { my: "left top", at: "left bottom", collision: "none", of: cell }, open: function(){ grid._pauseScrolling(); var autocompleteObj = grid.element.find('.ui-autocomplete'), widthFix = 1, fixLeft = false; if (cell.is(':first-child')) { widthFix++; fixLeft = true; } var autocompleteWidth = cell.outerWidth()+widthFix; if (autocompleteWidth < 200) autocompleteWidth = 200; autocompleteObj.outerWidth(autocompleteWidth); if (fixLeft > 0) autocompleteObj.css('margin-left', '-1px'); }, close: function(){ grid._resumeScrolling(); }, minLength: (columnInfo.minLength === undefined ? 1 : columnInfo.minLength) }; if (autocomplete == 'predefined') options.source = columnInfo.options; else if (autocomplete == 'remote') { var row = cell.closest('tr'), form = cell.closest('form'), action = form.attr('action'); options.source = function(request, response) { self.autocomplete(request, response, columnInfo, cell, row, action, form, grid); } } editor.autocomplete(options); } /* * Setup editor events */ this.hideCellDisplayText(cell); editor.bind('blur', function(){ window.setTimeout(function(){ self.hideEditor(cell, editor); }, 200) }); grid.element.bind('hideEditors', function(){ self.hideEditor(cell, editor); }) editor.keyup(function(ev){ self.setCellValue(cell, editor.val()); }); editor.bind('keydown', function(ev){ switch (ev.keyCode) { case 38 : if (autocomplete === false) grid._navigateUp(cell); break; case 40 : if (autocomplete === false) grid._navigateDown(cell); break; case 39 : case 37 : var sel = jQuery(editor).caret(); if (sel.end === undefined) sel.end = 0; if (ev.keyCode == 39) { if (sel.end == editor.attr('value').length) { ev.preventDefault(); grid._navigateRight(cell); } } else { if (sel.start === undefined) { ev.preventDefault(); grid._navigateLeft(cell); } } break; case 9 : if (!ev.shiftKey) { if (grid._navigateRight(cell, true)) ev.preventDefault(); } else { if (grid._navigateLeft(cell, true)) ev.preventDefault(); } break; case 27 : self.hideEditor(cell, editor); break; case 73 : if (ev.metaKey || ev.ctrlKey) grid.appendRow(cell, ev); break; } }); /* * Create button for the popup editor */ if (columnInfo.editor_class !== undefined) { var button = jQuery('<a href="#" class="ui-grid-cell-button"></a>'), knob = jQuery('<span></span>'), heightTweak = -1, row = cell.parent(); if (row.is(':last-child') && grid.bodyTable.hasClass('no-bottom-border')) heightTweak = 0; button.css({ 'height': cell.outerHeight() + heightTweak + 'px', }) .append(knob); button.click(function(){ self.hideEditor(cell, editor); self.buildPopup(cell, columnInfo, cell.data('grid.rowDataIndex'), self); return false; }); editorContainer.append(button); cell.addClass('popup-button-container'); editor.bind('keydown', function(ev){ if (ev.keyCode == 13 && !ev.ctrlKey) { button.trigger('click'); editorContainer.blur(); ev.preventDefault(); return false; } }); } /* * Append the editor, and focus it */ cell.append(editorContainer); editor.focus(); /* * Set the caret position and display the eidtor */ if (!selectAll) { if (navigationDirection !== undefined && navigationDirection === 'left') { var len = editor.attr('value').length; editor.caret(len, len); } else editor.caret(0, 0); } else { var len = editor.attr('value').length; editor.caret(0, len); } this.base('displayEditor', cell); }, hideEditor: function(cell, editor) { this.editorVisible(cell, false); var self = this, grid = self.getGrid(cell); this.setCellDisplayText(cell, editor.attr('value')); this.setCellValue(cell, editor.attr('value')); if (editor.data('gridContainer')) editor.data('gridContainer').remove(); else editor.remove(); this.showCellDisplayText(cell); if (grid) grid._enableRowMenu(cell); }, autocomplete: function (request, response, columnInfo, cell, row, url, form, grid) { var formData = form.serialize(), rowData = {}, custom_values = columnInfo.autocomplete_custom_values === undefined ? false : true; row.find('input.cell-value').each(function(index, input){ var $input = jQuery(input), match = /[^\]]+\[[^\]]+\]\[\-?[0-9]+\]\[([^\]]+)\]/.exec($input.attr('name')); if (match !== null) { var field_name = 'autocomplete_row_data['+match[1]+']', field_value = $input.attr('value'); rowData[field_name] = field_value; } }); formData += '&'+ jQuery.param(rowData)+ '&autocomplete_term='+encodeURIComponent(request.term)+ '&autocomplete_column='+columnInfo.field+ '&autocomplete_custom_values='+custom_values+ '&phpr_custom_event_name=on_autocomplete'+ '&phpr_event_field='+ grid.options.dataFieldName+ '&phpr_no_cookie_update=1'; var lastXhr = jQuery.ajax({ 'type': 'POST', 'url': url, 'data': formData, success: function( data, status, xhr ) { if ( xhr === lastXhr ) { response(data); } }, dataType: 'json', headers: { 'PHPR-REMOTE-EVENT': 1, 'PHPR-POSTBACK': 1, 'PHPR-EVENT-HANDLER': 'ev{'+grid.actionName+'onFormWidgetEvent}', 'PHPR-CUSTOM-EVENT-NAME': 'on_autocomplete', 'PHPR-EVENT-FIELD': grid.options.dataFieldName } }); } }); /* * Drop-down cell editor. This editor requires the option_keys and option_values properties * to be set in the column configuration object: {option_keys: [0, 1], option_values: ['Option 1', 'Option 2']} * Other supported options: allowDeselect (boolean), default_text: string */ jQuery.ui.grid.editors.dropdownEditor = jQuery.Class.create(jQuery.ui.grid.editors.editorBase, { initialize: function() { this.base('initialize'); }, initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { var self = this; this.ignoreFocus = false; this.base('initContent', cell, cellContent, row, cellIndex, columnInfo, rowDataIndex); cell.addClass('ui-grid-cell-navigatable'); cell.addClass('ui-grid-cell-editable'); cell.addClass('ui-grid-cell-focusable'); this.contentContainer = cell.find('.cell-content-container'); this.bindContentContainerKeys(this.contentContainer, true, false); this.contentContainer.bind('focus', function(ev){ if (ev.originalEvent !== undefined) self.displayEditor(cell, null, columnInfo); else self.getGrid(cell)._setCurrentRow(cell.closest('tr')); }); cell.bind('click.grid', function(event, direction, selectAll){ self.displayEditor(cell, direction, columnInfo); }); cell.bind('navigateTo', function(event, direction, selectAll){ self.contentContainer.focus(); }); }, displayEditor: function(cell, navigationDirection, columnInfo) { if (this.editorVisible(cell) || this.getGrid(cell).dragStarted) return; var grid = this.getGrid(cell); grid._scrollToCell(cell); var self = this, gridOffset = grid.element.offset(), cellOffset = cell.offset(), offsetLeft = cellOffset.left-gridOffset.left-2, offsetTop = cellOffset.top-gridOffset.top-3; if (!cell.is(':first-child')) offsetLeft++; if (!grid.options.scrollable) offsetLeft++; grid._hideEditors(); this.editorVisible(cell, true); this.hideCellDisplayText(cell); var select = jQuery('<select>'), selectContainer = jQuery('<div class="ui-grid-select-container">'); selectContainer.css({ 'left': offsetLeft+'px', 'top': offsetTop+'px', 'width': (cell.width()+2)+'px', 'height': (cell.height()+2)+'px' }); if (columnInfo.default_text !== undefined) select.attr('data-placeholder', columnInfo.default_text); if (columnInfo.allow_deselect !== undefined || columnInfo.default_text !== undefined) select.append(jQuery('<option>').attr('value', '').text('')); var valueFound = false, currentValue = this.getCellValue(cell); jQuery.each(columnInfo.option_keys, function(index, value){ select.append(jQuery('<option></option>').attr('value', value).text(columnInfo.option_values[index])); if (currentValue == value) valueFound = true; }); if (!valueFound) select.append(jQuery('<option></option>').attr('value', currentValue).text(currentValue)); select.val(currentValue); selectContainer.append(select); grid.element.append(selectContainer); select.bind('change', function(){ self.setCellDisplayText(cell, select.find('option:selected').text()); self.setCellValue(cell, select.val()); self.hideEditor(cell, select); self.ignoreFocus = true; self.contentContainer.focus(); self.ignoreFocus = false; }) cell.css('overflow', 'visible'); var options = {allow_single_deselect: false}; if (columnInfo.allowDeselect !== undefined) options.allow_single_deselect = columnInfo.allowDeselect; jQuery(select).chosen(options); grid._disableRowMenu(cell); grid._pauseScrolling(); var container = selectContainer.find('.chzn-container'); container.css('height', (cell.height()+2)+'px'); container.bind('keydown', function(ev){ switch (ev.keyCode) { case 9 : self.hideEditor(cell, select); if (!ev.shiftKey) { if (self.getGrid(cell)._navigateRight(cell, true)) ev.preventDefault(); } else { if (self.getGrid(cell)._navigateLeft(cell, true)) ev.preventDefault(); } break; case 27 : self.hideEditor(cell, select); ev.preventDefault(); self.ignoreFocus = true; self.contentContainer.focus(); self.ignoreFocus = false; break; } }); window.setTimeout(function(){ jQuery(document).bind('mousedown.gridDropdown', function(e) { self.hideEditor(cell, select); }); }, 300); this.base('displayEditor', cell); this.getGrid(cell).element.bind('hideEditors', function(){ self.hideEditor(cell, select); }); window.setTimeout(function(){ container.trigger('mousedown'); }, 60); }, hideEditor: function(cell, editor) { var grid = this.getGrid(cell); if (grid === undefined) return; grid._enableRowMenu(cell); grid._resumeScrolling(); jQuery(document).unbind('.gridDropdown'); editor.parent().remove(); this.editorVisible(cell, false); cell.find('.chzn-container').remove(); cell.css('overflow', ''); var self = this; this.showCellDisplayText(cell); } }); /* * Checkbox cell editor */ jQuery.ui.grid.editors.checkboxEditor = jQuery.Class.create(jQuery.ui.grid.editors.editorBase, { initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { var self = this; this.base('initContent', cell, cellContent, row, cellIndex, columnInfo, rowDataIndex); cell.addClass('cell-checkbox'); cell.addClass('ui-grid-cell-navigatable'); this.hideCellDisplayText(cell); var editor = jQuery('<div class="checkbox"/>') .attr('tabindex', 0) .bind('click', function(){ var curValue = self.getCellValue(cell); if (curValue == 1) { self.setCellValue(cell, 0); jQuery(this).removeClass('checked'); self.getGrid(cell)._dropHeaderCheckboxes(); if (columnInfo.checked_class !== undefined) row.removeClass(columnInfo.checked_class); } else { self.setCellValue(cell, 1); jQuery(this).addClass('checked'); if (columnInfo.checked_class !== undefined) row.addClass(columnInfo.checked_class); } }) .bind('focus', function(ev){ self.getGrid(cell)._setCurrentRow(cell.closest('tr')); }) .bind('keydown', function(ev){ switch (ev.keyCode) { case 32 : case 13 : editor.trigger('click'); break; case 38 : self.getGrid(cell)._navigateUp(cell); break; case 40 : self.getGrid(cell)._navigateDown(cell); break; case 39 : case 37 : ev.preventDefault(); if (ev.keyCode == 39) self.getGrid(cell)._navigateRight(cell); else self.getGrid(cell)._navigateLeft(cell); break; case 9 : if (!ev.shiftKey) { if (self.getGrid(cell)._navigateRight(cell, true)) ev.preventDefault(); } else { if (self.getGrid(cell)._navigateLeft(cell, true)) ev.preventDefault(); } break; default: self.getGrid(cell)._handleGridKeys(ev); break; } }); if (this.getCellValue(cell) == 1) editor.addClass('checked'); var contentContainer = cell.find('.cell-content-container'); contentContainer.append(editor); cell.bind('click navigateTo', function(ev, direction, selectAll){ editor.focus(); }); } }); jQuery.ui.grid.hidePopup = function() { if (!jQuery.ui.grid.popupContainer !== undefined && jQuery.ui.grid.popupOverlay !== undefined) { hide_tooltips(); jQuery.ui.grid.popupContainer.remove(); jQuery.ui.grid.popupOverlay.remove(); jQuery.ui.grid.popupCell.removeClass('popup-focused'); jQuery.ui.grid.popupCell.data('ui.grid')._enableRowAdding(); if (jQuery.ui.grid.popupCell.hasClass('ui-grid-cell-focusable')) jQuery.ui.grid.popupCell.find('.cell-content-container').focus(); jQuery(document).unbind('keydown.gridpopup'); } } })( jQuery );
JavaScript
/* Redactor v8.0.3 Updated: September 3, 2012 http://redactorjs.com/ Copyright (c) 2009-2012, Imperavi Inc. License: http://redactorjs.com/license/ Usage: $('#content').redactor(); */ // selection mechanism var _0xf6db=["(6(){11 49=24;11 14={50:6(8,10){5 10.58(8)\x2692},57:6(8,10){7(8.58!=12){5 8.58(10)\x2616}46{5 8.57(10)}},55:6(8,18,10,20){7(8===10){5 18\x3C=20}7(14.29(8)\x26\x2614.29(10)){5 14.50(8,10)}7(14.29(8)\x26\x26!14.29(10)){5!14.55(10,20,8,18)}7(!14.57(8,10)){5 14.50(8,10)}7(8.47.85\x3C=18){5 40}7(8.47[18]===10){5 0\x3C=20}5 14.50(8.47[18],10)},29:6(61){5(61!=12?61.93==3:40)},81:6(41){11 62=0;88(41=41.59){62++}5 62}};11 4=49.4=(6(){6 4(2){24.2=2}4.34.31=6(){5 4.31(24.2)};4.34.37=6(){5 4.37(24.2)};4.34.38=6(){5 4.38(24.2)};4.34.45=6(){5 4.45(24.2)};4.34.44=6(){5 4.44(24.2)};4.34.52=6(25,26,23,22){5 4.52(24.2,25,26,23,22)};4.34.51=6(){5 4.51(24.2)};5 4})();7(49.35){4.67=43;4.31=6(2){11 9;5(9=2.35())\x26\x26(9.63!=12)\x26\x26(9.36!=12)};4.37=6(2){11 9;7(!((9=2.35())\x26\x26(9.36!=12))){5 12}5[9.36,9.97]};4.38=6(2){11 9;7(!((9=2.35())\x26\x26(9.63!=12))){5 12}5[9.63,9.91]};4.45=6(2){11 8,10,18,20,27,28;7(!4.31(2)){5 12}27=4.37(2),8=27[0],18=27[1];28=4.38(2),10=28[0],20=28[1];7(14.55(8,18,10,20)){5[8,18]}5[10,20]};4.44=6(2){11 8,10,18,20,27,28;7(!4.31(2)){5 12}27=4.37(2),8=27[0],18=27[1];28=4.38(2),10=28[0],20=28[1];7(14.55(8,18,10,20)){5[10,20]}5[8,18]};4.52=6(2,25,26,23,22){11 9=2.35();7(!9){5}7(23==12){23=25}7(22==12){22=26}7(9.60\x26\x269.79){9.60(25,26);9.79(23,22)}46{54=2.15.56();54.106(25,26);54.107(23,22);71{9.73()}80(41){}9.98(54)}};4.51=6(2){71{11 9=2.35();7(!9){5}9.73()}80(41){}}}46 7(49.15.39){11 69=6(42,32,30){11 19,13,21,33,64;13=42.90(\x2789\x27);19=32.103();19.60(30);64=19.77();88(43){64.86(13,13.59);19.82(13);7(!(19.87((30?\x2766\x27:\x2783\x27),32)\x3E0\x26\x26(13.59!=12))){99}}7(19.87((30?\x2766\x27:\x2783\x27),32)===-1\x26\x2613.84){19.74((30?\x27100\x27:\x2778\x27),32);21=13.84;33=19.101.85}46{21=13.48;33=14.81(13)}13.48.72(13);5[21,33]};11 68=6(42,32,30,21,33){11 36,65,19,13,53;53=0;36=14.29(21)?21:21.47[33];65=14.29(21)?21.48:21;7(14.29(21)){53=33}13=42.90(\x2789\x27);65.86(13,36||12);19=42.76.75();19.82(13);13.48.72(13);32.74((30?\x2766\x27:\x2778\x27),19);5 32[30?\x27105\x27:\x27104\x27](\x27102\x27,53)};4.67=43;4.31=6(2){11 17;2.70();7(!2.15.39){5 40}17=2.15.39.56();5 17\x26\x2617.77().15===2.15};4.45=6(2){11 17;2.70();7(!4.31(2)){5 12}17=2.15.39.56();5 69(2.15,17,43)};4.44=6(2){11 17;2.70();7(!4.31(2)){5 12}17=2.15.39.56();5 69(2.15,17,40)};4.37=6(2){5 4.45(2)};4.38=6(2){5 4.44(2)};4.52=6(2,25,26,23,22){7(23==12){23=25}7(22==12){22=26}11 17=2.15.76.75();68(2.15,17,40,23,22);68(2.15,17,43,25,26);5 17.96()};4.51=6(2){5 2.15.39.95()}}46{4.67=40}}).94(24);","|","split","||win||Selection|return|function|if|n1|sel|n2|var|null|cursorNode|Dom|document||range|o1|cursor|o2|node|foco|focn|this|orgn|orgo|_ref|_ref2|isText|bStart|hasSelection|textRange|offset|prototype|getSelection|anchorNode|getOrigin|getFocus|selection|false|e|doc|true|getEnd|getStart|else|childNodes|parentNode|root|isPreceding|clearSelection|setSelection|textOffset|r|isCursorPreceding|createRange|contains|compareDocumentPosition|previousSibling|collapse|d|k|focusNode|parent|anchorParent|StartToStart|supported|moveBoundary|getBoundary|focus|try|removeChild|removeAllRanges|setEndPoint|createTextRange|body|parentElement|EndToEnd|extend|catch|getChildIndex|moveToElementText|StartToEnd|nextSibling|length|insertBefore|compareEndPoints|while|a|createElement|focusOffset|0x02|nodeType|call|empty|select|anchorOffset|addRange|break|EndToStart|text|character|duplicate|moveEnd|moveStart|setStart|setEnd","replace","","\x5Cw+","\x5Cb","g"];eval(function (p,a,c,k,e,d){e=function (c){return c;} ;if(!_0xf6db[5][_0xf6db[4]](/^/,String)){while(c--){d[c]=k[c]||c;} ;k=[function (e){return d[e];} ];e=function (){return _0xf6db[6];} ;c=1;} ;while(c--){if(k[c]){p=p[_0xf6db[4]]( new RegExp(_0xf6db[7]+e(c)+_0xf6db[7],_0xf6db[8]),k[c]);} ;} ;return p;} (_0xf6db[0],10,108,_0xf6db[3][_0xf6db[2]](_0xf6db[1]),0,{})); if (typeof RELANG === 'undefined') { var RELANG = {}; } var RLANG = { html: 'HTML', video: 'Insert Video...', image: 'Insert Image...', table: 'Table', link: 'Link', link_insert: 'Insert Link ...', unlink: 'Unlink', formatting: 'Formatting', paragraph: 'Paragraph', quote: 'Quote', code: 'Code', header1: 'Header 1', header2: 'Header 2', header3: 'Header 3', header4: 'Header 4', bold: 'Bold', italic: 'Italic', fontcolor: 'Font Color', backcolor: 'Back Color', unorderedlist: 'Unordered List', orderedlist: 'Ordered List', outdent: 'Outdent', indent: 'Indent', cancel: 'Cancel', insert: 'Insert', save: 'Save', _delete: 'Delete', insert_table: 'Insert Table...', insert_row_above: 'Add Row Above', insert_row_below: 'Add Row Below', insert_column_left: 'Add Column Left', insert_column_right: 'Add Column Right', delete_column: 'Delete Column', delete_row: 'Delete Row', delete_table: 'Delete Table', rows: 'Rows', columns: 'Columns', add_head: 'Add Head', delete_head: 'Delete Head', title: 'Title', image_position: 'Position', none: 'None', left: 'Left', right: 'Right', image_web_link: 'Image Web Link', text: 'Text', mailto: 'Email', web: 'URL', video_html_code: 'Video Embed Code', file: 'Insert File...', upload: 'Upload', download: 'Download', choose: 'Choose', or_choose: 'Or choose', drop_file_here: 'Drop file here', align_left: 'Align Left', align_center: 'Align Center', align_right: 'Align Right', align_justify: 'Justify', horizontalrule: 'Insert Horizontal Rule', deleted: 'Deleted', anchor: 'Anchor', link_new_tab: 'Open link in new tab' }; (function($){ // Plugin jQuery.fn.redactor = function(option) { return this.each(function() { var $obj = $(this); var data = $obj.data('redactor'); if (!data) { $obj.data('redactor', (data = new Redactor(this, option))); } }); }; // Initialization var Redactor = function(element, options) { // Element this.$el = $(element); // Lang if (typeof options !== 'undefined' && typeof options.lang !== 'undefined' && options.lang !== 'en' && typeof RELANG[options.lang] !== 'undefined') { RLANG = RELANG[options.lang]; } // Options this.opts = $.extend({ lang: 'en', direction: 'ltr', // ltr or rtl callback: false, // function keyupCallback: false, // function keydownCallback: false, // function execCommandCallback: false, // function cleanup: true, focus: false, tabindex: false, autoresize: true, minHeight: false, fixed: false, fixedTop: 0, // pixels fixedBox: false, source: true, shortcuts: true, mobile: true, air: false, wym: false, paragraphy: true, convertLinks: true, convertDivs: true, protocol: 'http://', // for links http or https autosave: false, // false or url autosaveCallback: false, // function interval: 60, // seconds imageGetJson: false, // url (ex. /folder/images.json ) or false imageUpload: false, // url imageUploadCallback: false, // function fileUpload: false, // url fileUploadCallback: false, // function uploadCrossDomain: false, uploadFields: false, observeImages: true, overlay: true, // modal overlay allowedTags: ["code", "span", "div", "label", "a", "br", "p", "b", "i", "del", "strike", "u", "img", "video", "audio", "iframe", "object", "embed", "param", "blockquote", "mark", "cite", "small", "ul", "ol", "li", "hr", "dl", "dt", "dd", "sup", "sub", "big", "pre", "code", "figure", "figcaption", "strong", "em", "table", "tr", "td", "th", "tbody", "thead", "tfoot", "h1", "h2", "h3", "h4", "h5", "h6"], buttonsCustom: {}, buttonsAdd: [], buttons: ['html', '|', 'formatting', '|', 'bold', 'italic', 'deleted', '|', 'unorderedlist', 'orderedlist', 'outdent', 'indent', '|', 'image', 'video', 'file', 'table', 'link', '|', 'fontcolor', 'backcolor', '|', 'alignleft', 'aligncenter', 'alignright', 'justify', '|', 'horizontalrule'], airButtons: ['formatting', '|', 'bold', 'italic', 'deleted', '|', 'unorderedlist', 'orderedlist', 'outdent', 'indent', '|', 'fontcolor', 'backcolor'], colors: [ '#ffffff', '#000000', '#eeece1', '#1f497d', '#4f81bd', '#c0504d', '#9bbb59', '#8064a2', '#4bacc6', '#f79646', '#ffff00', '#f2f2f2', '#7f7f7f', '#ddd9c3', '#c6d9f0', '#dbe5f1', '#f2dcdb', '#ebf1dd', '#e5e0ec', '#dbeef3', '#fdeada', '#fff2ca', '#d8d8d8', '#595959', '#c4bd97', '#8db3e2', '#b8cce4', '#e5b9b7', '#d7e3bc', '#ccc1d9', '#b7dde8', '#fbd5b5', '#ffe694', '#bfbfbf', '#3f3f3f', '#938953', '#548dd4', '#95b3d7', '#d99694', '#c3d69b', '#b2a2c7', '#b7dde8', '#fac08f', '#f2c314', '#a5a5a5', '#262626', '#494429', '#17365d', '#366092', '#953734', '#76923c', '#5f497a', '#92cddc', '#e36c09', '#c09100', '#7f7f7f', '#0c0c0c', '#1d1b10', '#0f243e', '#244061', '#632423', '#4f6128', '#3f3151', '#31859b', '#974806', '#7f6000'], // private allEmptyHtml: '<p><br /></p>', mozillaEmptyHtml: '<p>&nbsp;</p>', buffer: false, visual: true, // modal windows container modal_file: String() + '<form id="redactorUploadFileForm" method="post" action="" enctype="multipart/form-data">' + '<label>Name (optional)</label>' + '<input type="text" id="redactor_filename" class="redactor_input" />' + '<div style="margin-top: 7px;">' + '<input type="file" id="redactor_file" name="file" />' + '</div>' + '</form>', modal_image_edit: String() + '<label>' + RLANG.title + '</label>' + '<input id="redactor_file_alt" class="redactor_input" />' + '<label>' + RLANG.link + '</label>' + '<input id="redactor_file_link" class="redactor_input" />' + '<label>' + RLANG.image_position + '</label>' + '<select id="redactor_form_image_align">' + '<option value="none">' + RLANG.none + '</option>' + '<option value="left">' + RLANG.left + '</option>' + '<option value="right">' + RLANG.right + '</option>' + '</select>' + '<div id="redactor_modal_footer">' + '<a href="javascript:void(null);" id="redactor_image_delete_btn" style="color: #000;">' + RLANG._delete + '</a>' + '<span class="redactor_btns_box">' + '<input type="button" name="save" id="redactorSaveBtn" value="' + RLANG.save + '" />' + '<a href="javascript:void(null);" id="redactor_btn_modal_close">' + RLANG.cancel + '</a>' + '</span>' + '</div>', modal_image: String() + '<div id="redactor_tabs">' + '<a href="javascript:void(null);" class="redactor_tabs_act">' + RLANG.upload + '</a>' + '<a href="javascript:void(null);">' + RLANG.choose + '</a>' + '<a href="javascript:void(null);">' + RLANG.link + '</a>' + '</div>' + '<form id="redactorInsertImageForm" method="post" action="" enctype="multipart/form-data">' + '<div id="redactor_tab1" class="redactor_tab">' + '<input type="file" id="redactor_file" name="file" />' + '</div>' + '<div id="redactor_tab2" class="redactor_tab" style="display: none;">' + '<div id="redactor_image_box"></div>' + '</div>' + '</form>' + '<div id="redactor_tab3" class="redactor_tab" style="display: none;">' + '<label>' + RLANG.image_web_link + '</label>' + '<input name="redactor_file_link" id="redactor_file_link" class="redactor_input" />' + '</div>' + '<div id="redactor_modal_footer">' + '<span class="redactor_btns_box">' + '<input type="button" name="upload" id="redactor_upload_btn" value="' + RLANG.insert + '" />' + '<a href="javascript:void(null);" id="redactor_btn_modal_close">' + RLANG.cancel + '</a>' + '</span>' + '</div>', modal_link: String() + '<form id="redactorInsertLinkForm" method="post" action="">' + '<div id="redactor_tabs">' + '<a href="javascript:void(null);" class="redactor_tabs_act">URL</a>' + '<a href="javascript:void(null);">Email</a>' + '<a href="javascript:void(null);">' + RLANG.anchor + '</a>' + '</div>' + '<input type="hidden" id="redactor_tab_selected" value="1" />' + '<div class="redactor_tab" id="redactor_tab1">' + '<label>URL</label><input id="redactor_link_url" class="redactor_input" />' + '<label>' + RLANG.text + '</label><input class="redactor_input redactor_link_text" id="redactor_link_url_text" />' + '<label><input type="checkbox" id="redactor_link_blank"> ' + RLANG.link_new_tab + '</div>' + '<div class="redactor_tab" id="redactor_tab2" style="display: none;">' + '<label>Email</label><input id="redactor_link_mailto" class="redactor_input" />' + '<label>' + RLANG.text + '</label><input class="redactor_input redactor_link_text" id="redactor_link_mailto_text" />' + '</div>' + '<div class="redactor_tab" id="redactor_tab3" style="display: none;">' + '<label>' + RLANG.anchor + '</label><input class="redactor_input" id="redactor_link_anchor" />' + '<label>' + RLANG.text + '</label><input class="redactor_input redactor_link_text" id="redactor_link_anchor_text" />' + '</div>' + '</form>' + '<div id="redactor_modal_footer">' + '<span class="redactor_btns_box">' + '<input type="button" id="redactor_insert_link_btn" value="' + RLANG.insert + '" />' + '<a href="javascript:void(null);" id="redactor_btn_modal_close">' + RLANG.cancel + '</a>' + '</span>' + '</div>', modal_table: String() + '<label>' + RLANG.rows + '</label>' + '<input size="5" value="2" id="redactor_table_rows" />' + '<label>' + RLANG.columns + '</label>' + '<input size="5" value="3" id="redactor_table_columns" />' + '<div id="redactor_modal_footer">' + '<span class="redactor_btns_box">' + '<input type="button" name="upload" id="redactor_insert_table_btn" value="' + RLANG.insert + '" />' + '<a href="javascript:void(null);" id="redactor_btn_modal_close">' + RLANG.cancel + '</a>' + '</span>' + '</div>', modal_video: String() + '<form id="redactorInsertVideoForm">' + '<label>' + RLANG.video_html_code + '</label>' + '<textarea id="redactor_insert_video_area" style="width: 99%; height: 160px;"></textarea>' + '</form>' + '<div id="redactor_modal_footer">' + '<span class="redactor_btns_box">' + '<input type="button" id="redactor_insert_video_btn" value="' + RLANG.insert + '" />' + '<a href="javascript:void(null);" id="redactor_btn_modal_close">' + RLANG.cancel + '</a>' + '</span>' + '</div>', toolbar: { html: { title: RLANG.html, func: 'toggle' }, formatting: { title: RLANG.formatting, func: 'show', dropdown: { p: { title: RLANG.paragraph, exec: 'formatblock' }, blockquote: { title: RLANG.quote, exec: 'formatblock', className: 'redactor_format_blockquote' }, pre: { title: RLANG.code, exec: 'formatblock', className: 'redactor_format_pre' }, h1: { title: RLANG.header1, exec: 'formatblock', className: 'redactor_format_h1' }, h2: { title: RLANG.header2, exec: 'formatblock', className: 'redactor_format_h2' }, h3: { title: RLANG.header3, exec: 'formatblock', className: 'redactor_format_h3' }, h4: { title: RLANG.header4, exec: 'formatblock', className: 'redactor_format_h4' } } }, bold: { title: RLANG.bold, exec: 'bold' }, italic: { title: RLANG.italic, exec: 'italic' }, deleted: { title: RLANG.deleted, exec: 'strikethrough' }, unorderedlist: { title: '&bull; ' + RLANG.unorderedlist, exec: 'insertunorderedlist' }, orderedlist: { title: '1. ' + RLANG.orderedlist, exec: 'insertorderedlist' }, outdent: { title: '< ' + RLANG.outdent, exec: 'outdent' }, indent: { title: '> ' + RLANG.indent, exec: 'indent' }, image: { title: RLANG.image, func: 'showImage' }, video: { title: RLANG.video, func: 'showVideo' }, file: { title: RLANG.file, func: 'showFile' }, table: { title: RLANG.table, func: 'show', dropdown: { insert_table: { title: RLANG.insert_table, func: 'showTable' }, separator_drop1: { name: 'separator' }, insert_row_above: { title: RLANG.insert_row_above, func: 'insertRowAbove' }, insert_row_below: { title: RLANG.insert_row_below, func: 'insertRowBelow' }, insert_column_left: { title: RLANG.insert_column_left, func: 'insertColumnLeft' }, insert_column_right: { title: RLANG.insert_column_right, func: 'insertColumnRight' }, separator_drop2: { name: 'separator' }, add_head: { title: RLANG.add_head, func: 'addHead' }, delete_head: { title: RLANG.delete_head, func: 'deleteHead' }, separator_drop3: { name: 'separator' }, delete_column: { title: RLANG.delete_column, func: 'deleteColumn' }, delete_row: { title: RLANG.delete_row, func: 'deleteRow' }, delete_table: { title: RLANG.delete_table, func: 'deleteTable' } } }, link: { title: RLANG.link, func: 'show', dropdown: { link: { title: RLANG.link_insert, func: 'showLink' }, unlink: { title: RLANG.unlink, exec: 'unlink' } } }, fontcolor: { title: RLANG.fontcolor, func: 'show' }, backcolor: { title: RLANG.backcolor, func: 'show' }, alignleft: { exec: 'JustifyLeft', title: RLANG.align_left }, aligncenter: { exec: 'JustifyCenter', title: RLANG.align_center }, alignright: { exec: 'JustifyRight', title: RLANG.align_right }, justify: { exec: 'justifyfull', title: RLANG.align_justify }, horizontalrule: { exec: 'inserthorizontalrule', title: RLANG.horizontalrule } } }, options, this.$el.data()); this.dropdowns = []; // Init this.init(); }; // Functionality Redactor.prototype = { // Initialization init: function() { // get dimensions this.height = this.$el.css('height'); this.width = this.$el.css('width'); // mobile if (this.opts.mobile === false && this.isMobile()) { this.build(true); return false; } if (this.opts.paragraphy === false) { this.opts.convertDivs = false; } // extend buttons if (this.opts.air) { this.opts.buttons = this.opts.airButtons; } else if (this.opts.toolbar !== false) { if (this.opts.source === false) { var index = this.opts.buttons.indexOf('html'); var next = this.opts.buttons[index+1]; this.opts.buttons.splice(index, 1); if (typeof next !== 'undefined' && next === '|') { this.opts.buttons.splice(index, 1); } } $.extend(this.opts.toolbar, this.opts.buttonsCustom); $.each(this.opts.buttonsAdd, $.proxy(function(i,s) { this.opts.buttons.push(s); }, this)); } // construct editor this.build(); // air enable this.enableAir(); // toolbar this.buildToolbar(); // paste var oldsafari = false; if ($.browser.webkit && navigator.userAgent.indexOf('Chrome') === -1) { var arr = $.browser.version.split('.'); if (arr[0] < 536) oldsafari = true; } if (this.isMobile(true) === false && oldsafari === false) { this.$editor.bind('paste', $.proxy(function(e) { if (this.opts.cleanup === false) { return true; } this.setBuffer(); if (this.opts.autoresize === true) { this.saveScroll = document.body.scrollTop; } else { this.saveScroll = this.$editor.scrollTop(); } var frag = this.extractContent(); setTimeout($.proxy(function() { var pastedFrag = this.extractContent(); this.$editor.append(frag); this.restoreSelection(); var html = this.getFragmentHtml(pastedFrag); this.pasteCleanUp(html); }, this), 1); }, this)); } // key handlers this.keyup(); this.keydown(); // autosave if (this.opts.autosave !== false) { this.autoSave(); } // observers this.observeImages(); this.observeTables(); // FF fix if ($.browser.mozilla) { document.execCommand('enableObjectResizing', false, false); document.execCommand('enableInlineTableEditing', false, false); } // focus if (this.opts.focus) { this.$editor.focus(); } // fixed if (this.opts.fixed) { this.observeScroll(); $(document).scroll($.proxy(this.observeScroll, this)); } // callback if (typeof this.opts.callback === 'function') { this.opts.callback(this); } }, shortcuts: function(e, cmd) { e.preventDefault(); this.execCommand(cmd, false); }, keyup: function() { this.$editor.keyup($.proxy(function(e) { var key = e.keyCode || e.which; // callback as you type if (typeof this.opts.keyupCallback === 'function') { this.opts.keyupCallback(this, e); } // if empty if (key === 8 || key === 46) { this.observeImages(); return this.formatEmpty(e); } // new line p if (key === 13 && !e.shiftKey && !e.ctrlKey && !e.metaKey) { if ($.browser.webkit && this.opts.paragraphy) { this.formatNewLine(e); } // convert links if (this.opts.convertLinks) { this.$editor.linkify(); } } this.syncCode(); }, this)); }, keydown: function() { this.$editor.keydown($.proxy(function(e) { var key = e.keyCode || e.which; var parent = this.getParentNode(); var pre = false; var ctrl = e.ctrlKey || e.metaKey; if (parent && $(parent).get(0).tagName === 'PRE') { pre = true; } // callback keydown if (typeof this.opts.keydownCallback === 'function') { this.opts.keydownCallback(this, e); } // breakline if (this.opts.paragraphy === false && $.browser.webkit && key === 13 && !e.shiftKey && !e.ctrlKey && !e.metaKey) { e.preventDefault(); this.insertNodeAtCaret($('<span class="redactor-breakline"><br></span>').get(0)); setTimeout($.proxy(function() { this.$editor.find('span.redactor-breakline').replaceWith('<br>'); setTimeout($.proxy(function() { this.syncCode(); }, this), 10); }, this), 10); return false; } if (ctrl && this.opts.shortcuts) { if (key === 90) { if (this.opts.buffer !== false) { e.preventDefault(); this.getBuffer(); } else if (e.shiftKey) { this.shortcuts(e, 'redo'); // Ctrl + Shift + z } else { this.shortcuts(e, 'undo'); // Ctrl + z } } else if (key === 77) { this.shortcuts(e, 'removeFormat'); // Ctrl + m } else if (key === 66) { this.shortcuts(e, 'bold'); // Ctrl + b } else if (key === 73) { this.shortcuts(e, 'italic'); // Ctrl + i } else if (key === 74) { this.shortcuts(e, 'insertunorderedlist'); // Ctrl + j } else if (key === 75) { this.shortcuts(e, 'insertorderedlist'); // Ctrl + k } else if (key === 76) { this.shortcuts(e, 'superscript'); // Ctrl + l } else if (key === 72) { this.shortcuts(e, 'subscript'); // Ctrl + h } } // clear undo buffer if (!ctrl && key !== 90) { this.opts.buffer = false; } // enter if (pre === true && key === 13) { e.preventDefault(); this.insertNodeAtCaret(document.createTextNode('\r\n')); } // tab if (this.opts.shortcuts && !e.shiftKey && key === 9) { if (pre === false) { this.shortcuts(e, 'indent'); // Tab } else { e.preventDefault(); this.insertNodeAtCaret(document.createTextNode('\t')); } } else if (this.opts.shortcuts && e.shiftKey && key === 9 ) { this.shortcuts(e, 'outdent'); // Shift + tab } // safari shift key + enter if ($.browser.webkit && navigator.userAgent.indexOf('Chrome') === -1) { return this.safariShiftKeyEnter(e, key); } }, this)); }, build: function(mobile) { if (mobile !== true) { // container this.$box = $('<div class="redactor_box"></div>'); // air box if (this.opts.air) { this.air = $('<div class="redactor_air" style="display: none;"></div>'); } // editor this.textareamode = true; if (this.$el.get(0).tagName === 'TEXTAREA') { this.$editor = $('<div></div>'); } else { this.textareamode = false; this.$editor = this.$el; this.$el = $('<textarea name="' + this.$editor.attr('id') + '"></textarea>').css('height', this.height); } this.$editor.addClass('redactor_editor').attr('contenteditable', true).attr('dir', this.opts.direction); if (this.opts.tabindex !== false) { this.$editor.attr('tabindex', this.opts.tabindex); } if (this.opts.minHeight !== false) { this.$editor.css('min-height', this.opts.minHeight + 'px'); } if (this.opts.wym === true) { this.$editor.addClass('redactor_editor_wym'); } if (this.opts.autoresize === false) { this.$editor.css('height', this.height); } // hide textarea this.$el.hide(); // append box and frame var html = ''; if (this.textareamode) { // get html html = this.$el.val(); this.$box.insertAfter(this.$el).append(this.$editor).append(this.$el); } else { // get html html = this.$editor.html(); this.$box.insertAfter(this.$editor).append(this.$el).append(this.$editor); } // conver newlines to p if (this.opts.paragraphy) { html = this.paragraphy(html); } else { html = html.replace(/<p>([\w\W]*?)<\/p>/gi, '$1<br><br>'); } // enable this.$editor.html(html); if (this.textareamode === false) { this.syncCode(); } } else { if (this.$el.get(0).tagName !== 'TEXTAREA') { var html = this.$el.val(); var textarea = $('<textarea name="' + this.$editor.attr('id') + '"></textarea>').css('height', this.height).val(html); this.$el.hide(); this.$el.after(textarea); } } }, enableAir: function() { if (this.opts.air === false) { return false; } this.air.hide(); this.$editor.bind('textselect', $.proxy(function(e) { this.showAir(e); }, this)); this.$editor.bind('textunselect', $.proxy(function() { this.air.hide(); }, this)); }, showAir: function(e) { $('.redactor_air').hide(); var width = this.air.innerWidth(); var left = e.clientX; if ($(document).width() < (left + width)) { left = left - width; } this.air.css({ left: left + 'px', top: (e.clientY + $(document).scrollTop() + 14) + 'px' }).show(); }, syncCode: function() { this.$el.val(this.$editor.html()); }, // API functions setCode: function(html) { this.$editor.html(html).focus(); this.syncCode(); }, getCode: function() { if (this.opts.visual) { return this.$editor.html() } else { return this.$el.val(); } }, insertHtml: function(html) { this.$editor.focus(); this.execCommand('inserthtml', html); this.observeImages(); }, destroy: function() { var html = this.getCode(); if (this.textareamode) { this.$box.after(this.$el); this.$box.remove(); this.$el.height(this.height).val(html).show(); } else { this.$box.after(this.$editor); this.$box.remove(); this.$editor.removeClass('redactor_editor').removeClass('redactor_editor_wym').attr('contenteditable', false).html(html).show(); } $('.redactor_air').remove(); for (var i = 0; i < this.dropdowns.length; i++) { this.dropdowns[i].remove(); delete(this.dropdowns[i]); } }, // end API functions // OBSERVERS observeImages: function() { if (this.opts.observeImages === false) { return false; } this.$editor.find('img').each($.proxy(function(i,s) { if ($.browser.msie) { $(s).attr('unselectable', 'on'); } this.resizeImage(s); }, this)); }, observeTables: function() { this.$editor.find('table').click($.proxy(this.tableObserver, this)); }, observeScroll: function() { var scrolltop = $(document).scrollTop(); var boxtop = this.$box.offset().top; var left = 0; if (scrolltop > boxtop) { var width = '100%'; if (this.opts.fixedBox) { left = this.$editor.offset().left; width = this.$editor.innerWidth(); } this.fixed = true; this.$toolbar.css({ position: 'fixed', width: width, zIndex: 100, top: this.opts.fixedTop + 'px', left: left }); } else { this.fixed = false; this.$toolbar.css({ position: 'relative', width: 'auto', zIndex: 1, top: 0, left: left }); } }, // BUFFER setBuffer: function() { this.saveSelection(); this.opts.buffer = this.$editor.html(); }, getBuffer: function() { if (this.opts.buffer === false) { return false; } this.$editor.html(this.opts.buffer); if (!$.browser.msie) { this.restoreSelection(); } this.opts.buffer = false; }, // EXECCOMMAND execCommand: function(cmd, param) { if (this.opts.visual == false) { this.$el.focus(); return false; } try { var parent; if (cmd === 'inserthtml' && $.browser.msie) { /*** IE-Insertion-Fix by Fabio Poloni ***/ if (!this.$editor.is(":focus")) { this.$editor.focus(); } document.selection.createRange().pasteHTML(param); } else if (cmd === 'formatblock' && $.browser.msie) { document.execCommand(cmd, false, '<' + param + '>'); } else if (cmd === 'unlink') { parent = this.getParentNode(); if ($(parent).get(0).tagName === 'A') { $(parent).replaceWith($(parent).text()); } else { document.execCommand(cmd, false, param); } } else if (cmd === 'formatblock' && param === 'blockquote') { parent = this.getParentNode(); if ($(parent).get(0).tagName === 'BLOCKQUOTE') { document.execCommand(cmd, false, 'p'); } else if ($(parent).get(0).tagName === 'P') { var parent2 = $(parent).parent(); if ($(parent2).get(0).tagName === 'BLOCKQUOTE') { var node = $('<p>' + $(parent).html() + '</p>'); $(parent2).replaceWith(node); this.setFocusNode(node.get(0)); } else { document.execCommand(cmd, false, param); } } else { document.execCommand(cmd, false, param); } } else if (cmd === 'formatblock' && param === 'pre') { parent = this.getParentNode(); if ($(parent).get(0).tagName === 'PRE') { $(parent).replaceWith('<p>' + $(parent).text() + '</p>'); } else { document.execCommand(cmd, false, param); } } else { document.execCommand(cmd, false, param); } if (cmd === 'inserthorizontalrule') { this.$editor.find('hr').removeAttr('id'); } this.syncCode(); if (this.oldIE()) { this.$editor.focus(); } if (typeof this.opts.execCommandCallback === 'function') { this.opts.execCommandCallback(this, cmd); } if (this.opts.air) { this.air.hide(); } } catch (e) { } }, // FORMAT NEW LINE formatNewLine: function(e) { var parent = this.getParentNode(); if (parent.nodeName === 'DIV' && parent.className === 'redactor_editor') { var element = $(this.getCurrentNode()); if (element.get(0).tagName === 'DIV' && (element.html() === '' || element.html() === '<br>')) { var newElement = $('<p>').append(element.clone().get(0).childNodes); element.replaceWith(newElement); newElement.html('<br />'); this.setFocusNode(newElement.get(0)); } } }, // SAFARI SHIFT KEY + ENTER safariShiftKeyEnter: function(e, key) { if (e.shiftKey && key === 13) { e.preventDefault(); this.insertNodeAtCaret($('<span><br /></span>').get(0)); this.syncCode(); return false; } else { return true; } }, // FORMAT EMPTY formatEmpty: function(e) { var html = $.trim(this.$editor.html()); if ($.browser.mozilla) { html = html.replace(/<br>/i, ''); } if (html === '') { e.preventDefault(); var nodehtml = this.opts.allEmptyHtml; if ($.browser.mozilla) { nodehtml = this.opts.mozillaEmptyHtml; } var node = $(nodehtml).get(0); this.$editor.html(node); this.setFocusNode(node); this.syncCode(); return false; } else { this.syncCode(); } }, // PARAGRAPHY paragraphy: function (str) { str = $.trim(str); if (str === '') { if (!$.browser.mozilla) { return this.opts.allEmptyHtml; } else { return this.opts.mozillaEmptyHtml; } } // convert div to p if (this.opts.convertDivs) { str = str.replace(/<div(.*?)>([\w\W]*?)<\/div>/gi, '<p>$2</p>'); } // inner functions var X = function(x, a, b) { return x.replace(new RegExp(a, 'g'), b); }; var R = function(a, b) { return X(str, a, b); }; // block elements var blocks = '(table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|math|style|script|object|input|param|p|h[1-6])'; //str = '<p>' + str; str += '\n'; R('<br />\\s*<br />', '\n\n'); R('(<' + blocks + '[^>]*>)', '\n$1'); R('(</' + blocks + '>)', '$1\n\n'); R('\r\n|\r', '\n'); // newlines R('\n\n+', '\n\n'); // remove duplicates R('\n?((.|\n)+?)$', '<p>$1</p>\n'); // including one at the end R('<p>\\s*?</p>', ''); // remove empty p R('<p>(<div[^>]*>\\s*)', '$1<p>'); R('<p>([^<]+)\\s*?(</(div|address|form)[^>]*>)', '<p>$1</p>$2'); R('<p>\\s*(</?' + blocks + '[^>]*>)\\s*</p>', '$1'); R('<p>(<li.+?)</p>', '$1'); R('<p>\\s*(</?' + blocks + '[^>]*>)', '$1'); R('(</?' + blocks + '[^>]*>)\\s*</p>', '$1'); R('(</?' + blocks + '[^>]*>)\\s*<br />', '$1'); R('<br />(\\s*</?(p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)', '$1'); // pre if (str.indexOf('<pre') != -1) { R('(<pre(.|\n)*?>)((.|\n)*?)</pre>', function(m0, m1, m2, m3) { return X(m1, '\\\\([\'\"\\\\])', '$1') + X(X(X(m3, '<p>', '\n'), '</p>|<br />', ''), '\\\\([\'\"\\\\])', '$1') + '</pre>'; }); } return R('\n</p>$', '</p>'); }, // REMOVE TAGS stripTags: function(html) { var allowed = this.opts.allowedTags; var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi; return html.replace(tags, function ($0, $1) { return $.inArray($1.toLowerCase(), allowed) > '-1' ? $0 : ''; }); }, // PASTE CLEANUP pasteCleanUp: function(html) { // remove comments and php tags html = html.replace(/<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi, ''); // remove nbsp html = html.replace(/(&nbsp;){1,}/gi, '&nbsp;'); // remove google docs marker html = html.replace(/<b\sid="internal-source-marker(.*?)">([\w\W]*?)<\/b>/gi, "$2"); // strip tags html = this.stripTags(html); // prevert html = html.replace(/<td><br><\/td>/gi, '[td]'); html = html.replace(/<a(.*?)>([\w\W]*?)<\/a>/gi, '[a$1]$2[/a]'); html = html.replace(/<iframe(.*?)>([\w\W]*?)<\/iframe>/gi, '[iframe$1]$2[/iframe]'); html = html.replace(/<video(.*?)>([\w\W]*?)<\/video>/gi, '[video$1]$2[/video]'); html = html.replace(/<audio(.*?)>([\w\W]*?)<\/audio>/gi, '[audio$1]$2[/audio]'); html = html.replace(/<embed(.*?)>([\w\W]*?)<\/embed>/gi, '[embed$1]$2[/embed]'); html = html.replace(/<object(.*?)>([\w\W]*?)<\/object>/gi, '[object$1]$2[/object]'); html = html.replace(/<param(.*?)>/gi, '[param$1]'); html = html.replace(/<img(.*?)>/gi, '[img$1]'); // remove attributes html = html.replace(/<(\w+)([\w\W]*?)>/gi, '<$1>'); // remove empty html = html.replace(/<[^\/>][^>]*>(\s*|\t*|\n*|&nbsp;|<br>)<\/[^>]+>/gi, ''); html = html.replace(/<[^\/>][^>]*>(\s*|\t*|\n*|&nbsp;|<br>)<\/[^>]+>/gi, ''); // revert html = html.replace(/\[td\]/gi, '<td><br></td>'); html = html.replace(/\[a(.*?)\]([\w\W]*?)\[\/a\]/gi, '<a$1>$2</a>'); html = html.replace(/\[iframe(.*?)\]([\w\W]*?)\[\/iframe\]/gi, '<iframe$1>$2</iframe>'); html = html.replace(/\[video(.*?)\]([\w\W]*?)\[\/video\]/gi, '<video$1>$2</video>'); html = html.replace(/\[audio(.*?)\]([\w\W]*?)\[\/audio\]/gi, '<audio$1>$2</audio>'); html = html.replace(/\[embed(.*?)\]([\w\W]*?)\[\/embed\]/gi, '<embed$1>$2</embed>'); html = html.replace(/\[object(.*?)\]([\w\W]*?)\[\/object\]/gi, '<object$1>$2</object>'); html = html.replace(/\[param(.*?)\]/gi, '<param$1>'); html = html.replace(/\[img(.*?)\]/gi, '<img$1>'); // convert div to p if (this.opts.convertDivs) { html = html.replace(/<div(.*?)>([\w\W]*?)<\/div>/gi, '<p>$2</p>'); } if (this.opts.paragraphy === false) { html = html.replace(/<p>([\w\W]*?)<\/p>/gi, '$1<br>'); } // remove span html = html.replace(/<span>([\w\W]*?)<\/span>/gi, '$1'); html = html.replace(/\n{3,}/gi, '\n'); // remove dirty p html = html.replace(/<p><p>/g, '<p>'); html = html.replace(/<\/p><\/p>/g, '</p>'); this.execCommand('inserthtml', html); if (this.opts.autoresize === true) { $(document.body).scrollTop(this.saveScroll); } else { this.$editor.scrollTop(this.saveScroll); } }, // TEXTAREA CODE FORMATTING formattingRemove: function(html) { // save pre var prebuffer = []; var pre = html.match(/<pre(.*?)>([\w\W]*?)<\/pre>/gi); if (pre !== null) { $.each(pre, function(i,s) { html = html.replace(s, 'prebuffer_' + i); prebuffer.push(s); }); } html = html.replace(/\s{2,}/g, ' '); html = html.replace(/\n/g, ' '); html = html.replace(/[\t]*/g, ''); html = html.replace(/\n\s*\n/g, "\n"); html = html.replace(/^[\s\n]*/g, ''); html = html.replace(/[\s\n]*$/g, ''); html = html.replace(/>\s+</g, '><'); if (prebuffer) { $.each(prebuffer, function(i,s) { html = html.replace('prebuffer_' + i, s); }); prebuffer = []; } return html; }, formattingIndenting: function(html) { html = html.replace(/<li/g, "\t<li"); html = html.replace(/<tr/g, "\t<tr"); html = html.replace(/<td/g, "\t\t<td"); html = html.replace(/<\/tr>/g, "\t</tr>"); return html; }, formattingEmptyTags: function(html) { var etags = ["<pre></pre>","<blockquote>\\s*</blockquote>","<em>\\s*</em>","<ul></ul>","<ol></ol>","<li></li>","<table></table>","<tr></tr>","<span>\\s*<span>", "<span>&nbsp;<span>", "<b>\\s*</b>", "<b>&nbsp;</b>", "<p>\\s*</p>", "<p>&nbsp;</p>", "<p>\\s*<br>\\s*</p>", "<div>\\s*</div>", "<div>\\s*<br>\\s*</div>"]; for (var i = 0; i < etags.length; ++i) { var bbb = etags[i]; html = html.replace(new RegExp(bbb,'gi'), ""); } return html; }, formattingAddBefore: function(html) { var lb = '\r\n'; var btags = ["<p", "<form","</ul>", '</ol>', "<fieldset","<legend","<object","<embed","<select","<option","<input","<textarea","<pre","<blockquote","<ul","<ol","<li","<dl","<dt","<dd","<table", "<thead","<tbody","<caption","</caption>","<th","<tr","<td","<figure"]; for (var i = 0; i < btags.length; ++i) { var eee = btags[i]; html = html.replace(new RegExp(eee,'gi'),lb+eee); } return html; }, formattingAddAfter: function(html) { var lb = '\r\n'; var atags = ['</p>', '</div>', '</h1>', '</h2>', '</h3>', '</h4>', '</h5>', '</h6>', '<br>', '<br />', '</dl>', '</dt>', '</dd>', '</form>', '</blockquote>', '</pre>', '</legend>', '</fieldset>', '</object>', '</embed>', '</textarea>', '</select>', '</option>', '</table>', '</thead>', '</tbody>', '</tr>', '</td>', '</th>', '</figure>']; for (var i = 0; i < atags.length; ++i) { var aaa = atags[i]; html = html.replace(new RegExp(aaa,'gi'),aaa+lb); } return html; }, formatting: function(html) { html = this.formattingRemove(html); // empty tags html = this.formattingEmptyTags(html); // add formatting before html = this.formattingAddBefore(html); // add formatting after html = this.formattingAddAfter(html); // indenting html = this.formattingIndenting(html); return html; }, // TOGGLE toggle: function() { var html; if (this.opts.visual) { this.$editor.hide(); html = this.$editor.html(); html = $.trim(this.formatting(html)); this.$el.height(this.$editor.innerHeight()).val(html).show().focus(); this.setBtnActive('html'); this.opts.visual = false; } else { this.$el.hide(); var html = this.stripTags(this.$el.val()); this.$editor.html(html); this.$editor.show(); if (this.$editor.html() === '') { if (!$.browser.mozilla) { html = this.opts.allEmptyHtml; } else { html = this.opts.mozillaEmptyHtml; } this.setCode(html); } this.$editor.focus(); this.setBtnInactive('html'); this.opts.visual = true; this.observeImages(); this.observeTables(); } }, // AUTOSAVE autoSave: function() { setInterval($.proxy(function() { $.ajax({ url: this.opts.autosave, type: 'post', data: this.$el.attr('name') + '=' + this.getCode(), success: $.proxy(function(data) { // callback if (typeof this.opts.autosaveCallback === 'function') { this.opts.autosaveCallback(data, this); } }, this) }); }, this), this.opts.interval*1000); }, // TOOLBAR buildToolbar: function() { if (this.opts.toolbar === false) { return false; } this.$toolbar = $('<ul>').addClass('redactor_toolbar'); if (this.opts.air) { $(this.air).append(this.$toolbar); $('body').prepend(this.air); } else { this.$box.prepend(this.$toolbar); } $.each(this.opts.buttons, $.proxy(function(i,key) { if (key !== '|' && typeof this.opts.toolbar[key] !== 'undefined') { var s = this.opts.toolbar[key]; if (this.opts.fileUpload === false && key === 'file') { return true; } var li = $('<li>'); var a = this.buildButton(key, s); // dropdown if (key === 'backcolor' || key === 'fontcolor' || typeof(s.dropdown) !== 'undefined') { var dropdown = $('<div class="redactor_dropdown" style="display: none;">'); if (key === 'backcolor' || key === 'fontcolor') { dropdown = this.buildColorPicker(dropdown, key); } else { dropdown = this.buildDropdown(dropdown, s.dropdown); } this.dropdowns.push(dropdown.appendTo($(document.body))); // observing dropdown this.hdlHideDropDown = $.proxy(function(e) { this.hideDropDown(e, dropdown, key); }, this); this.hdlShowDropDown = $.proxy(function(e) { this.showDropDown(e, dropdown, key); }, this); a.click(this.hdlShowDropDown); } this.$toolbar.append($(li).append(a)); } if (key === '|') { this.$toolbar.append($('<li class="redactor_separator"></li>')); } }, this)); $(document).click(this.hdlHideDropDown); this.$editor.click(this.hdlHideDropDown); }, buildButton: function(key, s) { var button = $('<a href="javascript:void(null);" title="' + s.title + '" class="redactor_btn_' + key + '"></a>'); if (typeof s.func === 'undefined') { button.click($.proxy(function() { this.execCommand(s.exec, key); }, this)); } else if (s.func !== 'show') { button.click($.proxy(function(e) { this[s.func](e); }, this)); } if (typeof s.callback !== 'undefined') { button.click($.proxy(function(e) { s.callback(this, e, key); }, this)); } return button; }, buildDropdown: function(dropdown, obj) { $.each(obj, $.proxy( function (x, d) { if (typeof(d.className) === 'undefined') { d.className = ''; } var drop_a; if (typeof d.name !== 'undefined' && d.name === 'separator') { drop_a = $('<a class="redactor_separator_drop">'); } else { drop_a = $('<a href="javascript:void(null);" class="' + d.className + '">' + d.title + '</a>'); if (typeof(d.func) === 'undefined') { $(drop_a).click($.proxy(function() { this.execCommand(d.exec, x); }, this)); } else { $(drop_a).click($.proxy(function(e) { this[d.func](e); }, this)); } } $(dropdown).append(drop_a); }, this) ); return dropdown; }, buildColorPicker: function(dropdown, key) { var mode; if (key === 'backcolor') { if ($.browser.msie) { mode = 'BackColor'; } else { mode = 'hilitecolor'; } } else { mode = 'forecolor'; } $(dropdown).width(210); var len = this.opts.colors.length; for (var i = 0; i < len; ++i) { var color = this.opts.colors[i]; var swatch = $('<a rel="' + color + '" href="javascript:void(null);" class="redactor_color_link"></a>').css({ 'backgroundColor': color }); $(dropdown).append(swatch); var _self = this; $(swatch).click(function() { _self.execCommand(mode, $(this).attr('rel')); if (mode === 'forecolor') { _self.$editor.find('font').replaceWith(function() { return $('<span style="color: ' + $(this).attr('color') + ';">' + $(this).html() + '</span>'); }); } if ($.browser.msie && mode === 'BackColor') { _self.$editor.find('font').replaceWith(function() { return $('<span style="' + $(this).attr('style') + '">' + $(this).html() + '</span>'); }); } }); } var elnone = $('<a href="javascript:void(null);" class="redactor_color_none"></a>').html(RLANG.none); if (key === 'backcolor') { elnone.click($.proxy(this.setBackgroundNone, this)); } else { elnone.click($.proxy(this.setColorNone, this)); } $(dropdown).append(elnone); return dropdown; }, setBackgroundNone: function() { $(this.getParentNode()).css('background-color', 'transparent'); this.syncCode(); }, setColorNone: function() { $(this.getParentNode()).attr('color', '').css('color', ''); this.syncCode(); }, // DROPDOWNS showDropDown: function(e, dropdown, key) { if (this.getBtn(key).hasClass('dropact')) { this.hideAllDropDown(); } else { this.hideAllDropDown(); this.setBtnActive(key); this.getBtn(key).addClass('dropact'); var left = this.getBtn(key).offset().left; if (this.opts.air) { var air_top = this.air.offset().top; $(dropdown).css({ position: 'absolute', left: left + 'px', top: air_top+30 + 'px' }).show(); } else if (this.opts.fixed && this.fixed) { $(dropdown).css({ position: 'fixed', left: left + 'px', top: '30px' }).show(); } else { var top = this.$toolbar.offset().top + 30; $(dropdown).css({ position: 'absolute', left: left + 'px', top: top + 'px' }).show(); } } }, hideAllDropDown: function() { this.$toolbar.find('a.dropact').removeClass('act').removeClass('dropact'); $('.redactor_dropdown').hide(); }, hideDropDown: function(e, dropdown, key) { if (!$(e.target).hasClass('dropact')) { $(dropdown).removeClass('act'); this.showedDropDown = false; this.hideAllDropDown(); } }, // SELECTION AND NODE MANIPULATION getSelection: function () { if (typeof window.getSelection !== 'undefined') { return document.getSelection(); } else if (typeof document.selection !== 'undefined') { return document.selection.createRange(); } }, getFragmentHtml: function (fragment) { var cloned = fragment.cloneNode(true); var div = document.createElement('div'); div.appendChild(cloned); return div.innerHTML; }, extractContent: function() { var node = this.$editor.get(0); var frag = document.createDocumentFragment(), child; while ((child = node.firstChild)) { frag.appendChild(child); } return frag; }, saveSelection: function() { this.savedSel = null; this.savedSelObj = null; if ($.browser.msie && parseInt($.browser.version, 10) < 9) { var node = this.$editor.get(0); this.savedSel = window.Selection.getOrigin(node); this.savedSelObj = window.Selection.getFocus(node); } else { this.savedSel = window.Selection.getOrigin(window); this.savedSelObj = window.Selection.getFocus(window); } }, restoreSelection: function() { if (this.savedSel !== null && this.savedSelObj !== null && this.savedSel[0].tagName !== 'BODY') { if ($(this.savedSel[0]).closest('.redactor_editor').size() == 0) { this.$editor.focus(); } else { window.Selection.setSelection(window, this.savedSel[0], this.savedSel[1], this.savedSelObj[0], this.savedSelObj[1]); } } else { this.$editor.focus(); } }, getParentNode: function() { if (typeof window.getSelection !== 'undefined') { var s = window.getSelection(); if (s.rangeCount > 0) { return this.getSelection().getRangeAt(0).startContainer.parentNode; } else return false; } else if (typeof document.selection !== 'undefined') { return this.getSelection().parentElement(); } }, getCurrentNode: function() { if (typeof window.getSelection !== 'undefined') { return this.getSelection().getRangeAt(0).startContainer; } else if (typeof document.selection !== 'undefined') { return this.getSelection(); } }, setFocusNode: function(node) { if (typeof node === 'undefined') { return false; } try { var range = document.createRange(); var selection = this.getSelection(); if (selection !== null) { range.selectNodeContents(node); selection.addRange(range); selection.collapse(node, 0); } this.$editor.focus(); } catch (e) { } }, insertNodeAtCaret: function (node) { if (window.getSelection) { var sel = this.getSelection(); if (sel.rangeCount) { var range = sel.getRangeAt(0); range.collapse(false); range.insertNode(node); range = range.cloneRange(); range.selectNodeContents(node); range.collapse(false); sel.removeAllRanges(); sel.addRange(range); } } else if (document.selection) { var html = (node.nodeType === 1) ? node.outerHTML : node.data; var id = "marker_" + ("" + Math.random()).slice(2); html += '<span id="' + id + '"></span>'; var textRange = this.getSelection(); textRange.collapse(false); textRange.pasteHTML(html); var markerSpan = document.getElementById(id); textRange.moveToElementText(markerSpan); textRange.select(); markerSpan.parentNode.removeChild(markerSpan); } }, getSelectedHtml: function() { var html = ''; if (window.getSelection) { var sel = window.getSelection(); if (sel.rangeCount) { var container = document.createElement("div"); for (var i = 0, len = sel.rangeCount; i < len; ++i) { container.appendChild(sel.getRangeAt(i).cloneContents()); } html = container.innerHTML; } } else if (document.selection) { if (document.selection.type === "Text") { html = document.selection.createRange().htmlText; } } return html; }, // BUTTONS MANIPULATIONS getBtn: function(key) { return $(this.$toolbar.find('a.redactor_btn_' + key)); }, setBtnActive: function(key) { this.getBtn(key).addClass('act'); }, setBtnInactive: function(key) { this.getBtn(key).removeClass('act'); }, // RESIZE IMAGES resizeImage: function(resize) { var clicked = false; var clicker = false; var start_x; var start_y; var ratio = $(resize).width()/$(resize).height(); var min_w = 10; var min_h = 10; $(resize).hover(function() { $(resize).css('cursor', 'nw-resize'); }, function() { $(resize).css('cursor','default'); clicked = false; }); $(resize).mousedown(function(e) { e.preventDefault(); ratio = $(resize).width()/$(resize).height(); clicked = true; clicker = true; start_x = Math.round(e.pageX - $(resize).eq(0).offset().left); start_y = Math.round(e.pageY - $(resize).eq(0).offset().top); }); $(resize).mouseup($.proxy(function(e) { clicked = false; this.syncCode(); }, this)); $(resize).click($.proxy(function(e) { if (clicker) { this.imageEdit(e); } }, this)); $(resize).mousemove(function(e) { if (clicked) { clicker = false; var mouse_x = Math.round(e.pageX - $(this).eq(0).offset().left) - start_x; var mouse_y = Math.round(e.pageY - $(this).eq(0).offset().top) - start_y; var div_h = $(resize).height(); var new_h = parseInt(div_h, 10) + mouse_y; var new_w = new_h*ratio; if (new_w > min_w) { $(resize).width(new_w); } if (new_h > min_h) { $(resize).height(new_h); } start_x = Math.round(e.pageX - $(this).eq(0).offset().left); start_y = Math.round(e.pageY - $(this).eq(0).offset().top); } }); }, // TABLE showTable: function() { this.saveSelection(); this.modalInit(RLANG.table, 'table', 300, $.proxy(function() { $('#redactor_insert_table_btn').click($.proxy(this.insertTable, this)); }, this), function() { $('#redactor_table_rows').focus(); } ); }, insertTable: function() { var rows = $('#redactor_table_rows').val(); var columns = $('#redactor_table_columns').val(); var table_box = $('<div></div>'); var tableid = Math.floor(Math.random() * 99999); var table = $('<table id="table' + tableid + '"><tbody></tbody></table>'); for (var i = 0; i < rows; i++) { var row = $('<tr></tr>'); for (var z = 0; z < columns; z++) { var column = $('<td><br></td>'); $(row).append(column); } $(table).append(row); } $(table_box).append(table); var html = $(table_box).html() + '<p></p>'; this.restoreSelection(); this.execCommand('inserthtml', html); this.modalClose(); this.observeTables(); }, tableObserver: function(e) { this.$table = $(e.target).closest('table'); this.$table_tr = this.$table.find('tr'); this.$table_td = this.$table.find('td'); this.$table_td.removeClass('redactor-current-td'); this.$tbody = $(e.target).closest('tbody'); this.$thead = $(this.$table).find('thead'); this.$current_td = $(e.target); this.$current_td.addClass('redactor-current-td'); this.$current_tr = $(e.target).closest('tr'); }, deleteTable: function() { $(this.$table).remove(); this.$table = false; this.syncCode(); }, deleteRow: function() { $(this.$current_tr).remove(); this.syncCode(); }, deleteColumn: function() { var index = $(this.$current_td).get(0).cellIndex; $(this.$table).find('tr').each(function() { $(this).find('td').eq(index).remove(); }); this.syncCode(); }, addHead: function() { if ($(this.$table).find('thead').size() !== 0) { this.deleteHead(); } else { var tr = $(this.$table).find('tr').first().clone(); tr.find('td').html('&nbsp;'); this.$thead = $('<thead></thead>'); this.$thead.append(tr); $(this.$table).prepend(this.$thead); this.syncCode(); } }, deleteHead: function() { $(this.$thead).remove(); this.$thead = false; this.syncCode(); }, insertRowAbove: function() { this.insertRow('before'); }, insertRowBelow: function() { this.insertRow('after'); }, insertColumnLeft: function() { this.insertColumn('before'); }, insertColumnRight: function() { this.insertColumn('after'); }, insertRow: function(type) { var new_tr = $(this.$current_tr).clone(); new_tr.find('td').html('&nbsp;'); if (type === 'after') { $(this.$current_tr).after(new_tr); } else { $(this.$current_tr).before(new_tr); } this.syncCode(); }, insertColumn: function(type) { var index = 0; this.$current_td.addClass('redactor-current-td'); this.$current_tr.find('td').each(function(i,s) { if ($(s).hasClass('redactor-current-td')) { index = i; } }); this.$table_tr.each(function(i,s) { var current = $(s).find('td').eq(index); var td = current.clone(); td.html('&nbsp;'); if (type === 'after') { $(current).after(td); } else { $(current).before(td); } }); this.syncCode(); }, // INSERT VIDEO showVideo: function() { this.saveSelection(); this.modalInit(RLANG.video, 'video', 600, $.proxy(function() { $('#redactor_insert_video_btn').click($.proxy(this.insertVideo, this)); }, this), function() { $('#redactor_insert_video_area').focus(); } ); }, insertVideo: function() { var data = $('#redactor_insert_video_area').val(); data = this.stripTags(data); this.restoreSelection(); this.execCommand('inserthtml', data); this.modalClose(); }, // INSERT IMAGE imageEdit: function(e) { var $el = $(e.target); var parent = $el.parent(); var handler = $.proxy(function() { $('#redactor_file_alt').val($el.attr('alt')); $('#redactor_image_edit_src').attr('href', $el.attr('src')); $('#redactor_form_image_align').val($el.css('float')); if ($(parent).get(0).tagName === 'A') { $('#redactor_file_link').val($(parent).attr('href')); } $('#redactor_image_delete_btn').click($.proxy(function() { this.imageDelete($el); }, this)); $('#redactorSaveBtn').click($.proxy(function() { this.imageSave($el); }, this)); }, this); this.modalInit(RLANG.image, 'image_edit', 380, handler); }, imageDelete: function(el) { $(el).remove(); this.modalClose(); this.syncCode(); }, imageSave: function(el) { var parent = $(el).parent(); $(el).attr('alt', $('#redactor_file_alt').val()); var floating = $('#redactor_form_image_align').val(); if (floating === 'left') { $(el).css({ 'float': 'left', margin: '0 10px 10px 0' }); } else if (floating === 'right') { $(el).css({ 'float': 'right', margin: '0 0 10px 10px' }); } else { $(el).css({ 'float': 'none', margin: '0' }); } // as link var link = $.trim($('#redactor_file_link').val()); if (link !== '') { if ($(parent).get(0).tagName !== 'A') { $(el).replaceWith('<a href="' + link + '">' + this.outerHTML(el) + '</a>'); } else { $(parent).attr('href', link); } } else { if ($(parent).get(0).tagName === 'A') { $(parent).replaceWith(this.outerHTML(el)); } } this.modalClose(); this.observeImages(); this.syncCode(); }, showImage: function() { this.saveSelection(); var handler = $.proxy(function() { // json if (this.opts.imageGetJson !== false) { $.getJSON(this.opts.imageGetJson, $.proxy(function(data) { var folders = {}; var z = 0; // folders $.each(data, $.proxy(function(key, val) { if (typeof val.folder !== 'undefined') { z++; folders[val.folder] = z; } }, this)); var folderclass = false; $.each(data, $.proxy(function(key, val) { // title var thumbtitle = ''; if (typeof val.title !== 'undefined') { thumbtitle = val.title; } var folderkey = 0; if (!$.isEmptyObject(folders) && typeof val.folder !== 'undefined') { folderkey = folders[val.folder]; if (folderclass === false) { folderclass = '.redactorfolder' + folderkey; } } var img = $('<img src="' + val.thumb + '" class="redactorfolder redactorfolder' + folderkey + '" rel="' + val.image + '" title="' + thumbtitle + '" />'); $('#redactor_image_box').append(img); $(img).click($.proxy(this.imageSetThumb, this)); }, this)); // folders if (!$.isEmptyObject(folders)) { $('.redactorfolder').hide(); $(folderclass).show(); var onchangeFunc = function(e) { $('.redactorfolder').hide(); $('.redactorfolder' + $(e.target).val()).show(); } var select = $('<select id="redactor_image_box_select">'); $.each(folders, function(k,v) { select.append($('<option value="' + v + '">' + k + '</option>')); }); $('#redactor_image_box').before(select); select.change(onchangeFunc); } }, this)); } else { $('#redactor_tabs a').eq(1).remove(); } if (this.opts.imageUpload !== false) { // dragupload if (this.opts.uploadCrossDomain === false && this.isMobile() === false) { if ($('#redactor_file').size() !== 0) { $('#redactor_file').dragupload( { url: this.opts.imageUpload, uploadFields: this.opts.uploadFields, success: $.proxy(this.imageUploadCallback, this) }); } } // ajax upload this.uploadInit('redactor_file', { auto: true, url: this.opts.imageUpload, success: $.proxy(this.imageUploadCallback, this) }); } else { $('.redactor_tab').hide(); if (this.opts.imageGetJson === false) { $('#redactor_tabs').remove(); $('#redactor_tab3').show(); } else { var tabs = $('#redactor_tabs a'); tabs.eq(0).remove(); tabs.eq(1).addClass('redactor_tabs_act'); $('#redactor_tab2').show(); } } $('#redactor_upload_btn').click($.proxy(this.imageUploadCallbackLink, this)); }, this); var endCallback = $.proxy(function() { if (this.opts.imageUpload === false && this.opts.imageGetJson === false) { $('#redactor_file_link').focus(); } }, this); this.modalInit(RLANG.image, 'image', 570, handler, endCallback, true); }, imageSetThumb: function(e) { this._imageSet('<img src="' + $(e.target).attr('rel') + '" alt="' + $(e.target).attr('title') + '" />', true); }, imageUploadCallbackLink: function() { if ($('#redactor_file_link').val() !== '') { var data = '<img src="' + $('#redactor_file_link').val() + '" />'; this._imageSet(data, true); } else { this.modalClose(); } }, imageUploadCallback: function(data) { this._imageSet(data); }, _imageSet: function(json, link) { this.restoreSelection(); if (json !== false) { var html = '', data = ''; if (link !== true) { data = $.parseJSON(json); html = '<p><img src="' + data.filelink + '" /></p>'; } else { html = json; } this.execCommand('inserthtml', html); // upload image callback if (link !== true && typeof this.opts.imageUploadCallback === 'function') { this.opts.imageUploadCallback(this, data); } } this.modalClose(); this.observeImages(); }, // INSERT LINK showLink: function() { this.saveSelection(); var handler = $.proxy(function() { this.insert_link_node = false; var sel = this.getSelection(); var url = '', text = '', target = ''; if ($.browser.msie) { var parent = this.getParentNode(); if (parent.nodeName === 'A') { this.insert_link_node = $(parent); text = this.insert_link_node.text(); url = this.insert_link_node.attr('href'); target = this.insert_link_node.attr('target'); } else { if (this.oldIE()) { text = sel.text; } else { text = sel.toString(); } } } else { if (sel && sel.anchorNode && sel.anchorNode.parentNode.tagName === 'A') { url = sel.anchorNode.parentNode.href; text = sel.anchorNode.parentNode.text; target = sel.anchorNode.parentNode.target; if (sel.toString() === '') { this.insert_link_node = sel.anchorNode.parentNode; } } else { text = sel.toString(); } } $('.redactor_link_text').val(text); var turl = url.replace(self.location.href, ''); if (url.search('mailto:') === 0) { this.setModalTab(2); $('#redactor_tab_selected').val(2); $('#redactor_link_mailto').val(url.replace('mailto:', '')); } else if (turl.search(/^#/gi) === 0) { this.setModalTab(3); $('#redactor_tab_selected').val(3); $('#redactor_link_anchor').val(turl.replace(/^#/gi, '')); } else { $('#redactor_link_url').val(url); } if (target === '_blank') { $('#redactor_link_blank').attr('checked', true); } $('#redactor_insert_link_btn').click($.proxy(this.insertLink, this)); }, this); var endCallback = function(url) { $('#redactor_link_url').focus(); }; this.modalInit(RLANG.link, 'link', 460, handler, endCallback); }, insertLink: function() { var tab_selected = $('#redactor_tab_selected').val(); var link = '', text = '', target = ''; if (tab_selected === '1') // url { link = $('#redactor_link_url').val(); text = $('#redactor_link_url_text').val(); if ($('#redactor_link_blank').attr('checked')) { target = '_blank'; } // test http var re = new RegExp('^https?://', 'i'); if (link.search(re) == -1) { link = this.opts.protocol + link; } } else if (tab_selected === '2') // mailto { link = 'mailto:' + $('#redactor_link_mailto').val(); text = $('#redactor_link_mailto_text').val(); } else if (tab_selected === '3') // anchor { link = '#' + $('#redactor_link_anchor').val(); text = $('#redactor_link_anchor_text').val(); } this._insertLink('<a href="' + link + '" target="' + target + '">' + text + '</a>&nbsp;', $.trim(text), link, target); }, _insertLink: function(a, text, link, target) { this.$editor.focus(); this.restoreSelection(); if (text !== '') { if (this.insert_link_node) { $(this.insert_link_node).text(text); $(this.insert_link_node).attr('href', link); if (target !== '') { $(this.insert_link_node).attr('target', target); } this.syncCode(); } else { this.execCommand('inserthtml', a); } } this.modalClose(); }, // INSERT FILE showFile: function() { this.saveSelection(); var handler = $.proxy(function() { var sel = this.getSelection(); var text = ''; if (this.oldIE()) { text = sel.text; } else { text = sel.toString(); } $('#redactor_filename').val(text); // dragupload if (this.opts.uploadCrossDomain === false && this.isMobile() === false) { $('#redactor_file').dragupload( { url: this.opts.fileUpload, uploadFields: this.opts.uploadFields, success: $.proxy(function(data) { this.fileUploadCallback(data); }, this) }); } this.uploadInit('redactor_file', { auto: true, url: this.opts.fileUpload, success: $.proxy(function(data) { this.fileUploadCallback(data); }, this)}); }, this); this.modalInit(RLANG.file, 'file', 500, handler); }, fileUploadCallback: function(json) { this.restoreSelection(); if (json !== false) { var data = $.parseJSON(json); var text = $('#redactor_filename').val(); if (text === '') { text = data.filename; } var link = '<a href="' + data.filelink + '">' + text + '</a>'; // chrome fix if ($.browser.webkit && !!window.chrome) { link = link + '&nbsp;'; } this.execCommand('inserthtml', link); // file upload callback if (typeof this.opts.fileUploadCallback === 'function') { this.opts.fileUploadCallback(this, data); } } this.modalClose(); }, // MODAL modalInit: function(title, url, width, handler, endCallback) { // modal overlay if ($('#redactor_modal_overlay').size() === 0) { this.overlay = $('<div id="redactor_modal_overlay" style="display: none;"></div>'); $('body').prepend(this.overlay); } if (this.opts.overlay) { $('#redactor_modal_overlay').show(); $('#redactor_modal_overlay').click($.proxy(this.modalClose, this)); } if ($('#redactor_modal').size() === 0) { this.modal = $('<div id="redactor_modal" style="display: none;"><div id="redactor_modal_close">&times;</div><div id="redactor_modal_header"></div><div id="redactor_modal_inner"></div></div>'); $('body').append(this.modal); } $('#redactor_modal_close').click($.proxy(this.modalClose, this)); this.hdlModalClose = $.proxy(function(e) { if ( e.keyCode === 27) { this.modalClose(); } }, this); $(document).keyup(this.hdlModalClose); this.$editor.keyup(this.hdlModalClose); $('#redactor_modal_inner').html(this.opts['modal_' + url]); $('#redactor_modal_header').html(title); // tabs if ($('#redactor_tabs').size() !== 0) { var that = this; $('#redactor_tabs a').each(function(i,s) { i++; $(s).click(function() { $('#redactor_tabs a').removeClass('redactor_tabs_act'); $(this).addClass('redactor_tabs_act'); $('.redactor_tab').hide(); $('#redactor_tab' + i).show(); $('#redactor_tab_selected').val(i); if (that.isMobile() === false) { var height = $('#redactor_modal').outerHeight(); $('#redactor_modal').css('margin-top', '-' + (height+10)/2 + 'px'); } }); }); } $('#redactor_btn_modal_close').click($.proxy(this.modalClose, this)); // callback if (typeof(handler) === 'function') { handler(); } // setup var height = $('#redactor_modal').outerHeight(); if (this.isMobile() === false) { $('#redactor_modal').css({ position: 'fixed', top: '50%', left: '50%', width: width + 'px', height: 'auto', minHeight: 'auto', marginTop: '-' + (height+10)/2 + 'px', marginLeft: '-' + (width+60)/2 + 'px' }).fadeIn('fast'); this.modalSaveBodyOveflow = $(document.body).css('overflow'); $(document.body).css('overflow', 'hidden'); } else { $('#redactor_modal').css({ position: 'fixed', width: '100%', height: '100%', top: '0', left: '0', margin: '0', minHeight: '300px' }).show(); } // end callback if (typeof(endCallback) === 'function') { endCallback(); } }, modalClose: function() { $('#redactor_modal_close').unbind('click', this.modalClose); $('#redactor_modal').fadeOut('fast', $.proxy(function() { $('#redactor_modal_inner').html(''); if (this.opts.overlay) { $('#redactor_modal_overlay').hide(); $('#redactor_modal_overlay').unbind('click', this.modalClose); } $(document).unbind('keyup', this.hdlModalClose); this.$editor.unbind('keyup', this.hdlModalClose); }, this)); if (this.isMobile() === false) { $(document.body).css('overflow', this.modalSaveBodyOveflow); } }, setModalTab: function(num) { $('.redactor_tab').hide(); var tabs = $('#redactor_tabs a'); tabs.removeClass('redactor_tabs_act'); tabs.eq(num-1).addClass('redactor_tabs_act'); $('#redactor_tab' + num).show(); }, // UPLOAD uploadInit: function(element, options) { // Upload Options this.uploadOptions = { url: false, success: false, start: false, trigger: false, auto: false, input: false }; $.extend(this.uploadOptions, options); // Test input or form if ($('#' + element).size() !== 0 && $('#' + element).get(0).tagName === 'INPUT') { this.uploadOptions.input = $('#' + element); this.element = $($('#' + element).get(0).form); } else { this.element = $('#' + element); } this.element_action = this.element.attr('action'); // Auto or trigger if (this.uploadOptions.auto) { $(this.uploadOptions.input).change($.proxy(function() { this.element.submit(function(e) { return false; }); this.uploadSubmit(); }, this)); } else if (this.uploadOptions.trigger) { $('#' + this.uploadOptions.trigger).click($.proxy(this.uploadSubmit, this)); } }, uploadSubmit : function() { this.uploadForm(this.element, this.uploadFrame()); }, uploadFrame : function() { this.id = 'f' + Math.floor(Math.random() * 99999); var d = document.createElement('div'); var iframe = '<iframe style="display:none" id="'+this.id+'" name="'+this.id+'"></iframe>'; d.innerHTML = iframe; document.body.appendChild(d); // Start if (this.uploadOptions.start) { this.uploadOptions.start(); } $('#' + this.id).load($.proxy(this.uploadLoaded, this)); return this.id; }, uploadForm : function(f, name) { if (this.uploadOptions.input) { var formId = 'redactorUploadForm' + this.id; var fileId = 'redactorUploadFile' + this.id; this.form = $('<form action="' + this.uploadOptions.url + '" method="POST" target="' + name + '" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); // append hidden fields if (this.opts.uploadFields !== false && typeof this.opts.uploadFields === 'object') { $.each(this.opts.uploadFields, $.proxy(function(k,v) { if (v.indexOf('#') === 0) { v = $(v).val(); } var hidden = $('<input type="hidden" name="' + k + '" value="' + v + '">'); $(this.form).append(hidden); }, this)); } var oldElement = this.uploadOptions.input; var newElement = $(oldElement).clone(); $(oldElement).attr('id', fileId); $(oldElement).before(newElement); $(oldElement).appendTo(this.form); $(this.form).css('position', 'absolute'); $(this.form).css('top', '-2000px'); $(this.form).css('left', '-2000px'); $(this.form).appendTo('body'); this.form.submit(); } else { f.attr('target', name); f.attr('method', 'POST'); f.attr('enctype', 'multipart/form-data'); f.attr('action', this.uploadOptions.url); this.element.submit(); } }, uploadLoaded : function() { var i = $('#' + this.id); var d; if (i.contentDocument) { d = i.contentDocument; } else if (i.contentWindow) { d = i.contentWindow.document; } else { d = window.frames[this.id].document; } // Success if (this.uploadOptions.success) { if (typeof d !== 'undefined') { // Remove bizarre <pre> tag wrappers around our json data: var rawString = d.body.innerHTML; var jsonString = rawString.match(/\{.*\}/)[0]; this.uploadOptions.success(jsonString); } else { alert('Upload failed!'); this.uploadOptions.success(false); } } this.element.attr('action', this.element_action); this.element.attr('target', ''); }, // UTILITY oldIE: function() { if ($.browser.msie && parseInt($.browser.version, 10) < 9) { return true; } return false; }, outerHTML: function(s) { return $("<p>").append($(s).eq(0).clone()).html(); }, normalize: function(str) { return parseInt(str.replace('px',''), 10); }, isMobile: function(ipad) { if (ipad === true && /(iPhone|iPod|iPad|BlackBerry|Android)/.test(navigator.userAgent)) { return true; } else if (/(iPhone|iPod|BlackBerry|Android)/.test(navigator.userAgent)) { return true; } else { return false; } } }; // API $.fn.getEditor = function() { return this.data('redactor').$editor; }; $.fn.getCode = function() { return this.data('redactor').getCode(); }; $.fn.getText = function() { return this.data('redactor').$editor.text(); }; $.fn.getSelected = function() { return this.data('redactor').getSelectedHtml(); }; $.fn.setCode = function(html) { this.data('redactor').setCode(html); }; $.fn.insertHtml = function(html) { this.data('redactor').insertHtml(html); }; $.fn.destroyEditor = function() { this.data('redactor').destroy(); this.removeData('redactor'); }; $.fn.setFocus = function() { this.data('redactor').$editor.focus(); }; $.fn.execCommand = function(cmd, param) { this.data('redactor').execCommand(cmd, param); }; })(jQuery); /* Plugin Drag and drop Upload v1.0.2 http://imperavi.com/ Copyright 2012, Imperavi Inc. */ (function($){ "use strict"; // Initialization $.fn.dragupload = function(options) { return this.each(function() { var obj = new Construct(this, options); obj.init(); }); }; // Options and variables function Construct(el, options) { this.opts = $.extend({ url: false, success: false, preview: false, uploadFields: false, text: RLANG.drop_file_here, atext: RLANG.or_choose }, options); this.$el = $(el); } // Functionality Construct.prototype = { init: function() { if (!$.browser.msie) { this.droparea = $('<div class="redactor_droparea"></div>'); this.dropareabox = $('<div class="redactor_dropareabox">' + this.opts.text + '</div>'); this.dropalternative = $('<div class="redactor_dropalternative">' + this.opts.atext + '</div>'); this.droparea.append(this.dropareabox); this.$el.before(this.droparea); this.$el.before(this.dropalternative); // drag over this.dropareabox.bind('dragover', $.proxy(function() { return this.ondrag(); }, this)); // drag leave this.dropareabox.bind('dragleave', $.proxy(function() { return this.ondragleave(); }, this)); var uploadProgress = $.proxy(function(e) { var percent = parseInt(e.loaded / e.total * 100, 10); this.dropareabox.text('Loading ' + percent + '%'); }, this); var xhr = jQuery.ajaxSettings.xhr(); if (xhr.upload) { xhr.upload.addEventListener('progress', uploadProgress, false); } var provider = function () { return xhr; }; // drop this.dropareabox.get(0).ondrop = $.proxy(function(event) { event.preventDefault(); this.dropareabox.removeClass('hover').addClass('drop'); var file = event.dataTransfer.files[0]; var fd = new FormData(); // append hidden fields if (this.opts.uploadFields !== false && typeof this.opts.uploadFields === 'object') { $.each(this.opts.uploadFields, $.proxy(function(k,v) { if (v.indexOf('#') === 0) { v = $(v).val(); } fd.append(k, v); }, this)); } // append file data fd.append('file', file); $.ajax({ dataType: 'html', url: this.opts.url, data: fd, xhr: provider, cache: false, contentType: false, processData: false, type: 'POST', success: $.proxy(function(data) { if (this.opts.success !== false) { this.opts.success(data); } if (this.opts.preview === true) { this.dropareabox.html(data); } }, this) }); }, this); } }, ondrag: function() { this.dropareabox.addClass('hover'); return false; }, ondragleave: function() { this.dropareabox.removeClass('hover'); return false; } }; })(jQuery); // Define: Linkify plugin from stackoverflow (function($){ "use strict"; var protocol = 'http://'; var url1 = /(^|&lt;|\s)(www\..+?\..+?)(\s|&gt;|$)/g, url2 = /(^|&lt;|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|&gt;|$)/g, linkifyThis = function () { var childNodes = this.childNodes, i = childNodes.length; while(i--) { var n = childNodes[i]; if (n.nodeType === 3) { var html = n.nodeValue; if (html) { html = html.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(url1, '$1<a href="' + protocol + '$2">$2</a>$3') .replace(url2, '$1<a href="$2">$2</a>$5'); $(n).after(html).remove(); } } else if (n.nodeType === 1 && !/^(a|button|textarea)$/i.test(n.tagName)) { linkifyThis.call(n); } } }; $.fn.linkify = function () { this.each(linkifyThis); }; })(jQuery); /* jQuery plugin textselect * version: 0.9 * author: Josef Moravec, josef.moravec@gmail.com * updated: Imperavi Inc. * */ (function($){$.event.special.textselect={setup:function(data,namespaces){$(this).data("textselected",false);$(this).data("ttt",data);$(this).bind('mouseup',$.event.special.textselect.handler)},teardown:function(data){$(this).unbind('mouseup',$.event.special.textselect.handler)},handler:function(event){var data=$(this).data("ttt");var text=$.event.special.textselect.getSelectedText(data).toString();if(text!=''){$(this).data("textselected",true);event.type="textselect";event.text=text;$.event.handle.apply(this,arguments)}},getSelectedText:function(data){var text='';if(window.getSelection)text=window.getSelection();else if(document.getSelection) text=document.getSelection();else if(document.selection)text=document.selection.createRange().text;return text}};$.event.special.textunselect={setup:function(data,namespaces){$(this).data("rttt",data);$(this).data("textselected",false);$(this).bind('mouseup',$.event.special.textunselect.handler);$(this).bind('keyup',$.event.special.textunselect.handlerKey)},teardown:function(data){$(this).unbind('mouseup',$.event.special.textunselect.handler)},handler:function(event){if($(this).data("textselected")){var data=$(this).data("rttt");var text=$.event.special.textselect.getSelectedText(data).toString();if(text==''){$(this).data("textselected",false);event.type="textunselect";$.event.handle.apply(this,arguments)}}},handlerKey:function(event){if($(this).data("textselected")){var data=$(this).data("rttt");var text=$.event.special.textselect.getSelectedText(data).toString();if((event.keyCode=27)&&(text=='')){$(this).data("textselected",false);event.type="textunselect";$.event.handle.apply(this,arguments)}}}}})(jQuery);
JavaScript
/** * This script contains the grid control. * The plugin should be applied to a DIV element. * Grid table will be built inside this element. * The options object should be specified in the followingi format: * { * columns: [ * {title: 'Id', field: 'id', type: 'text', width: '170'}, * {title: 'Name', field: 'name', type: 'text', width: '170'} * ], * data: [ * [1, "First row"] * [2, {display: "Second row", value: any_custom_data}] * ], * scrollable: true, * allowAutoRowAdding: false, * sortable: true, * scrollable: true, * name: 'myGrid' // This value will be use in hidden input names. * } * The "type" property of column specifies a column editor to be used for the column. * The "data" property is not required. However if the data is not provided, the DOM element * the plugin is applied to should contain a table markup with THEAD and TBODY elements. Head columns * should match the data provided in the "columns" property. If the table already exists, the "data" * element is ignored. Cells can contain a hidden input element with the "cell-value" class. * See jquery.backend.grid.editors.js for the list of supported editors. * The editor class name is calculated as the column type name + "Editor", so that * "text" is converted to "textEditor". */ (function( $, undefined ) { jQuery.widget( "ui.grid", { options: { allowAutoRowAdding: true, name: 'grid', dataFieldName: null, sortable: false, scrollable: false, scrollableViewportClass: null, rowsDeletable: false, deleteRowMessage: 'Do you really want to delete this row?', useDataSource: false, focusFirst: false }, /** * Updates table column widths. */ alignColumns: function(row) { if (this.options.useDataSource) return; var widths = [], self = this; this.headTable.find('th div.ui-grid-head-content').each(function(index, div){ widths.push(jQuery(div).outerWidth()); }); if (row === undefined) { this.bodyTable.find('tr:first-child').each(function(rowIndex, row) { $(row).find('td').each(function(index, td) { if (index < (widths.length-1)) { var tweak = 0, $td = jQuery(td); if (Browser.Engine.webkit && !self.isChrome && index > 0) tweak = 1; $td.css('width', (widths[index] + tweak) + 'px'); $td.find('span.cell-content').css('width', (widths[index] + tweak - 18) + 'px'); } }); }) } else { row.find('td').each(function(index, td) { if (index < (widths.length-1)) { var tweak = 0; if (Browser.Engine.webkit && index > 0) tweak = 1; jQuery(td).css('width', (widths[index] + tweak) + 'px'); } }) } }, /** * Adds new row to the table. * @param array data Optional data array. If the second parameter is required, pass false to this parameter. * @param string position Specifies the new row position. * Possible values: 'top', 'bottom', 'above', 'below'. 'bottom' is the default value. */ addRow: function(data, position) { if (!this.options.allowAutoRowAdding) return null; if (this._isNoSearchResults()) return false; var position = position === undefined ? 'bottom' : position; if (data == undefined || data === false) { data = []; for (var index=0; index<this.options.columns.length; index++) data.push(''); } var row = this._buildRow(data, position), offset = 'bottom'; if (position == 'top') offset = 'top'; else if (position == 'above' || position == 'below') { if (this.currentRow === undefined || !this.currentRow[0].parentNode) offset = 'bottom'; else offset = 'relative'; } this.alignColumns(row); if (!this.options.useDataSource) this._updateScroller(offset); this._fixBottomBorder(); this._assignRowEventHandlers(row); this._setCurrentRow(jQuery(row)); if (this.options.useDataSource) { var recordCount = parseInt(this.element.find('.pagination .row_count').text()); if (recordCount != NaN) this.element.find('.pagination .row_count').text(recordCount+1); } return row; }, /** * Deletes a current row */ deleteRow: function() { if (!this.currentRow) return false; var currentPage = 0, row = this.currentRow; if (self.options.useDataSource) currentPage = self._getCurrentPage(); var cell = this.currentRow.find('td:first'), rowIndex = this.bodyTable.children('tr').index(this.currentRow), cellIndex = this.currentRow.children('td').index(cell); if (cell.length && !this.options.useDataSource) this._navigateUp(cell); self._deleteRow(row, true, function(){ if (self.options.useDataSource) { if (cell) { var row = (currentPage == self._getCurrentPage()) ? self.bodyTable.find('tr:eq('+rowIndex+')') : self.bodyTable.find('tr:last'); if (!row.length) row = self.bodyTable.find('tr:last'); if (row.length) { self._initRow(row) row.find('td:eq('+cellIndex+')').trigger('navigateTo'); } } } }); }, appendRow: function(currentCell, ev) { var self = this; if (!this.options.useDataSource) return false; if (self.disableRowAdding !== undefined && self.disableRowAdding) return false; this._hideEditors(); var cell = currentCell !== undefined ? currentCell : ((ev !== undefined && ev.target !== undefined) ? jQuery(ev.target).closest('table.ui-grid-body tr td') : null); var index = (cell && cell !== null && cell.length) ? cell.parent().children('td').index(cell) : 0; self._createRowInTheEnd(function(nextRow){ if (!nextRow.length) return; self._initRow(nextRow); if (index !== null) nextRow.find('td:eq('+index+')').trigger('navigateTo', ['left']); }); return true; }, rebuild: function() { this._build(); }, focusFirst: function() { if (this._hasRows()) { var firstRow = this.bodyTable.find('tr:first'); this._initRow(firstRow); window.setTimeout(function(){ firstRow.find('td.ui-grid-cell-navigatable:first').trigger('navigateTo'); }, 100); } }, _create: function() { jQuery(this.element).data('ui.grid', this); this.isChrome = jQuery('body').hasClass('chrome'); this._build(); this.dragStarted = false; var self = this; jQuery(window).bind('phpr_widget_response_data', function(event, data){ self._handleWidgetResponseData(data); }); }, _build: function() { if (this.options.columns === undefined) { this._trace('Data grid has no columns. Exiting.'); return; } if (this.element.find('input.grid-table-disabled').length) { if (this.headTable !== undefined && this.headTable && !this.options.useDataSource) this.headTable.remove(); return; } this.element.addClass('ui-grid'); this.existingTable = this.element.find('table'); this.actionName = this.element.find('input.grid-event-handler-name').attr('value'); if (this.options.useDataSource) this.container = this.element.find('.ui-grid-table-container'); this._buildHead(); this._buildBody(); if (this.options.useDataSource && this.built === undefined) { var columnGroupsTitleHeight = this.headTable.find('.ui-column-group-row').height(); if (columnGroupsTitleHeight > 0) columnGroupsTitleHeight += 1; this.container.css('height', (this.bodyTable.find('tr:first').height()*(this.options.pageSize+1)+2)+columnGroupsTitleHeight+'px'); var scroller = this.element.find('.ui-grid-h-scroll'); scroller.scrollLeft(0); this._bindSearch(); } if (!this.options.useDataSource) { this.alignColumns(); var self = this; window.setTimeout(function(){ self._updateScroller(); }, 200); jQuery(window).bind('resize', function(){ self.alignColumns(); }); } if (this.built === undefined && this.options.focusFirst) this.focusFirst(); this.built = true; }, _updateScroller: function(direction){ if (this.options.scrollable) this.scroller.update(direction); }, _buildHead: function() { if (!this.options.useDataSource) { this.headTable = jQuery('<table class="ui-grid-head"></table>'); var row = jQuery('<tr></tr>') this.headTable.append(jQuery('<thead></thead>').append(row)); jQuery.each(this.options.columns, function(index, columnData){ var cell = jQuery('<th></th>'), content = jQuery('<div class="ui-grid-head-content"></div>'); cell.append(content); content.text(columnData.title); if (columnData.width !== undefined) cell.css('width', columnData.width + 'px'); if (columnData.align !== undefined) cell.addClass(columnData.align); row.append(cell); }); this.element.find('table').find('thead').remove(); this.element.prepend(this.headTable); } else this.headTable = this.element.find('table').find('thead'); if (this.built === undefined) this._initHeaderCheckboxes(); }, _buildBody: function() { var self = this; this.bodyTable = this.existingTable.length ? this.existingTable.find('tbody') : jQuery('<table class="ui-grid-body"></table>'); if (!this.existingTable.length) { jQuery.each(this.options.data, function(rowIndex, rowData) { self._buildRow(rowData); }); } else { this.bodyTable.addClass('ui-grid-body'); if (!this.options.useDataSource || this.built === undefined) this.bodyTable.bind('mouseover', function(ev){ if (ev.target !== undefined) self._initRow(jQuery(ev.target).closest('tr')); }); } if (this.options.scrollable) { this.scrollablePanel = this.element.find('div.backend_scroller'); this.scroller = new BackendVScroller(this.scrollablePanel[0], { slider_height_tweak: 0, auto_hide_slider: true, position_threshold: 9 }); this.viewport = this.scrollablePanel; this.overview = this.bodyTable; this.scrollablePanel.bind('onScroll', function(){ self._hideRowMenu(); self._hideEditors(); }); this.scrollablePanel.bind('onBeforeWheel', function(event){ if (self._scrollingPaused !== undefined && self._scrollingPaused) event.preventDefault(); }); } else this.headTable.after(this.bodyTable); if ((!this.options.useDataSource || this.built === undefined) && !this._hasRows()) this.addRow(); this._assignRowEventHandlers(); if (this.options.sortable) { this.dragging = false; this.bodyTable.addClass('ui-grid-draggable'); jQuery(document).bind('mousemove', function(event){self._mouseMove(event);}); jQuery(document).bind('mouseup', function(event){self._mouseUp(event);}); } if (this.built === undefined) { this.bodyTable.bind('mouseleave', function(event){ self._hideRowMenu(event); }) this._assignBodyEventHandlers(); this._assignDocumentHandlers(); } this._fixBottomBorder(); }, _buildRow: function(rowData, position) { var row = jQuery('<tr></tr>'), self = this, position = position === undefined ? 'bottom' : position; this.rowsAdded = this.rowsAdded === undefined ? 1 : this.rowsAdded+1; jQuery.each(rowData, function(cellIndex, cellData){ var cell = jQuery('<td></td>').data('ui.grid', self); self._getColumnEditor(cellIndex).initContent(cell, cellData, row, cellIndex, self.options.columns[cellIndex], -1*self.rowsAdded); row[0].rowDataIndex = -1*self.rowsAdded; if (self.options.columns[cellIndex].align !== undefined) cell.addClass(self.options.columns[cellIndex].align); if (self.options.columns[cellIndex].cell_css_class !== undefined) cell.addClass(self.options.columns[cellIndex].cell_css_class); if (self.options.rowsDeletable && rowData.length == cellIndex+1) self._createRowMenu(row, cell); if (self.options.columns[cellIndex].default_text !== undefined) cell.find('span.cell-content').text(self.options.columns[cellIndex].default_text); row.append(cell); }); row[0].grid_initialized = true; if (position == 'bottom') self.bodyTable.append(row); else if (position == 'top') self.bodyTable.prepend(row); else if (position == 'above' || position == 'below') { if (self.currentRow === undefined || !self.currentRow[0].parentNode) self.bodyTable.append(row); else { if (position == 'above') row.insertBefore(self.currentRow); else row.insertAfter(self.currentRow); } } this._markRowSearchUpdated(-1*self.rowsAdded); return row; }, _fixBottomBorder: function() { if (this.options.scrollable) { if (this.viewport.height() > this.overview[0].offsetHeight) this.bodyTable.closest('table').removeClass('no-bottom-border'); else this.bodyTable.closest('table').addClass('no-bottom-border'); } else if (this.options.useDataSource) { if (this.bodyTable.find('tr').length == this.options.pageSize) this.bodyTable.closest('table').addClass('no-bottom-border'); else this.bodyTable.closest('table').removeClass('no-bottom-border'); } }, _hasRows: function() { var tbody = this.bodyTable[0].tagName == 'TBODY' ? this.bodyTable : this.bodyTable.find('tbody'), i = 0; if (!tbody.length) return false; for (i=0; i< tbody[0].childNodes.length; i++) if (tbody[0].childNodes[i].nodeName == 'TR') return true; return false; }, _initRow: function(row) { if (row[0].grid_initialized !== undefined && row[0].grid_initialized) return; row[0].grid_initialized = true; var block_delete_input = row.find('input.block_delete_message'); if (block_delete_input.length && block_delete_input.val() != '') row[0].block_delete_message = block_delete_input.val(); var cells = row.find('td'), self = this; $.each(cells, function(cellIndex, cellElement){ var cell = jQuery(cellElement), valueInput = cell.find('input.cell-value'), internalInput = cell.find('input.internal-value'), rowDataIndex = cell.find('input.row-index').val(), cellData = { display: cell.text().trim(), value: valueInput.length ? valueInput.attr('value') : cell.text(), internal: internalInput.val() }; cell.data('ui.grid', self); cell.text(''); row[0].rowDataIndex = rowDataIndex; self._getColumnEditor(cellIndex).initContent(cell, cellData, row, cellIndex, self.options.columns[cellIndex], rowDataIndex); if (self.options.rowsDeletable && cells.length == cellIndex+1) self._createRowMenu(row, cell); }); }, _createRowMenu: function(row, cell) { var contentContainer = cell.find('.cell-content-container'); menu = jQuery('<span class="ui-grid-menu"></span>'), self = this, deleteLink = jQuery('<a class="menu-delete">Delete</a>').attr('tabindex', 0).bind('click', function(ev){ ev.stopImmediatePropagation(); self._deleteRow(row); return false; }); menu.append(deleteLink); contentContainer.append(menu); }, _assignRowEventHandlers: function(row) { if (this.options.sortable || this.options.rowsDeletable) { if (row === undefined) row = this.bodyTable.find('tr'); var self = this; if (this.options.sortable) { row.bind('mousedown', function(event){ self._dragStart(event); }); } if (this.options.rowsDeletable) { row.bind('mouseenter', function(event){self._rowMouseEnter(event);}); row.bind('mouseleave', function(event){self._rowMouseLeave(event);}); } } }, _assignDocumentHandlers: function() { var self = this; jQuery(document).bind('keydown.grid', function(ev){ return self._handleGridKeys(ev); }) }, _handleGridKeys: function(ev) { var self = this; if (self.options.useDataSource) { if (self.element.closest('html').length == 0) return; if ((ev.metaKey || ev.ctrlKey) && ev.keyCode == 73) { if (self.appendRow(null, ev)) { ev.preventDefault(); return false; } } } }, _assignBodyEventHandlers: function() { var self = this; this.bodyTable.bind('keydown', function(ev){ if (ev.keyCode == 9) { if (self._isNoSearchResults()) return false; if (ev.target !== undefined && jQuery(ev.target).hasClass('cell-content-container')) { if (!ev.shiftKey) self._navigateRight(jQuery(ev.target).parent(), false); else self._navigateLeft(jQuery(ev.target).parent(), false); ev.preventDefault(); return false; } } if ((ev.metaKey || ev.ctrlKey)) { if (ev.target !== undefined) { if (self._isNoSearchResults()) return false; var cell = jQuery(ev.target).closest('table.ui-grid-body tr td'); if (ev.keyCode == 68) { if (!self.options.rowsDeletable) return false; if (self._isNoSearchResults()) return false; var row = jQuery(ev.target).closest('table.ui-grid-body tr'), cellIndex = row.children('td').index(cell), rowIndex = self.bodyTable.children('tr').index(row), currentPage = 0; if (self.options.useDataSource) currentPage = self._getCurrentPage(); if (cell.length && !self.options.useDataSource) self._navigateUp(cell); if (row.length) self._deleteRow(row, true, function(){ if (self.options.useDataSource) { if (cell) { var row = (currentPage == self._getCurrentPage()) ? self.bodyTable.find('tr:eq('+rowIndex+')') : self.bodyTable.find('tr:last'); if (!row.length) row = self.bodyTable.find('tr:last'); if (row.length) { self._initRow(row) row.find('td:eq('+cellIndex+')').trigger('navigateTo'); } } } }); ev.preventDefault(); return false; } else if (ev.keyCode == 73) { if (!self.options.allowAutoRowAdding) return false; if (self.options.useDataSource) return false; self.addRow(false, 'above'); if (cell.length) self._navigateUp(cell); ev.preventDefault(); return false; } } } }) }, _deleteRow: function(row, noMessage, onComplete) { if (this._isNoSearchResults()) return false; row.addClass('ui-selected'); if (noMessage === undefined || noMessage === false) if (!confirm(this.options.deleteRowMessage)) { row.removeClass('ui-selected'); return; } if (row[0].block_delete_message !== undefined) { alert(row[0].block_delete_message); return; } if (!this.options.useDataSource) { row.remove(); this._hideRowMenu(); if (!this.bodyTable[0].rows.length) this.addRow(); this.alignColumns(); this._updateScroller(); this._fixBottomBorder(); } else { var self = this; this._gotoPage(this._getCurrentPage(), { data: {'phpr_delete_row': row[0].rowDataIndex}, 'onComplete': function(){ if (!self.bodyTable[0].rows.length) self.addRow(); if (onComplete !== undefined) onComplete(); } }); } }, _bindSearch: function() { this.searchField = jQuery('#' + this.element.attr('id') + '_search_field') if (this.searchField.length) { var self = this; new InputChangeTracker(this.searchField.attr('id'), {regexp_mask: '^.*$'}).addEvent('change', function(){ self._updateSearch(); }); this.searchField.bind('keydown', function(ev){ if (ev.keyCode == 13) self._updateSearch(); }) } }, _hideEditors: function() { this.element.trigger('hideEditors'); }, _scrollToCell: function(cell) { var scroller = this.element.find('.ui-grid-h-scroll'); if (scroller.length) { cellPosition = cell.position(); if (cellPosition.left < 0) { var tweak = cell.is(':first-child') ? -1 : 0; scroller.scrollLeft(scroller.scrollLeft() + cellPosition.left + tweak); } else { var offsetRight = scroller.width() - (cellPosition.left + cell.width()); if (offsetRight < 0) scroller.scrollLeft(scroller.scrollLeft() - offsetRight); } } }, _pauseScrolling: function() { this._scrollingPaused = true; this.element.find('.ui-grid-h-scroll').addClass('no-scroll'); }, _resumeScrolling: function() { this._scrollingPaused = false; this.element.find('.ui-grid-h-scroll').removeClass('no-scroll'); }, _disableRowAdding: function() { this.disableRowAdding = true; }, _enableRowAdding: function() { this.disableRowAdding = false; }, /* * Row menus */ _rowMouseEnter: function(event){ var self = this; jQuery(event.currentTarget).find('span.ui-grid-menu').removeClass('menu-visible'); this._clearMenuTimer(); this.menuTimer = window.setInterval(function(){ self._displayRowMenu(event); }, 200); }, _displayRowMenu: function(event) { this._clearMenuTimer(); var row = jQuery(event.currentTarget); if (row.hasClass('ui-no-menu')) return; var menu = row.find('span.ui-grid-menu'); if (!menu.length) return; menu.css('left', 'auto'); var rowHeight = row.outerHeight(), scroller = this.element.find('.ui-grid-h-scroll'); if (scroller.length) { var cell = row.find('td:last'), scrollerWidth = scroller.width(), cellWidth = cell.width(), fixMenuPosition = function() { var cellPosition = cell.position(), cellOffset = cellPosition.left - scrollerWidth; if ((cellOffset + cellWidth) > 0) menu.css('left', (-1*cellOffset - 21) + 'px'); else menu.css('left', 'auto'); }; scroller.bind('scroll.grid', fixMenuPosition); fixMenuPosition(); } menu.css('height', rowHeight-1); menu.addClass('menu-visible'); this.currentMenu = menu; }, _rowMouseLeave: function(event) { this._clearMenuTimer(); }, _hideRowMenu: function(event) { this._clearMenuTimer(); if (!this.currentMenu) return; var scroller = this.element.find('.ui-grid-h-scroll'); scroller.unbind('.grid'); this.currentMenu.removeClass('menu-visible'); this.currentMenu = null; }, _disableRowMenu: function(cell) { this._clearMenuTimer(); this._hideRowMenu(); jQuery(cell).closest('tr').addClass('ui-no-menu'); }, _enableRowMenu: function(cell) { jQuery(cell).closest('tr').removeClass('ui-no-menu'); }, _clearMenuTimer: function() { if (this.menuTimer) { window.clearInterval(this.menuTimer); this.menuTimer = null; } }, /* * Drag support */ _dragStart: function(event) { if (event.target.tagName == 'INPUT' || event.target.tagName == 'SELECT') return; this.dragging = true; this.dragStartOffset = event.pageY; this.dragPrevOffset = 0; this.dragRow = event.currentTarget; this.dragStarted = false; this.bodyTable.disableSelection(); if (this.options.scrollable) { this.viewportOffset = this.viewport.offset(); this.viewportHeight = this.viewport.height(); this.overviewHeight = this.overview.height(); } }, _mouseMove: function(event) { if (!this.dragging) return; if (!this.dragStarted) { this.element.trigger('hideEditors'); this.dragStarted = true; this.bodyTable.addClass('drag'); jQuery(this.dragRow).addClass('ui-selected'); } if (this.options.scrollable) { if (this.viewportOffset.top > event.pageY) { // var scrollOffset = Math.max(this.scrollablePanel.scrollTop() - this.viewportOffset.top + event.pageY, 0); this.scroller.update_position(this.scrollablePanel.scrollTop()-50); } else if (event.pageY > (this.viewportOffset.top + this.viewportHeight)) { // var // bottom = this.viewportOffset.top + this.viewportHeight, // scrollOffset = Math.min(this.scrollablePanel.scrollTop() + event.pageY - bottom, this.overviewHeight-this.viewportHeight); this.scroller.update_position(this.scrollablePanel.scrollTop()+50); } } var offset = event.pageY - this.dragStartOffset; if (offset != this.dragPrevOffset) { var movingDown = offset > this.dragPrevOffset; this.dragPrevOffset = offset; var currentRow = this._findDragHoverRow(this.dragRow, event.pageY); if (currentRow !== null && currentRow !== undefined) { if (movingDown) this.dragRow.parentNode.insertBefore(this.dragRow, currentRow.nextSibling); else this.dragRow.parentNode.insertBefore(this.dragRow, currentRow); } } this.alignColumns(); }, _findDragHoverRow: function(currentRow, y) { var rows = this.bodyTable[0].rows; for (var i=0; i<rows.length; i++) { var row = rows[i], rowTop = jQuery(row).offset().top, rowHeight = row.offsetHeight; if ((y > rowTop) && (y < (rowTop + rowHeight))) { if (row == currentRow) return null; return row; } } }, _mouseUp: function(event) { if (this.dragTimeout) window.clearTimeout(this.dragTimeout); if (!this.dragging) return; this.bodyTable.enableSelection(); this.bodyTable.removeClass('drag'); this.dragging = false; jQuery(this.dragRow).removeClass('ui-selected'); event.stopImmediatePropagation(); }, /* * Navigation */ _getColumnEditor: function(cellIndex) { if (this.editors === undefined) this.editors = []; if (this.editors[cellIndex] !== undefined) return this.editors[cellIndex]; var columConfiguration = this.options.columns[cellIndex], editorName = columConfiguration.type + 'Editor'; return this.editors[editorName] = new jQuery.ui.grid.editors[editorName](); }, _navigateRight: function(fromCell, selectAll) { selectAll = selectAll === undefined ? false : selectAll; var next = fromCell.nextAll('td.ui-grid-cell-navigatable'); if (next.length) { jQuery(next[0]).trigger('navigateTo', ['right', selectAll]); return true; } else { var self = this, row = fromCell.parent(); this._createFindNextRow(row, function(nextRow){ if (!nextRow.length) return false; self._initRow(nextRow); var cell = nextRow.find('td.ui-grid-cell-navigatable:first'); cell.trigger('navigateTo', ['right', selectAll]); }); return true; } return false; }, _navigateLeft: function(fromCell, selectAll) { selectAll = selectAll === undefined ? false : selectAll; var prev = fromCell.prevAll('td.ui-grid-cell-navigatable'); if (prev.length) { jQuery(prev[0]).trigger('navigateTo', ['left', selectAll]); return true; } else { var row = fromCell.closest('tr'); this._createFindPrevRow(row, function(prevRow){ if (!prevRow.length) return; self._initRow(prevRow); var cell = prevRow.find('td.ui-grid-cell-navigatable:last'); cell.trigger('navigateTo', ['left', selectAll]); }); return true; } return false; }, _navigateDown: function(fromCell) { var self = this, row = fromCell.parent(), index = row.children('td').index(fromCell); this._createFindNextRow(row, function(nextRow){ if (!nextRow.length) return; self._initRow(nextRow); nextRow.find('td:eq('+index+')').trigger('navigateTo', ['left']); }); }, _navigateUp: function(fromCell) { var self = this, row = fromCell.parent(), index = row.children('td').index(fromCell); this._createFindPrevRow(row, function(prevRow){ if (!prevRow.length) return; self._initRow(prevRow); prevRow.find('td:eq('+index+')').trigger('navigateTo', ['left']); }); }, _setCurrentRow: function(row) { if (this.currentRow !== undefined && this.currentRow != row) this.currentRow.removeClass('current-row'); this.currentRow = row; this.currentRow.addClass('current-row'); }, _createFindNextRow: function(currentRow, callback) { this._hideRowMenu(); if (!currentRow.is(':last-child')) return callback(currentRow.next('tr')); if (!this.options.useDataSource || this.bodyTable.find('tr').length < this.options.pageSize) return callback(this.addRow()); var self = this; /* * If the row is last on this page, but the page is not last, * go to the first row of the next page. */ if (!this._isLastPage()) { this._gotoPage(this._getCurrentPage() + 1, {onComplete: function(){ var row = self.bodyTable.find('tr:first'); if (row.length) callback(row); }}); } else { /* * If the row is last on this page, and the page is last, * create new record in the data source and go to the next page. */ this.rowsAdded = this.rowsAdded === undefined ? 1 : this.rowsAdded+1; this._gotoPage(this._getCurrentPage() + 1, {data: {'phpr_append_row': 1, 'phpr_new_row_key': -1*this.rowsAdded}, onComplete: function(){ var row = self.bodyTable.find('tr:first'); if (row.length) callback(row); }}); } }, _createFindPrevRow: function(currentRow, callback) { this._hideRowMenu(); if (!currentRow.is(':first-child')) return callback(currentRow.prev('tr')); if (!this.options.useDataSource) return; /* * Go to the previous page */ var self = this; if (!this._isFirstPage()) { this._gotoPage(this._getCurrentPage() - 1, {onComplete: function(){ var row = self.bodyTable.find('tr:last'); if (row.length) callback(row); }}); } }, _createRowInTheEnd: function(callback) { this.rowsAdded = this.rowsAdded === undefined ? 1 : this.rowsAdded+1; if (this._isLastPage() && this.bodyTable.find('tr').length < this.options.pageSize) return callback(this.addRow()); this._gotoPage('last', {data: {'phpr_append_row': 1, 'phpr_new_row_key': -1*this.rowsAdded}, onComplete: function(){ var row = self.bodyTable.find('tr:last'); if (row.length) callback(row); }}); }, _isLastPage: function() { return this.element.find('.grid-is-last-page').val() === '1'; }, _isFirstPage: function() { return this.element.find('.grid-is-first-page').val() === '1'; }, _getCurrentPage: function() { return parseInt(this.element.find('.grid-current-page').val()); }, _getTotalRowCount: function() { return parseInt(this.element.find('.grid-total-record-count').val()); }, /* * Server response handling */ _handleWidgetResponseData: function(data) { if (this.element.parent().length == 0) return; if (data.widget === undefined || data.widget != 'grid') return; if (this.options.name != data.name) return; var self = this; handleError = function() { errorFieldName = self.options.name+'['+data.row+']['+data.column+']', errorField = self.bodyTable.find('input.cell-value[name="'+errorFieldName+'"]'); if (!errorField.length) return; self._markErrorField(errorField); self._scrollToCell(errorField.closest('td')); } var searchEnabled = false; if (this.searchField !== undefined) { if (this.searchField.val().length) { this.searchField.val(''); searchEnabled = true; } } if (this.options.useDataSource && (searchEnabled || (data.page_index !== undefined && this._getCurrentPage() != data.page_index))) { this._gotoPage(data.page_index, {onComplete: function(){ handleError(); }}); } else handleError(); }, _markErrorField: function(field) { if (this._errorRow !== undefined) { this._errorRow.removeClass('grid-error'); this._errorCell.removeClass('grid-error'); } this._errorRow = field.closest('tr'); this._errorCell = field.closest('td'); this._errorRow.addClass('grid-error'); this._errorCell.addClass('grid-error'); if (this.options.scrollable) { var offset = this._errorCell.position().top - this._errorCell.height() + this.scrollablePanel.scrollTop(); if (offset < 0) offset = 0; this.scroller.update_position(offset); } this._errorCell.trigger('navigateTo'); }, /* * Datasource support */ _gotoPage: function(pageIndex, options) { var self = this; if (options === undefined) options = {}; if (options.data === undefined) options.data = {}; this._disableRowMenu(); var searchUpdatedRows = this.searchUpdatedRows !== undefined ? this.searchUpdatedRows : []; if (options.data.phpr_new_row_key !== undefined) searchUpdatedRows.push(options.data.phpr_new_row_key); if (this.rowsAdded === undefined) this.rowsAdded = 1; var searchTerm = this.searchField !== undefined ? this.searchField.val() : null, data = $merge({ 'phpr_custom_event_name': 'on_navigate_to_page', 'phpr_event_field': this.options.dataFieldName, 'phpr_page_index': pageIndex, 'phpr_grid_search': searchTerm, 'phpr_grid_records_added': this.rowsAdded, 'phpr_grid_search_updated_records': searchUpdatedRows.join(',') }, options.data); new Request.Phpr({ url: location.pathname, handler: this.actionName+'onFormWidgetEvent', extraFields: data, update: 'multi', loadIndicator: {show: false}, onBeforePost: LightLoadingIndicator.show.pass('Loading...'), onComplete: LightLoadingIndicator.hide, onAfterUpdate: function() { self.rebuild(); self._dropHeaderCheckboxes(); if (options.onComplete !== undefined) options.onComplete(); self._enableRowMenu(); if (!self._hasRows() && self.searchField !== undefined && self.searchField.val().length) self._showNoSearchResults(); else self._hideNoSearchResults(); self.rowsAdded += self._getTotalRowCount(); var message = self.element.find('.grid-message-text').val(); if (message.length) alert(message); }, onFailure: function(xhr) { alert(xhr.responseText.replace('@AJAX-ERROR@', '').replace(/(<([^>]+)>)/ig,"")); }, }).post(this.element.closest('form')[0]); return false; }, updateData: function(serverEvent) { if (this.searchField !== undefined) this.searchField.val(''); this.searchUpdatedRows = []; this._gotoPage(0, {data: {'phpr_grid_event': serverEvent}}); }, /* * Search support */ _updateSearch: function() { this.searchUpdatedRows = []; this._gotoPage(0); }, _markRowSearchUpdated: function(recordIndex) { if (this.searchUpdatedRows == undefined) this.searchUpdatedRows = []; this.searchUpdatedRows.push(recordIndex); }, _showNoSearchResults: function() { this.noSearchResultsVisible = true; if (this.noSearchResultsMessage === undefined) { this.noSearchResultsMessage = jQuery('<p class="ui-no-records noData"></p>').text('No records found'); this.container.append(this.noSearchResultsMessage); this.noSearchResultsMessage.css('top', Math.round(this.container.height()/2-19)); this.noSearchResultsMessage.css('left', Math.round(this.container.width()/2-100)); } this.noSearchResultsMessage.css('display', 'block'); this.existingTable.css('display', 'none'); }, _hideNoSearchResults: function() { this.noSearchResultsVisible = false; if (this.noSearchResultsMessage === undefined) return; this.noSearchResultsMessage.css('display', 'none'); this.existingTable.css('display', 'table'); }, _isNoSearchResults: function() { return this.noSearchResultsVisible; }, /* * Header checkboxes support */ _initHeaderCheckboxes: function() { var self = this; this.headTable.find('th.checkbox-cell input').each(function(index, input) { input.addEvent('click', function() { var headCell = jQuery(input).closest('th'); var cellIndex = headCell.parent().children('th').index(headCell); var columnInfo = self.options.columns[cellIndex]; self.bodyTable.find('tr').find('td:eq('+cellIndex+')').each(function(rowIndex, cell){ if (input.checked) jQuery(cell).find('div.checkbox').addClass('checked'); else jQuery(cell).find('div.checkbox').removeClass('checked'); jQuery(cell).find('.cell-value').val(input.checked ? 1 : 0); if (columnInfo.checked_class !== undefined) { var row = jQuery(cell).parent(); if (input.checked) row.addClass(columnInfo.checked_class); else row.removeClass(columnInfo.checked_class); } }); }) }) }, _dropHeaderCheckboxes: function() { this.headTable.find('th.checkbox-cell input').each(function(index, input) { input.cb_uncheck(); }); }, /* * Tracing */ _trace: function(message) { if (window.console) console.log(message); return; } }); })( jQuery );
JavaScript
/** * This script contains grid control column editor classes. */ (function( $, undefined ) { jQuery.ui.grid = {editors: {}}; jQuery.ui.grid.editors.editorBase = jQuery.Class.create({ initialize: function() { }, /** * Initializes the cell content during the table building procedure. * @param object cell Specifies a DOM td element corresponding to the cell. * @param mixed cellContent Specifies the text content - either a string, * or an object with "display" and "value" fields. * @param array row Current table row. * @param integer cellIndex Current cell index. * @param integer rowDataIndex Current cell data element index. * @param mixed columnInfo Column confiruation object. * The method should set the cell inner content, */ initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { if (cell.find('.cell-content-container').length == 0) cell.append(jQuery('<div/>').addClass('cell-content-container').attr('tabindex', 0)); this.createCellValueElement(cell, cellIndex, rowDataIndex); this.renderContent(cell, cellContent, row, cellIndex); }, /** * Creates a hiden input element for holding the cell value. * @param object cell Specifies a DOM td element corresponding to the cell. * @param integer cellIndex Specifies a cell index. * @param integer rowDataIndex Specifies a row data index. */ createCellValueElement: function(cell, cellIndex, rowDataIndex) { var grid = cell.data('ui.grid'), contentContainer = cell.find('.cell-content-container'); contentContainer.append(jQuery('<input type="hidden" class="cell-value"></input>').attr( 'name', grid.options.name+'['+rowDataIndex+']['+grid.options.columns[cellIndex].field+']' )); contentContainer.append(jQuery('<input type="hidden" class="internal-value"></input>').attr( 'name', grid.options.name+'['+rowDataIndex+']['+grid.options.columns[cellIndex].field+'_internal]' )); }, /** * Renders cell content in read-only mode. * @param object cell Specifies a DOM td element corresponding to the cell. * @param mixed cellContent Specifies the text content - either a string, * or an object with "display" and "value" fields. * @param array row Current table row. * @param integer cellIndex Current cell index. * The method should set the cell inner content, */ renderContent: function(cell, cellContent, row, cellIndex) { if (jQuery.type(cellContent) !== 'object') { this.setCellValue(cell, cellContent); this.setCellDisplayText(cell, cellContent); } else { this.setCellValue(cell, cellContent.value); this.setCellInternalValue(cell, cellContent.internal); this.setCellDisplayText(cell, cellContent.display); } }, /** * Sets cell hidden value. * @param object cell Specifies the cell DOM td element. * @param string value Specifies the value to set. */ setCellValue: function(cell, value) { cell.find('input.cell-value').attr('value', value); this.markCellRowSearchUpdated(cell); }, /** * Sets cell internal hidden value. * @param object cell Specifies the cell DOM td element. * @param string value Specifies the value to set. */ setCellInternalValue: function(cell, value) { cell.find('input.internal-value').attr('value', value); this.markCellRowSearchUpdated(cell); }, /** * Sets cell display value. * @param object cell Specifies the cell DOM td element. * @param string text Specifies the text to set. */ setCellDisplayText: function(cell, text) { var span = cell.find('span.cell-content'); if (span.length == 0) { var contentContainer = cell.find('.cell-content-container'); span = jQuery('<span class="cell-content"></span>').text(text); contentContainer.append(span); } else span.text(text); }, /** * Returns cell display value. * @param object cell Specifies the cell DOM td element. * @return string Cell display value. */ getCellDisplayText: function(cell) { return cell.find('span.cell-content').text(); }, /** * Returns cell hidden value. * @param object cell Specifies the cell DOM td element. * @return string Cell hidden value. */ getCellValue: function(cell) { return cell.find('input.cell-value').attr('value'); }, /** * Hides cell display value. * @param object cell Specifies the cell DOM td element. */ hideCellDisplayText: function(cell) { return cell.find('span.cell-content').hide(); }, /** * Shows cell display value. * @param object cell Specifies the cell DOM td element. */ showCellDisplayText: function(cell) { return cell.find('span.cell-content').show(); }, /** * Displays the cell editor, if applicable. * @param object cell Specifies the cell DOM td element. */ displayEditor: function(cell) { this.getGrid(cell)._setCurrentRow(cell.closest('tr')); }, /** * Hides the cell editor, if applicable. * @param object cell Specifies the cell DOM td element. * @param object editor Specifies the editor DOM element, if applicable. */ hideEditor: function(cell, editor) { }, /** * Sets or returns the editor visibility state. * @param object cell Specifies the cell DOM td element. * @param boolean value Optional visibility state value. * If omitted, the function will return the current visibility state. * @return boolean */ editorVisible: function(cell, value) { if (value === undefined) return cell.data('ui.grid.editor_visible') ? true : false; cell.data('ui.grid.editor_visible', value); return value; }, /** * Returns parent grid object. * @param object cell Specifies the cell DOM td element. */ getGrid: function(cell) { return cell.data('ui.grid'); }, /** * Binds standard content container keys. * @param object contentContainer Specifies the content containier jQuery object. * @param boolean allAsClick Indicates whether any key (but arrows, tab and return) should trigger the click event. * @param boolean returnAsClick Indicates whether Return key should trigger the click event. */ bindContentContainerKeys: function(contentContainer, allAsClick, returnAsClick) { var self = this, cell = contentContainer.parent(); contentContainer.bind('keydown', function(ev){ if (self.editorVisible(cell)) return; switch (ev.keyCode) { case 32 : ev.preventDefault(); cell.trigger('click'); break; case 38 : ev.preventDefault(); self.getGrid(cell)._navigateUp(cell); break; case 40 : ev.preventDefault(); self.getGrid(cell)._navigateDown(cell); break; case 39 : case 37 : ev.preventDefault(); if (ev.keyCode == 39) self.getGrid(cell)._navigateRight(cell); else self.getGrid(cell)._navigateLeft(cell); break; case 13 : if (returnAsClick === undefined || returnAsClick === false) return; ev.preventDefault(); cell.trigger('click'); break; case 9 : break; default : if (!ev.shiftKey && !ev.ctrlKey && !ev.altKey && !ev.metaKey) { ev.preventDefault(); cell.trigger('click'); } else self.getGrid(cell)._handleGridKeys(ev); break; } }); }, markCellRowSearchUpdated: function(cell) { var grid = this.getGrid(cell), row = cell.closest('tr'); if (row.length && grid) grid._markRowSearchUpdated(row[0].rowDataIndex); } }); /* * Popup editor */ jQuery.ui.grid.editors.popupEditor = jQuery.Class.create(jQuery.ui.grid.editors.editorBase, { initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { var self = this; this.base('initContent', cell, cellContent, row, cellIndex, columnInfo, rowDataIndex); cell.addClass('ui-grid-cell-clickable'); this.bindPopupTrigger(cell, columnInfo, rowDataIndex); }, bindPopupTrigger: function(cell, columnInfo, rowDataIndex) { var self = this; cell.addClass('ui-grid-cell-focusable'); cell.addClass('ui-grid-cell-navigatable'); this.contentContainer = cell.find('.cell-content-container'); this.bindContentContainerKeys(this.contentContainer, false, true); this.contentContainer.bind('focus', function(ev){ self.getGrid(cell)._setCurrentRow(cell.closest('tr')); }); cell.bind('navigateTo', function(event, direction, selectAll){ self.contentContainer.focus(); }); cell.bind('click', function(){ var grid = self.getGrid(cell); grid._scrollToCell(cell); self.buildPopup(cell, columnInfo, rowDataIndex); return false; }) }, getZIndex: function(element) { var zElement = element.parents().filter(function(){ var css = jQuery(this).css('z-index'); return css !== undefined && css != 'auto'; }); return parseInt(zElement.css('z-index')); }, buildPopup: function(cell, columnInfo, rowDataIndex) { var zIndex = this.getZIndex(cell), grid = this.getGrid(cell); self = this; /* * Build the overlay */ var overlay = jQuery('<div class="ui-grid-overlay ui-overlay"/>'); if (zIndex) overlay.css('z-index', zIndex+1); jQuery(grid.element).append(overlay); jQuery.ui.grid.popupOverlay = overlay; /* * Build the popup window */ var tmp = jQuery('<div/>').css('display', 'none'); jQuery(grid.element).append(tmp); grid._hideRowMenu(); cell.find('.cell-content-container').blur(); new Request.Phpr({ url: location.pathname, handler: grid.actionName+'onFormWidgetEvent', extraFields: { 'phpr_custom_event_name': 'on_show_popup_editor', 'phpr_event_field': grid.options.dataFieldName, 'phpr_popup_column': columnInfo.field, 'phpr_grid_row_index': rowDataIndex }, update: tmp[0], loadIndicator: {show: false}, onSuccess: function() { self.displayPopup(tmp, zIndex, cell, grid); }, onFailure: function(xhr) { alert(xhr.responseText.replace('@AJAX-ERROR@', '').replace(/(<([^>]+)>)/ig,"")); tmp.remove(); overlay.remove(); jQuery.ui.grid.popupOverlay = undefined; }, }).post(cell.closest('form')[0]); }, displayPopup: function(dataContainer, zIndex, cell, grid) { var container = jQuery('<div class="ui-popup-container"/>').css({ 'z-index': zIndex+2, 'visibility': 'hidden' }), handle = jQuery('<div class="ui-popup-handle"/>'), content = jQuery('<div class="ui-popup-content-container"/>'), containerOffset = jQuery(grid.element).offset(), cellOffset = cell.offset(), docHeight = jQuery(document).height(), docWidth = jQuery(document).width(), cellHeightOffset = docHeight - cellOffset.top, cellWidthOffset = docWidth - cellOffset.left, popupContent = dataContainer.children().first(); jQuery.ui.grid.popupContainer = container; jQuery.ui.grid.popupCell = cell; content.append(popupContent); container.append(content); container.append(handle); dataContainer.remove(); jQuery(grid.element).append(container); var containerHeight = container.outerHeight(), containerWidth = container.outerWidth(), showBelow = cellHeightOffset > (containerHeight+40), showRight = cellWidthOffset > (containerWidth+50); if ((cellOffset.top - cell.height() + 15 - containerHeight) < 0) showBelow = true; var contentTop = showBelow ? (cellOffset.top - containerOffset.top + cell.height() + 5 + 'px') : (cellOffset.top - containerOffset.top - cell.height() + 15 - containerHeight + 'px'); var contentLeft = showRight ? (cellOffset.left - containerOffset.left + container.width() + 40 - containerWidth + 'px') : (cellOffset.left - containerOffset.left - container.width() + 40 + 'px'); container.css({ top: contentTop, left: contentLeft, visibility: 'visible' }); if (!showBelow) container.addClass('above'); if (showRight) container.addClass('right'); cell.addClass('popup-focused'); popupContent[0].fireEvent('popupLoaded'); window.fireEvent('popupLoaded', popupContent[0]); popupContent.data('ui.gridEditor', this); popupContent.data('ui.gridCell', cell); grid._hideEditors(); grid._disableRowAdding(); jQuery(document).bind('keydown.gridpopup', function(ev){ if (ev.keyCode == 27) popupContent[0].fireEvent('onEscape'); }); } }); /* * Single-line text editor. This editor has optional autocomplete parameter, which could be set in the column configuration object. * The parameter value could be either "predefined" or "remote". If the predefined option is specified, the column configuration * object should also have the "options" array with a list of available values. */ jQuery.ui.grid.editors.textEditor = jQuery.Class.create(jQuery.ui.grid.editors.popupEditor, { initialize: function() { this.base('initialize'); }, initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { var self = this; this.base('initContent', cell, cellContent, row, cellIndex, columnInfo, rowDataIndex); cell.addClass('ui-grid-cell-navigatable'); cell.addClass('ui-grid-cell-editable'); cell.find('.cell-content-container').bind('focus.grid', function(event){ self.displayEditor(cell, null, false, columnInfo); }) cell.bind('click.grid navigateTo', function(event, direction, selectAll){ selectAll = selectAll === undefined ? false : selectAll; self.displayEditor(cell, direction, selectAll, columnInfo); }); if (columnInfo.editor_class !== undefined) { cell.data('grid.rowDataIndex', rowDataIndex); } }, bindPopupTrigger: function(cell, columnInfo, rowDataIndex) {}, displayEditor: function(cell, navigationDirection, selectAll, columnInfo) { if (this.editorVisible(cell) || this.getGrid(cell).dragStarted) return; this.editorVisible(cell, true); var grid = this.getGrid(cell); grid._scrollToCell(cell); var self = this, editor = jQuery('<input type="text" class="cell-editor"/>') .attr('value', this.getCellValue(cell)) .css('height', cell.height()+'px'), editorContainer = jQuery('<div class="cell-editor-container"/>'), autocomplete = columnInfo.autocomplete !== undefined ? columnInfo.autocomplete : false; grid._disableRowMenu(cell); editorContainer.append(editor); editor.data('gridContainer', editorContainer); /* * Setup autocompletion */ if (autocomplete !== false) { var options = { appendTo: grid.element, position: { my: "left top", at: "left bottom", collision: "none", of: cell }, open: function(){ grid._pauseScrolling(); var autocompleteObj = grid.element.find('.ui-autocomplete'), widthFix = 1, fixLeft = false; if (cell.is(':first-child')) { widthFix++; fixLeft = true; } var autocompleteWidth = cell.outerWidth()+widthFix; if (autocompleteWidth < 200) autocompleteWidth = 200; autocompleteObj.outerWidth(autocompleteWidth); if (fixLeft > 0) autocompleteObj.css('margin-left', '-1px'); }, close: function(){ grid._resumeScrolling(); }, minLength: (columnInfo.minLength === undefined ? 1 : columnInfo.minLength) }; if (autocomplete == 'predefined') options.source = columnInfo.options; else if (autocomplete == 'remote') { var row = cell.closest('tr'), form = cell.closest('form'), action = form.attr('action'); options.source = function(request, response) { self.autocomplete(request, response, columnInfo, cell, row, action, form, grid); } } editor.autocomplete(options); } /* * Setup editor events */ this.hideCellDisplayText(cell); editor.bind('blur', function(){ window.setTimeout(function(){ self.hideEditor(cell, editor); }, 200) }); grid.element.bind('hideEditors', function(){ self.hideEditor(cell, editor); }) editor.keyup(function(ev){ self.setCellValue(cell, editor.val()); }); editor.bind('keydown', function(ev){ switch (ev.keyCode) { case 38 : if (autocomplete === false) grid._navigateUp(cell); break; case 40 : if (autocomplete === false) grid._navigateDown(cell); break; case 39 : case 37 : var sel = jQuery(editor).caret(); if (sel.end === undefined) sel.end = 0; if (ev.keyCode == 39) { if (sel.end == editor.attr('value').length) { ev.preventDefault(); grid._navigateRight(cell); } } else { if (sel.start === undefined) { ev.preventDefault(); grid._navigateLeft(cell); } } break; case 9 : if (!ev.shiftKey) { if (grid._navigateRight(cell, true)) ev.preventDefault(); } else { if (grid._navigateLeft(cell, true)) ev.preventDefault(); } break; case 27 : self.hideEditor(cell, editor); break; case 73 : if (ev.metaKey || ev.ctrlKey) grid.appendRow(cell, ev); break; } }); /* * Create button for the popup editor */ if (columnInfo.editor_class !== undefined) { var button = jQuery('<a href="#" class="ui-grid-cell-button"></a>'), knob = jQuery('<span></span>'), heightTweak = -1, row = cell.parent(); if (row.is(':last-child') && grid.bodyTable.hasClass('no-bottom-border')) heightTweak = 0; button.css({ 'height': cell.outerHeight() + heightTweak + 'px', }) .append(knob); button.click(function(){ self.hideEditor(cell, editor); self.buildPopup(cell, columnInfo, cell.data('grid.rowDataIndex')); return false; }); editorContainer.append(button); cell.addClass('popup-button-container'); editor.bind('keydown', function(ev){ if (ev.keyCode == 13 && !ev.ctrlKey) { button.trigger('click'); editorContainer.blur(); ev.preventDefault(); return false; } }); } /* * Append the editor, and focus it */ cell.append(editorContainer); editor.focus(); /* * Set the caret position and display the eidtor */ if (!selectAll) { if (navigationDirection !== undefined && navigationDirection === 'left') { var len = editor.attr('value').length; editor.caret(len, len); } else editor.caret(0, 0); } else { var len = editor.attr('value').length; editor.caret(0, len); } this.base('displayEditor', cell); }, hideEditor: function(cell, editor) { this.editorVisible(cell, false); var self = this, grid = self.getGrid(cell); this.setCellDisplayText(cell, editor.attr('value')); this.setCellValue(cell, editor.attr('value')); if (editor.data('gridContainer')) editor.data('gridContainer').remove(); else editor.remove(); this.showCellDisplayText(cell); if (grid) grid._enableRowMenu(cell); }, autocomplete: function (request, response, columnInfo, cell, row, url, form, grid) { var formData = form.serialize(), rowData = {}, custom_values = columnInfo.autocomplete_custom_values === undefined ? false : true; row.find('input.cell-value').each(function(index, input){ var $input = jQuery(input), match = /[^\]]+\[[^\]]+\]\[\-?[0-9]+\]\[([^\]]+)\]/.exec($input.attr('name')); if (match !== null) { var field_name = 'autocomplete_row_data['+match[1]+']', field_value = $input.attr('value'); rowData[field_name] = field_value; } }); formData += '&'+ jQuery.param(rowData)+ '&autocomplete_term='+encodeURIComponent(request.term)+ '&autocomplete_column='+columnInfo.field+ '&autocomplete_custom_values='+custom_values+ '&phpr_custom_event_name=on_autocomplete'+ '&phpr_event_field='+ grid.options.dataFieldName+ '&phpr_no_cookie_update=1'; var lastXhr = jQuery.ajax({ 'type': 'POST', 'url': url, 'data': formData, success: function( data, status, xhr ) { if ( xhr === lastXhr ) { response(data); } }, error: function(request, error) { alert(request.responseText); }, dataType: 'json', headers: { 'PHPR-REMOTE-EVENT': 1, 'PHPR-POSTBACK': 1, 'PHPR-EVENT-HANDLER': 'ev{'+grid.actionName+'onFormWidgetEvent}', 'PHPR-CUSTOM-EVENT-NAME': 'on_autocomplete', 'PHPR-EVENT-FIELD': grid.options.dataFieldName } }); } }); /* * Drop-down cell editor. This editor requires the option_keys and option_values properties * to be set in the column configuration object: {option_keys: [0, 1], option_values: ['Option 1', 'Option 2']} * Other supported options: allowDeselect (boolean), default_text: string */ jQuery.ui.grid.editors.dropdownEditor = jQuery.Class.create(jQuery.ui.grid.editors.editorBase, { initialize: function() { this.base('initialize'); }, initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { var self = this; this.ignoreFocus = false; this.base('initContent', cell, cellContent, row, cellIndex, columnInfo, rowDataIndex); cell.addClass('ui-grid-cell-navigatable'); cell.addClass('ui-grid-cell-editable'); cell.addClass('ui-grid-cell-focusable'); this.contentContainer = cell.find('.cell-content-container'); this.bindContentContainerKeys(this.contentContainer, true, false); this.contentContainer.bind('focus', function(ev){ if (ev.originalEvent !== undefined) self.displayEditor(cell, null, columnInfo); else self.getGrid(cell)._setCurrentRow(cell.closest('tr')); }); cell.bind('click.grid', function(event, direction, selectAll){ self.displayEditor(cell, direction, columnInfo); }); cell.bind('navigateTo', function(event, direction, selectAll){ self.contentContainer.focus(); }); }, displayEditor: function(cell, navigationDirection, columnInfo) { if (this.editorVisible(cell) || this.getGrid(cell).dragStarted) return; var grid = this.getGrid(cell); grid._scrollToCell(cell); var self = this, gridOffset = grid.element.offset(), cellOffset = cell.offset(), offsetLeft = cellOffset.left-gridOffset.left-2, offsetTop = cellOffset.top-gridOffset.top-3; if (!cell.is(':first-child')) offsetLeft++; if (!grid.options.scrollable) offsetLeft++; grid._hideEditors(); this.editorVisible(cell, true); this.hideCellDisplayText(cell); var select = jQuery('<select>'), selectContainer = jQuery('<div class="ui-grid-select-container">'); selectContainer.css({ 'left': offsetLeft+'px', 'top': offsetTop+'px', 'width': (cell.width()+2)+'px', 'height': (cell.height()+2)+'px' }); if (columnInfo.default_text !== undefined) select.attr('data-placeholder', columnInfo.default_text); if (columnInfo.allow_deselect !== undefined || columnInfo.default_text !== undefined) select.append(jQuery('<option>').attr('value', '').text('')); var valueFound = false, currentValue = this.getCellValue(cell); jQuery.each(columnInfo.option_keys, function(index, value){ select.append(jQuery('<option></option>').attr('value', value).text(columnInfo.option_values[index])); if (currentValue == value) valueFound = true; }); if (!valueFound) select.append(jQuery('<option></option>').attr('value', currentValue).text(currentValue)); select.val(currentValue); selectContainer.append(select); grid.element.append(selectContainer); select.bind('change', function(){ self.setCellDisplayText(cell, select.find('option:selected').text()); self.setCellValue(cell, select.val()); self.hideEditor(cell, select); self.ignoreFocus = true; self.contentContainer.focus(); self.ignoreFocus = false; }) cell.css('overflow', 'visible'); var options = {allow_single_deselect: false}; if (columnInfo.allowDeselect !== undefined) options.allow_single_deselect = columnInfo.allowDeselect; jQuery(select).chosen(options); grid._disableRowMenu(cell); grid._pauseScrolling(); var container = selectContainer.find('.chzn-container'); container.css('height', (cell.height()+2)+'px'); container.bind('keydown', function(ev){ switch (ev.keyCode) { case 9 : self.hideEditor(cell, select); if (!ev.shiftKey) { if (self.getGrid(cell)._navigateRight(cell, true)) ev.preventDefault(); } else { if (self.getGrid(cell)._navigateLeft(cell, true)) ev.preventDefault(); } break; case 27 : self.hideEditor(cell, select); ev.preventDefault(); self.ignoreFocus = true; self.contentContainer.focus(); self.ignoreFocus = false; break; } }); window.setTimeout(function(){ jQuery(document).bind('mousedown.gridDropdown', function(e) { self.hideEditor(cell, select); }); }, 300); this.base('displayEditor', cell); this.getGrid(cell).element.bind('hideEditors', function(){ self.hideEditor(cell, select); }); window.setTimeout(function(){ container.trigger('mousedown'); }, 60); }, hideEditor: function(cell, editor) { var grid = this.getGrid(cell); if (grid === undefined) return; grid._enableRowMenu(cell); grid._resumeScrolling(); jQuery(document).unbind('.gridDropdown'); editor.parent().remove(); this.editorVisible(cell, false); cell.find('.chzn-container').remove(); cell.css('overflow', ''); var self = this; this.showCellDisplayText(cell); } }); /* * Checkbox cell editor */ jQuery.ui.grid.editors.checkboxEditor = jQuery.Class.create(jQuery.ui.grid.editors.editorBase, { initContent: function(cell, cellContent, row, cellIndex, columnInfo, rowDataIndex) { var self = this; this.base('initContent', cell, cellContent, row, cellIndex, columnInfo, rowDataIndex); cell.addClass('cell-checkbox'); cell.addClass('ui-grid-cell-navigatable'); this.hideCellDisplayText(cell); var editor = jQuery('<div class="checkbox"/>') .attr('tabindex', 0) .bind('click', function(){ var curValue = self.getCellValue(cell); if (curValue == 1) { self.setCellValue(cell, 0); jQuery(this).removeClass('checked'); self.getGrid(cell)._dropHeaderCheckboxes(); if (columnInfo.checked_class !== undefined) row.removeClass(columnInfo.checked_class); } else { self.setCellValue(cell, 1); jQuery(this).addClass('checked'); if (columnInfo.checked_class !== undefined) row.addClass(columnInfo.checked_class); } }) .bind('focus', function(ev){ self.getGrid(cell)._setCurrentRow(cell.closest('tr')); }) .bind('keydown', function(ev){ switch (ev.keyCode) { case 32 : case 13 : editor.trigger('click'); break; case 38 : self.getGrid(cell)._navigateUp(cell); break; case 40 : self.getGrid(cell)._navigateDown(cell); break; case 39 : case 37 : ev.preventDefault(); if (ev.keyCode == 39) self.getGrid(cell)._navigateRight(cell); else self.getGrid(cell)._navigateLeft(cell); break; case 9 : if (!ev.shiftKey) { if (self.getGrid(cell)._navigateRight(cell, true)) ev.preventDefault(); } else { if (self.getGrid(cell)._navigateLeft(cell, true)) ev.preventDefault(); } break; default: self.getGrid(cell)._handleGridKeys(ev); break; } }); if (this.getCellValue(cell) == 1) editor.addClass('checked'); var contentContainer = cell.find('.cell-content-container'); contentContainer.append(editor); cell.bind('click navigateTo', function(ev, direction, selectAll){ editor.focus(); }); } }); jQuery.ui.grid.hidePopup = function() { if (!jQuery.ui.grid.popupContainer !== undefined && jQuery.ui.grid.popupOverlay !== undefined) { hide_tooltips(); jQuery.ui.grid.popupContainer.remove(); jQuery.ui.grid.popupOverlay.remove(); jQuery.ui.grid.popupCell.removeClass('popup-focused'); jQuery.ui.grid.popupCell.data('ui.grid')._enableRowAdding(); if (jQuery.ui.grid.popupCell.hasClass('ui-grid-cell-focusable')) jQuery.ui.grid.popupCell.find('.cell-content-container').focus(); jQuery(document).unbind('keydown.gridpopup'); } } })( jQuery );
JavaScript
/** * Swiff.Uploader - Flash FileReference Control * * @version 1.2 * * @license MIT License * * @author Harald Kirschner <mail [at] digitarald [dot] de> * @copyright Authors */ Swiff.Uploader = new Class({ Extends: Swiff, Implements: Events, options: { path: 'Swiff.Uploader.swf', multiple: true, queued: true, typeFilter: null, url: null, method: 'post', data: null, fieldName: 'Filedata', target: null, height: '100%', width: '100%', callBacks: null }, initialize: function(options){ if (Browser.Plugins.Flash.version < 9) return false; this.setOptions(options); var callBacks = this.options.callBacks || this; if (callBacks.onLoad) this.addEvent('onLoad', callBacks.onLoad); if (!callBacks.onBrowse) { callBacks.onBrowse = function() { return this.options.typeFilter; } } var prepare = {}, self = this; ['onBrowse', 'onSelect', 'onAllSelect', 'onCancel', 'onBeforeOpen', 'onOpen', 'onProgress', 'onComplete', 'onError', 'onAllComplete'].each(function(index) { var fn = callBacks[index] || $empty; prepare[index] = function() { self.fireEvent(index, arguments, 10); return fn.apply(self, arguments); }; }); prepare.onLoad = this.load.create({delay: 10, bind: this}); this.options.callBacks = prepare; var path = this.options.path; if (!path.contains('?')) path += '?noCache=' + $time(); // quick fix this.parent(path); var scroll = window.getScroll(); this.box = new Element('div', { styles: { position: 'absolute', visibility: 'visible', zIndex: 9999, overflow: 'hidden', height: 15, width: 15, top: scroll.y, left: scroll.x } }); this.inject(this.box); this.box.inject($(this.options.container) || document.body); return this; }, load: function(){ this.remote('register', this.instance, this.options.multiple, this.options.queued); this.fireEvent('onLoad'); this.target = $(this.options.target); if (Browser.Plugins.Flash.version >= 10 && this.target) { this.reposition(); window.addEvent('resize', this.reposition.bind(this)); } }, reposition: function() { var pos = this.target.getCoordinatesIeFixed(this.box.getOffsetParentIeFixed()); this.box.setStyles(pos); }, /* Method: browse Open the file browser. */ browse: function(typeFilter){ this.options.typeFilter = $pick(typeFilter, this.options.typeFilter); return this.remote('browse'); }, /* Method: upload Starts the upload of all selected files. */ upload: function(options){ var current = this.options; options = $extend({data: current.data, url: current.url, method: current.method, fieldName: current.fieldName}, options); if ($type(options.data) == 'element') options.data = $(options.data).toQueryString(); return this.remote('upload', options); }, /* Method: removeFile For multiple uploads cancels and removes the given file from queue. Arguments: name - (string) Filename name - (string) Filesize in byte */ removeFile: function(file){ if (file) file = {name: file.name, size: file.size}; return this.remote('removeFile', file); }, /* Method: getFileList Returns one Array with with arrays containing name and size of the file. Returns: (array) An array with files */ getFileList: function(){ return this.remote('getFileList'); } });
JavaScript
/* * jQuery UI Tag-it! * * @version v2.0 (06/2011) * * Copyright 2011, Levy Carneiro Jr. * Released under the MIT license. * http://aehlke.github.com/tag-it/LICENSE * * Homepage: * http://aehlke.github.com/tag-it/ * * Authors: * Levy Carneiro Jr. * Martin Rehfeld * Tobias Schmidt * Skylar Challand * Alex Ehlke * * Maintainer: * Alex Ehlke - Twitter: @aehlke * * Dependencies: * jQuery v1.4+ * jQuery UI v1.8+ */ (function($) { $.widget('ui.tagit', { options: { itemName : 'item', fieldName : 'tags', availableTags : [], tagSource : null, removeConfirmation: false, caseSensitive : true, placeholderText : null, // When enabled, quotes are not neccesary // for inputting multi-word tags. allowSpaces: false, // Whether to animate tag removals or not. animate: true, // The below options are for using a single field instead of several // for our form values. // // When enabled, will use a single hidden field for the form, // rather than one per tag. It will delimit tags in the field // with singleFieldDelimiter. // // The easiest way to use singleField is to just instantiate tag-it // on an INPUT element, in which case singleField is automatically // set to true, and singleFieldNode is set to that element. This // way, you don't need to fiddle with these options. singleField: false, singleFieldDelimiter: ',', // Set this to an input DOM node to use an existing form field. // Any text in it will be erased on init. But it will be // populated with the text of tags as they are created, // delimited by singleFieldDelimiter. // // If this is not set, we create an input node for it, // with the name given in settings.fieldName, // ignoring settings.itemName. singleFieldNode: null, // Optionally set a tabindex attribute on the input that gets // created for tag-it. tabIndex: null, // Event callbacks. onTagAdded : null, onTagRemoved: null, onTagClicked: null }, _create: function() { // for handling static scoping inside callbacks var that = this; // There are 2 kinds of DOM nodes this widget can be instantiated on: // 1. UL, OL, or some element containing either of these. // 2. INPUT, in which case 'singleField' is overridden to true, // a UL is created and the INPUT is hidden. if (this.element.is('input')) { this.tagList = $('<ul></ul>').insertAfter(this.element); this.options.singleField = true; this.options.singleFieldNode = this.element; this.element.css('display', 'none'); } else { this.tagList = this.element.find('ul, ol').andSelf().last(); } this._tagInput = $('<input type="text" />').addClass('ui-widget-content'); if (this.options.tabIndex) { this._tagInput.attr('tabindex', this.options.tabIndex); } if (this.options.placeholderText) { this._tagInput.attr('placeholder', this.options.placeholderText); } this.options.tagSource = this.options.tagSource || function(search, showChoices) { var filter = search.term.toLowerCase(); var choices = $.grep(this.options.availableTags, function(element) { // Only match autocomplete options that begin with the search term. // (Case insensitive.) return (element.toLowerCase().indexOf(filter) === 0); }); showChoices(this._subtractArray(choices, this.assignedTags())); }; // Bind tagSource callback functions to this context. if ($.isFunction(this.options.tagSource)) { this.options.tagSource = $.proxy(this.options.tagSource, this); } this.tagList .addClass('tagit') .addClass('ui-widget ui-widget-content ui-corner-all') // Create the input field. .append($('<li class="tagit-new"></li>').append(this._tagInput)) .click(function(e) { var target = $(e.target); if (target.hasClass('tagit-label')) { that._trigger('onTagClicked', e, target.closest('.tagit-choice')); } else { // Sets the focus() to the input field, if the user // clicks anywhere inside the UL. This is needed // because the input field needs to be of a small size. that._tagInput.focus(); } }); // Add existing tags from the list, if any. this.tagList.children('li').each(function() { if (!$(this).hasClass('tagit-new')) { that.createTag($(this).html(), $(this).attr('class')); $(this).remove(); } }); // Single field support. if (this.options.singleField) { if (this.options.singleFieldNode) { // Add existing tags from the input field. var node = $(this.options.singleFieldNode); var tags = node.val().split(this.options.singleFieldDelimiter); node.val(''); $.each(tags, function(index, tag) { that.createTag(tag); }); } else { // Create our single field input after our list. this.options.singleFieldNode = this.tagList.after('<input type="hidden" style="display:none;" value="" name="' + this.options.fieldName + '" />'); } } // Events. this._tagInput .keydown(function(event) { // Backspace is not detected within a keypress, so it must use keydown. if (event.which == $.ui.keyCode.BACKSPACE && that._tagInput.val() === '') { var tag = that._lastTag(); if (!that.options.removeConfirmation || tag.hasClass('remove')) { // When backspace is pressed, the last tag is deleted. that.removeTag(tag); } else if (that.options.removeConfirmation) { tag.addClass('remove ui-state-highlight'); } } else if (that.options.removeConfirmation) { that._lastTag().removeClass('remove ui-state-highlight'); } // Comma/Space/Enter are all valid delimiters for new tags, // except when there is an open quote or if setting allowSpaces = true. // Tab will also create a tag, unless the tag input is empty, in which case it isn't caught. if ( event.which == $.ui.keyCode.COMMA || event.which == $.ui.keyCode.ENTER || ( event.which == $.ui.keyCode.TAB && that._tagInput.val() !== '' ) || ( event.which == $.ui.keyCode.SPACE && that.options.allowSpaces !== true && ( $.trim(that._tagInput.val()).replace( /^s*/, '' ).charAt(0) != '"' || ( $.trim(that._tagInput.val()).charAt(0) == '"' && $.trim(that._tagInput.val()).charAt($.trim(that._tagInput.val()).length - 1) == '"' && $.trim(that._tagInput.val()).length - 1 !== 0 ) ) ) ) { event.preventDefault(); that.createTag(that._cleanedInput()); // The autocomplete doesn't close automatically when TAB is pressed. // So let's ensure that it closes. that._tagInput.autocomplete('close'); } }).blur(function(e){ // Create a tag when the element loses focus (unless it's empty). that.createTag(that._cleanedInput()); }); // Autocomplete. if (this.options.availableTags || this.options.tagSource) { this._tagInput.autocomplete({ source: this.options.tagSource, select: function(event, ui) { // Delete the last tag if we autocomplete something despite the input being empty // This happens because the input's blur event causes the tag to be created when // the user clicks an autocomplete item. // The only artifact of this is that while the user holds down the mouse button // on the selected autocomplete item, a tag is shown with the pre-autocompleted text, // and is changed to the autocompleted text upon mouseup. if (that._tagInput.val() === '') { that.removeTag(that._lastTag(), false); } that.createTag(ui.item.value); // Preventing the tag input to be updated with the chosen value. return false; } }); } }, _cleanedInput: function() { // Returns the contents of the tag input, cleaned and ready to be passed to createTag return $.trim(this._tagInput.val().replace(/^"(.*)"$/, '$1')); }, _lastTag: function() { return this.tagList.children('.tagit-choice:last'); }, assignedTags: function() { // Returns an array of tag string values var that = this; var tags = []; if (this.options.singleField) { tags = $(this.options.singleFieldNode).val().split(this.options.singleFieldDelimiter); if (tags[0] === '') { tags = []; } } else { this.tagList.children('.tagit-choice').each(function() { tags.push(that.tagLabel(this)); }); } return tags; }, _updateSingleTagsField: function(tags) { // Takes a list of tag string values, updates this.options.singleFieldNode.val to the tags delimited by this.options.singleFieldDelimiter $(this.options.singleFieldNode).val(tags.join(this.options.singleFieldDelimiter)); }, _subtractArray: function(a1, a2) { var result = []; for (var i = 0; i < a1.length; i++) { if ($.inArray(a1[i], a2) == -1) { result.push(a1[i]); } } return result; }, tagLabel: function(tag) { // Returns the tag's string label. if (this.options.singleField) { return $(tag).children('.tagit-label').text(); } else { return $(tag).children('input').val(); } }, _isNew: function(value) { var that = this; var isNew = true; this.tagList.children('.tagit-choice').each(function(i) { if (that._formatStr(value) == that._formatStr(that.tagLabel(this))) { isNew = false; return false; } }); return isNew; }, _formatStr: function(str) { if (this.options.caseSensitive) { return str; } return $.trim(str.toLowerCase()); }, createTag: function(value, additionalClass) { var that = this; // Automatically trims the value of leading and trailing whitespace. value = $.trim(value); if (!this._isNew(value) || value === '') { return false; } var label = $(this.options.onTagClicked ? '<a class="tagit-label"></a>' : '<span class="tagit-label"></span>').text(value); // Create tag. var tag = $('<li></li>') .addClass('tagit-choice ui-widget-content ui-state-default ui-corner-all') .addClass(additionalClass) .append(label); // Button for removing the tag. var removeTagIcon = $('<span></span>') .addClass('ui-icon ui-icon-close'); var removeTag = $('<a><span class="text-icon">\xd7</span></a>') // \xd7 is an X .addClass('tagit-close') .append(removeTagIcon) .click(function(e) { // Removes a tag when the little 'x' is clicked. that.removeTag(tag); }); tag.append(removeTag); // Unless options.singleField is set, each tag has a hidden input field inline. if (this.options.singleField) { var tags = this.assignedTags(); tags.push(value); this._updateSingleTagsField(tags); } else { var escapedValue = label.html(); tag.append('<input type="hidden" style="display:none;" value="' + escapedValue + '" name="' + this.options.itemName + '[' + this.options.fieldName + '][]" />'); } this._trigger('onTagAdded', null, tag); // Cleaning the input. this._tagInput.val(''); // insert tag this._tagInput.parent().before(tag); }, removeTag: function(tag, animate) { animate = animate || this.options.animate; tag = $(tag); this._trigger('onTagRemoved', null, tag); if (this.options.singleField) { var tags = this.assignedTags(); var removedTagLabel = this.tagLabel(tag); tags = $.grep(tags, function(el){ return el != removedTagLabel; }); this._updateSingleTagsField(tags); } // Animate the removal. if (animate) { tag.fadeOut('fast').hide('blind', {direction: 'horizontal'}, 'fast', function(){ tag.remove(); }).dequeue(); } else { tag.remove(); } }, removeAll: function() { // Removes all tags. var that = this; this.tagList.children('.tagit-choice').each(function(index, tag) { that.removeTag(tag, false); }); } }); })(jQuery); /* Copyright (c) 2011 Levy Carneiro Jr. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
JavaScript
/** * * Date picker * Author: Stefan Petre www.eyecon.ro * */ (function ($) { var DatePicker = function () { var ids = {}, tpl = { wrapper: '<div class="datepicker"><div class="datepickerBorderT" /><div class="datepickerBorderB" /><div class="datepickerBorderL" /><div class="datepickerBorderR" /><div class="datepickerBorderTL" /><div class="datepickerBorderTR" /><div class="datepickerBorderBL" /><div class="datepickerBorderBR" /><div class="datepickerContainer"><table cellspacing="0" cellpadding="0"><tbody><tr></tr></tbody></table></div></div>', head: [ '<td>', '<table cellspacing="0" cellpadding="0">', '<thead>', '<tr class="datepickerMonthSelector">', '<th class="datepickerGoPrev"><a tabidex="-1" href="#"><span><%=prev%></span></a></th>', '<th colspan="6" class="datepickerMonth"><a tabidex="-1" href="#"><span></span></a></th>', '<th class="datepickerGoNext"><a tabidex="-1" href="#"><span><%=next%></span></a></th>', '</tr>', '<tr class="datepickerDoW">', '<th><span><%=week%></span></th>', '<th><span><%=day1%></span></th>', '<th><span><%=day2%></span></th>', '<th><span><%=day3%></span></th>', '<th><span><%=day4%></span></th>', '<th><span><%=day5%></span></th>', '<th><span><%=day6%></span></th>', '<th><span><%=day7%></span></th>', '</tr>', '</thead>', '</table></td>' ], space : '<td class="datepickerSpace"><div></div></td>', days: [ '<tbody class="datepickerDays">', '<tr>', '<th class="datepickerWeek"><a href="#"><span><%=weeks[0].week%></span></a></th>', '<td class="<%=weeks[0].days[0].classname%>"><a href="#"><span><%=weeks[0].days[0].text%></span></a></td>', '<td class="<%=weeks[0].days[1].classname%>"><a href="#"><span><%=weeks[0].days[1].text%></span></a></td>', '<td class="<%=weeks[0].days[2].classname%>"><a href="#"><span><%=weeks[0].days[2].text%></span></a></td>', '<td class="<%=weeks[0].days[3].classname%>"><a href="#"><span><%=weeks[0].days[3].text%></span></a></td>', '<td class="<%=weeks[0].days[4].classname%>"><a href="#"><span><%=weeks[0].days[4].text%></span></a></td>', '<td class="<%=weeks[0].days[5].classname%>"><a href="#"><span><%=weeks[0].days[5].text%></span></a></td>', '<td class="<%=weeks[0].days[6].classname%>"><a href="#"><span><%=weeks[0].days[6].text%></span></a></td>', '</tr>', '<tr>', '<th class="datepickerWeek"><a href="#"><span><%=weeks[1].week%></span></a></th>', '<td class="<%=weeks[1].days[0].classname%>"><a href="#"><span><%=weeks[1].days[0].text%></span></a></td>', '<td class="<%=weeks[1].days[1].classname%>"><a href="#"><span><%=weeks[1].days[1].text%></span></a></td>', '<td class="<%=weeks[1].days[2].classname%>"><a href="#"><span><%=weeks[1].days[2].text%></span></a></td>', '<td class="<%=weeks[1].days[3].classname%>"><a href="#"><span><%=weeks[1].days[3].text%></span></a></td>', '<td class="<%=weeks[1].days[4].classname%>"><a href="#"><span><%=weeks[1].days[4].text%></span></a></td>', '<td class="<%=weeks[1].days[5].classname%>"><a href="#"><span><%=weeks[1].days[5].text%></span></a></td>', '<td class="<%=weeks[1].days[6].classname%>"><a href="#"><span><%=weeks[1].days[6].text%></span></a></td>', '</tr>', '<tr>', '<th class="datepickerWeek"><a href="#"><span><%=weeks[2].week%></span></a></th>', '<td class="<%=weeks[2].days[0].classname%>"><a href="#"><span><%=weeks[2].days[0].text%></span></a></td>', '<td class="<%=weeks[2].days[1].classname%>"><a href="#"><span><%=weeks[2].days[1].text%></span></a></td>', '<td class="<%=weeks[2].days[2].classname%>"><a href="#"><span><%=weeks[2].days[2].text%></span></a></td>', '<td class="<%=weeks[2].days[3].classname%>"><a href="#"><span><%=weeks[2].days[3].text%></span></a></td>', '<td class="<%=weeks[2].days[4].classname%>"><a href="#"><span><%=weeks[2].days[4].text%></span></a></td>', '<td class="<%=weeks[2].days[5].classname%>"><a href="#"><span><%=weeks[2].days[5].text%></span></a></td>', '<td class="<%=weeks[2].days[6].classname%>"><a href="#"><span><%=weeks[2].days[6].text%></span></a></td>', '</tr>', '<tr>', '<th class="datepickerWeek"><a href="#"><span><%=weeks[3].week%></span></a></th>', '<td class="<%=weeks[3].days[0].classname%>"><a href="#"><span><%=weeks[3].days[0].text%></span></a></td>', '<td class="<%=weeks[3].days[1].classname%>"><a href="#"><span><%=weeks[3].days[1].text%></span></a></td>', '<td class="<%=weeks[3].days[2].classname%>"><a href="#"><span><%=weeks[3].days[2].text%></span></a></td>', '<td class="<%=weeks[3].days[3].classname%>"><a href="#"><span><%=weeks[3].days[3].text%></span></a></td>', '<td class="<%=weeks[3].days[4].classname%>"><a href="#"><span><%=weeks[3].days[4].text%></span></a></td>', '<td class="<%=weeks[3].days[5].classname%>"><a href="#"><span><%=weeks[3].days[5].text%></span></a></td>', '<td class="<%=weeks[3].days[6].classname%>"><a href="#"><span><%=weeks[3].days[6].text%></span></a></td>', '</tr>', '<tr>', '<th class="datepickerWeek"><a href="#"><span><%=weeks[4].week%></span></a></th>', '<td class="<%=weeks[4].days[0].classname%>"><a href="#"><span><%=weeks[4].days[0].text%></span></a></td>', '<td class="<%=weeks[4].days[1].classname%>"><a href="#"><span><%=weeks[4].days[1].text%></span></a></td>', '<td class="<%=weeks[4].days[2].classname%>"><a href="#"><span><%=weeks[4].days[2].text%></span></a></td>', '<td class="<%=weeks[4].days[3].classname%>"><a href="#"><span><%=weeks[4].days[3].text%></span></a></td>', '<td class="<%=weeks[4].days[4].classname%>"><a href="#"><span><%=weeks[4].days[4].text%></span></a></td>', '<td class="<%=weeks[4].days[5].classname%>"><a href="#"><span><%=weeks[4].days[5].text%></span></a></td>', '<td class="<%=weeks[4].days[6].classname%>"><a href="#"><span><%=weeks[4].days[6].text%></span></a></td>', '</tr>', '<tr>', '<th class="datepickerWeek"><a href="#"><span><%=weeks[5].week%></span></a></th>', '<td class="<%=weeks[5].days[0].classname%>"><a href="#"><span><%=weeks[5].days[0].text%></span></a></td>', '<td class="<%=weeks[5].days[1].classname%>"><a href="#"><span><%=weeks[5].days[1].text%></span></a></td>', '<td class="<%=weeks[5].days[2].classname%>"><a href="#"><span><%=weeks[5].days[2].text%></span></a></td>', '<td class="<%=weeks[5].days[3].classname%>"><a href="#"><span><%=weeks[5].days[3].text%></span></a></td>', '<td class="<%=weeks[5].days[4].classname%>"><a href="#"><span><%=weeks[5].days[4].text%></span></a></td>', '<td class="<%=weeks[5].days[5].classname%>"><a href="#"><span><%=weeks[5].days[5].text%></span></a></td>', '<td class="<%=weeks[5].days[6].classname%>"><a href="#"><span><%=weeks[5].days[6].text%></span></a></td>', '</tr>', '</tbody>' ], months: [ '<tbody class="<%=className%>">', '<tr>', '<td colspan="2"><a href="#"><span><%=data[0]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[1]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[2]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[3]%></span></a></td>', '</tr>', '<tr>', '<td colspan="2"><a href="#"><span><%=data[4]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[5]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[6]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[7]%></span></a></td>', '</tr>', '<tr>', '<td colspan="2"><a href="#"><span><%=data[8]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[9]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[10]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[11]%></span></a></td>', '</tr>', '</tbody>' ] }, defaults = { flat: false, starts: 1, prev: '&nbsp;', next: '&nbsp;', lastSel: false, mode: 'single', calendars: 1, format: 'Y-m-d', position: 'bottom', eventName: 'click', onRender: function(){return {};}, onChange: function(){return true;}, onDayClick: function(){return true;}, onShow: function(){return true;}, onBeforeShow: function(){return true;}, onHide: function(){return true;}, locale: { days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], weekMin: 'wk' } }, fill = function(el) { var options = $(el).data('datepicker'); var cal = $(el); var currentCal = Math.floor(options.calendars/2), date, data, dow, month, cnt = 0, week, days, indic, indic2, html, tblCal; cal.find('td>table tbody').remove(); for (var i = 0; i < options.calendars; i++) { date = new Date(options.current); date.addMonths(-currentCal + i); tblCal = cal.find('table').eq(i+1); switch (tblCal[0].className) { case 'datepickerViewDays': dow = formatDate(date, 'B, Y'); break; case 'datepickerViewMonths': dow = date.getFullYear(); break; case 'datepickerViewYears': dow = (date.getFullYear()-6) + ' - ' + (date.getFullYear()+5); break; } tblCal.find('thead tr:first th:eq(1) span').text(dow); dow = date.getFullYear()-6; data = { data: [], className: 'datepickerYears' } for ( var j = 0; j < 12; j++) { data.data.push(dow + j); } html = tmpl(tpl.months.join(''), data); date.setDate(1); data = {weeks:[], test: 10}; month = date.getMonth(); var dow = (date.getDay() - options.starts) % 7; date.addDays(-(dow + (dow < 0 ? 7 : 0))); week = -1; cnt = 0; while (cnt < 42) { indic = parseInt(cnt/7,10); indic2 = cnt%7; if (!data.weeks[indic]) { week = date.getWeekNumber(); data.weeks[indic] = { week: week, days: [] }; } data.weeks[indic].days[indic2] = { text: date.getDate(), classname: [] }; if (month != date.getMonth()) { data.weeks[indic].days[indic2].classname.push('datepickerNotInMonth'); } if (date.getDay() == 0) { data.weeks[indic].days[indic2].classname.push('datepickerSunday'); } if (date.getDay() == 6) { data.weeks[indic].days[indic2].classname.push('datepickerSaturday'); } var fromUser = options.onRender(date); var val = date.valueOf(); if (fromUser.selected || options.date == val || $.inArray(val, options.date) > -1 || (options.mode == 'range' && val >= options.date[0] && val <= options.date[1])) { data.weeks[indic].days[indic2].classname.push('datepickerSelected'); } if (fromUser.disabled) { data.weeks[indic].days[indic2].classname.push('datepickerDisabled'); } if (fromUser.className) { data.weeks[indic].days[indic2].classname.push(fromUser.className); } data.weeks[indic].days[indic2].classname = data.weeks[indic].days[indic2].classname.join(' '); cnt++; date.addDays(1); } html = tmpl(tpl.days.join(''), data) + html; data = { data: options.locale.monthsShort, className: 'datepickerMonths' }; html = tmpl(tpl.months.join(''), data) + html; tblCal.append(html); } }, parseDate = function (date, format) { if (date.constructor == Date) { return new Date(date); } var parts = date.split(/\W+/); var against = format.split(/\W+/), d, m, y, h, min, now = new Date(); for (var i = 0; i < parts.length; i++) { switch (against[i]) { case 'd': case 'e': d = parseInt(parts[i],10); break; case 'm': m = parseInt(parts[i], 10) - 1; break; case 'Y': case 'y': y = parseInt(parts[i], 10); y += y > 100 ? 0 : (y < 29 ? 2000 : 1900); break; case 'H': case 'I': case 'k': case 'l': h = parseInt(parts[i], 10); break; case 'P': case 'p': if (/pm/i.test(parts[i]) && h < 12) { h += 12; } else if (/am/i.test(parts[i]) && h >= 12) { h -= 12; } break; case 'M': min = parseInt(parts[i], 10); break; } } return new Date( $type(y) ? y : now.getFullYear(), $type(m) ? m : now.getMonth(), $type(d) ? d : now.getDate(), $type(h) ? h : now.getHours(), $type(min) ? min : now.getMinutes(), 0 ); /* return new Date( y||now.getFullYear(), m||now.getMonth(), d||now.getDate(), h||now.getHours(), min||now.getMinutes(), 0 ); */ }, formatDate = function(date, format) { var m = date.getMonth(); var d = date.getDate(); var y = date.getFullYear(); var wn = date.getWeekNumber(); var w = date.getDay(); var s = {}; var hr = date.getHours(); var pm = (hr >= 12); var ir = (pm) ? (hr - 12) : hr; var dy = date.getDayOfYear(); if (ir == 0) { ir = 12; } var min = date.getMinutes(); var sec = date.getSeconds(); var parts = format.split(''), part; for ( var i = 0; i < parts.length; i++ ) { part = parts[i]; switch (parts[i]) { case 'a': part = date.getDayName(); break; case 'A': part = date.getDayName(true); break; case 'b': part = date.getMonthName(); break; case 'B': part = date.getMonthName(true); break; case 'C': part = 1 + Math.floor(y / 100); break; case 'd': part = (d < 10) ? ("0" + d) : d; break; case 'e': part = d; break; case 'H': part = (hr < 10) ? ("0" + hr) : hr; break; case 'I': part = (ir < 10) ? ("0" + ir) : ir; break; case 'j': part = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; break; case 'k': part = hr; break; case 'l': part = ir; break; case 'm': part = (m < 9) ? ("0" + (1+m)) : (1+m); break; case 'M': part = (min < 10) ? ("0" + min) : min; break; case 'p': case 'P': part = pm ? "PM" : "AM"; break; case 's': part = Math.floor(date.getTime() / 1000); break; case 'S': part = (sec < 10) ? ("0" + sec) : sec; break; case 'u': part = w + 1; break; case 'w': part = w; break; case 'y': part = ('' + y).substr(2, 2); break; case 'Y': part = y; break; } parts[i] = part; } return parts.join(''); }, extendDate = function(options) { if (Date.prototype.tempDate) { return; } Date.prototype.tempDate = null; Date.prototype.months = options.months; Date.prototype.monthsShort = options.monthsShort; Date.prototype.days = options.days; Date.prototype.daysShort = options.daysShort; Date.prototype.getMonthName = function(fullName) { return this[fullName ? 'months' : 'monthsShort'][this.getMonth()]; }; Date.prototype.getDayName = function(fullName) { return this[fullName ? 'days' : 'daysShort'][this.getDay()]; }; Date.prototype.addDays = function (n) { this.setDate(this.getDate() + n); this.tempDate = this.getDate(); }; Date.prototype.addMonths = function (n) { if (this.tempDate == null) { this.tempDate = this.getDate(); } this.setDate(1); this.setMonth(this.getMonth() + n); this.setDate(Math.min(this.tempDate, this.getMaxDays())); }; Date.prototype.addYears = function (n) { if (this.tempDate == null) { this.tempDate = this.getDate(); } this.setDate(1); this.setFullYear(this.getFullYear() + n); this.setDate(Math.min(this.tempDate, this.getMaxDays())); }; Date.prototype.getMaxDays = function() { var tmpDate = new Date(Date.parse(this)), d = 28, m; m = tmpDate.getMonth(); d = 28; while (tmpDate.getMonth() == m) { d ++; tmpDate.setDate(d); } return d - 1; }; Date.prototype.getFirstDay = function() { var tmpDate = new Date(Date.parse(this)); tmpDate.setDate(1); return tmpDate.getDay(); }; Date.prototype.getWeekNumber = function() { var tempDate = new Date(this); tempDate.setDate(tempDate.getDate() - (tempDate.getDay() + 6) % 7 + 3); var dms = tempDate.valueOf(); tempDate.setMonth(0); tempDate.setDate(4); return Math.round((dms - tempDate.valueOf()) / (604800000)) + 1; }; Date.prototype.getDayOfYear = function() { var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0); var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0); var time = now - then; return Math.floor(time / 24*60*60*1000); }; }, layout = function (el) { var options = $(el).data('datepicker'); var cal = $('#' + options.id); if (!options.extraHeight) { var divs = $(el).find('div'); options.extraHeight = divs.get(0).offsetHeight + divs.get(1).offsetHeight; options.extraWidth = divs.get(2).offsetWidth + divs.get(3).offsetWidth; } var tbl = cal.find('table:first').get(0); var width = tbl.offsetWidth; var height = tbl.offsetHeight; cal.css({ width: width + options.extraWidth + 'px', height: height + options.extraHeight + 'px' }).find('div.datepickerContainer').css({ width: width + 'px', height: height + 'px' }); }, click = function(ev) { if ($(ev.target).is('span')) { ev.target = ev.target.parentNode; } var el = $(ev.target); if (el.is('a')) { ev.target.blur(); if (el.hasClass('datepickerDisabled')) { return false; } var options = $(this).data('datepicker'); var parentEl = el.parent(); var tblEl = parentEl.parent().parent().parent(); var tblIndex = $('table', this).index(tblEl.get(0)) - 1; var tmp = new Date(options.current); var changed = false; var fillIt = false; var dayClicked = false; if (parentEl.is('th')) { if (parentEl.hasClass('datepickerWeek') && options.mode == 'range' && !parentEl.next().hasClass('datepickerDisabled')) { var val = parseInt(parentEl.next().text(), 10); tmp.addMonths(tblIndex - Math.floor(options.calendars/2)); if (parentEl.next().hasClass('datepickerNotInMonth')) { tmp.addMonths(val > 15 ? -1 : 1); } tmp.setDate(val); options.date[0] = (tmp.setHours(0,0,0,0)).valueOf(); tmp.setHours(23,59,59,0); tmp.addDays(6); options.date[1] = tmp.valueOf(); fillIt = true; changed = true; options.lastSel = false; } else if (parentEl.hasClass('datepickerMonth')) { tmp.addMonths(tblIndex - Math.floor(options.calendars/2)); switch (tblEl.get(0).className) { case 'datepickerViewDays': tblEl.get(0).className = 'datepickerViewMonths'; el.find('span').text(tmp.getFullYear()); break; case 'datepickerViewMonths': tblEl.get(0).className = 'datepickerViewYears'; el.find('span').text((tmp.getFullYear()-6) + ' - ' + (tmp.getFullYear()+5)); break; case 'datepickerViewYears': tblEl.get(0).className = 'datepickerViewDays'; el.find('span').text(formatDate(tmp, 'B, Y')); break; } } else if (parentEl.parent().parent().is('thead')) { switch (tblEl.get(0).className) { case 'datepickerViewDays': options.current.addMonths(parentEl.hasClass('datepickerGoPrev') ? -1 : 1); break; case 'datepickerViewMonths': options.current.addYears(parentEl.hasClass('datepickerGoPrev') ? -1 : 1); break; case 'datepickerViewYears': options.current.addYears(parentEl.hasClass('datepickerGoPrev') ? -12 : 12); break; } fillIt = true; } } else if (parentEl.is('td') && !parentEl.hasClass('datepickerDisabled')) { switch (tblEl.get(0).className) { case 'datepickerViewMonths': options.current.setMonth(tblEl.find('tbody.datepickerMonths td').index(parentEl)); options.current.setFullYear(parseInt(tblEl.find('thead th.datepickerMonth span').text(), 10)); options.current.addMonths(Math.floor(options.calendars/2) - tblIndex); tblEl.get(0).className = 'datepickerViewDays'; break; case 'datepickerViewYears': options.current.setFullYear(parseInt(el.text(), 10)); tblEl.get(0).className = 'datepickerViewMonths'; break; default: dayClicked = true; var val = parseInt(el.text(), 10); tmp.addMonths(tblIndex - Math.floor(options.calendars/2)); if (parentEl.hasClass('datepickerNotInMonth')) { tmp.addMonths(val > 15 ? -1 : 1); } tmp.setDate(val); switch (options.mode) { case 'multiple': val = (tmp.setHours(0,0,0,0)).valueOf(); if ($.inArray(val, options.date) > -1) { $.each(options.date, function(nr, dat){ if (dat == val) { delete options.date[nr]; return false; } }); } else { options.date.push(val); } break; case 'range': if (!options.lastSel) { options.date[0] = (tmp.setHours(0,0,0,0)).valueOf(); } val = (tmp.setHours(23,59,59,0)).valueOf(); if (val < options.date[0]) { options.date[1] = options.date[0] + 86399000; options.date[0] = val - 86399000; } else { options.date[1] = val; } options.lastSel = !options.lastSel; break; default: options.date = tmp.valueOf(); break; } break; } fillIt = true; changed = true; } if (fillIt) { fill(this); } if (changed) { options.onChange.apply(this, prepareDate(options)); } if (dayClicked) { options.onDayClick.apply(this, prepareDate(options)); } } return false; }, prepareDate = function (options) { var tmp; if (options.mode == 'single') { tmp = new Date(options.date); return [formatDate(tmp, options.format), tmp]; } else { tmp = [[],[]]; $.each(options.date, function(nr, val){ var date = new Date(val); tmp[0].push(formatDate(date, options.format)); tmp[1].push(date); }); return tmp; } }, getViewport = function () { var m = document.compatMode == 'CSS1Compat'; return { l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft), t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop), w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth), h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight) }; }, isChildOf = function(parentEl, el, container) { if (parentEl == el) { return true; } if (parentEl.contains) { return parentEl.contains(el); } if ( parentEl.compareDocumentPosition ) { return !!(parentEl.compareDocumentPosition(el) & 16); } var prEl = el.parentNode; while(prEl && prEl != container) { if (prEl == parentEl) return true; prEl = prEl.parentNode; } return false; }, show = function (ev) { var cal = $('#' + $(this).data('datepickerId')); if (!cal.is(':visible')) { var calEl = cal.get(0); var options = cal.data('datepicker'); options.onBeforeShow.apply(this, [cal.get(0)]); var pos = $(this).offset(); var viewPort = getViewport(); var top = pos.top; var left = pos.left; var oldDisplay = $.curCSS(calEl, 'display'); cal.css({ visibility: 'hidden', display: 'block' }); layout(calEl); switch (options.position){ case 'top': top -= calEl.offsetHeight; break; case 'left': left -= calEl.offsetWidth; break; case 'right': left += this.offsetWidth; break; case 'bottom': top += this.offsetHeight; break; } if (top + calEl.offsetHeight > viewPort.t + viewPort.h) { top = pos.top - calEl.offsetHeight; } if (top < viewPort.t) { top = pos.top + this.offsetHeight + calEl.offsetHeight; } if (left + calEl.offsetWidth > viewPort.l + viewPort.w) { left = pos.left - calEl.offsetWidth; } if (left < viewPort.l) { left = pos.left + this.offsetWidth } cal.css({ visibility: 'visible', display: 'block', top: top + 'px', left: left + 'px' }); if (options.onShow.apply(this, [cal.get(0)]) != false) { cal.show(); } $(document).bind('mousedown', {cal: cal, trigger: this}, hide); } return false; }, hide = function (ev) { if (ev.target != ev.data.trigger && !isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) { if (ev.data.cal.data('datepicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) { ev.data.cal.hide(); } $(document).unbind('mousedown', hide); } }; return { init: function(options){ options = $.extend({}, defaults, options||{}); extendDate(options.locale); options.calendars = Math.max(1, parseInt(options.calendars,10)||1); options.mode = /single|multiple|range/.test(options.mode) ? options.mode : 'single'; return this.each(function(){ if (!$(this).data('datepicker')) { if (options.date.constructor == String) { options.date = parseDate(options.date, options.format); options.date.setHours(0,0,0,0); } if (options.mode != 'single') { if (options.date.constructor != Array) { options.date = [options.date.valueOf()]; if (options.mode == 'range') { options.date.push(((new Date(options.date[0])).setHours(23,59,59,0)).valueOf()); } } else { for (var i = 0; i < options.date.length; i++) { options.date[i] = (parseDate(options.date[i], options.format).setHours(0,0,0,0)).valueOf(); } if (options.mode == 'range') { options.date[1] = ((new Date(options.date[1])).setHours(23,59,59,0)).valueOf(); } } } else { options.date = options.date.valueOf(); } if (!options.current) { options.current = new Date(); } else { options.current = parseDate(options.current, options.format); } options.current.setDate(1); options.current.setHours(0,0,0,0); var id = 'datepicker_' + parseInt(Math.random() * 1000), cnt; options.id = id; $(this).data('datepickerId', options.id); var cal = $(tpl.wrapper).attr('id', id).bind('click', click).data('datepicker', options); if (options.className) { cal.addClass(options.className); } for (var i = 0; i < options.calendars; i++) { cnt = options.starts; cal.find('tr:first').append( i > 0 ? tpl.space: '', tmpl(tpl.head.join(''), { week: options.locale.weekMin, prev: options.prev, next: options.next, day1: options.locale.daysMin[(cnt++)%7], day2: options.locale.daysMin[(cnt++)%7], day3: options.locale.daysMin[(cnt++)%7], day4: options.locale.daysMin[(cnt++)%7], day5: options.locale.daysMin[(cnt++)%7], day6: options.locale.daysMin[(cnt++)%7], day7: options.locale.daysMin[(cnt++)%7] }) ); } cal.find('tr:first table').addClass('datepickerViewDays'); fill(cal.get(0)); if (options.flat) { cal.appendTo(this).show().css('position', 'relative'); layout(cal.get(0)); } else { cal.appendTo(document.body); $(this).bind(options.eventName, show); } } }); }, showPicker: function() { return this.each( function () { if ($(this).data('datepickerId')) { show.apply(this); } }); }, hidePicker: function() { return this.each( function () { if ($(this).data('datepickerId')) { $('#' + $(this).data('datepickerId')).hide(); } }); }, setDate: function(date, shiftTo){ return this.each(function(){ if ($(this).data('datepickerId')) { var cal = $('#' + $(this).data('datepickerId')); var options = cal.data('datepicker'); options.date = date; if (options.date.constructor == String) { options.date = parseDate(options.date, options.format); options.date.setHours(0,0,0,0); } if (options.mode != 'single') { if (options.date.constructor != Array) { options.date = [options.date.valueOf()]; if (options.mode == 'range') { options.date.push(((new Date(options.date[0])).setHours(23,59,59,0)).valueOf()); } } else { for (var i = 0; i < options.date.length; i++) { options.date[i] = (parseDate(options.date[i], options.format).setHours(0,0,0,0)).valueOf(); } if (options.mode == 'range') { options.date[1] = ((new Date(options.date[1])).setHours(23,59,59,0)).valueOf(); } } } else { options.date = options.date.valueOf(); } if (shiftTo) { options.current = new Date (options.mode != 'single' ? options.date[0] : options.date); } fill(cal.get(0)); } }); }, getDate: function(formated) { if (this.size() > 0) { return prepareDate($('#' + $(this).data('datepickerId')).data('datepicker'))[formated ? 0 : 1]; } } }; }(); $.fn.extend({ DatePicker: DatePicker.init, DatePickerHide: DatePicker.hide, DatePickerShow: DatePicker.show, DatePickerSetDate: DatePicker.setDate, DatePickerGetDate: DatePicker.getDate }); })(jQuery); (function(){ var cache = {}; this.tmpl = function tmpl(str, data){ // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template // generator (and which will be cached). new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){} "with(obj){p.push('" + // Convert the template into pure JavaScript str .replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn( data ) : fn; }; })();
JavaScript
var AceWrapper = new Class({ Implements: [Options, Events], options: { showInvisibles: true, highlightActiveLine: true, showGutter: true, showPrintMargin: true, highlightSelectedWord: false, hScrollBarAlwaysVisible: false, useSoftTabs: true, tabSize: 4, fontSize: 12, wrapMode: 'off', readOnly: false, theme: 'textmate', folding: 'manual' }, fullscreen_title_off: 'Enter fullscreen mode: <strong>ctrl+alt+f</strong>', fullscreen_title_on: 'Exit fullscreen mode: <strong>ctrl+alt+f</strong> or <strong>esc</strong>', initialize: function(textarea, language, options) { this.setOptions(options); this.textarea = $(textarea); this.textarea.hide(); this.bound_resize = this._update_size_fullscreen.bind(this); this.bound_keydown = this._keydown.bind(this); this.code_wrapper = this.textarea.getParent(); this.field_container = this.code_wrapper.getParent(); var ui_wrapper = this.ui_wrapper = new Element('div', {'class': 'code_editor_wrapper'}).inject(this.field_container, 'bottom'), height = Cookie.read(this.field_container.get('id')+'editor_size'); this.code_wrapper.inject(this.ui_wrapper); this.pre = new Element('pre', { 'styles': { 'fontSize': this.options.fontSize + 'px' }, 'class': 'form-ace-editor', 'id': this.textarea.get('id') + 'pre' }).inject(this.textarea.getParent(), 'bottom'); this.editor = ace.edit(this.pre.get('id')); Asset.javascript(phpr_url('vendor/ace/theme-'+this.options.theme+'.js'), {onload: function() { this.editor.setTheme('ace/theme/'+this.options.theme); }.bind(this)}); this.editor.getSession().setValue(this.textarea.get('value')); if (language.length) Asset.javascript(phpr_url('vendor/ace/mode-'+language+'.js'), {onload: this._language_loaded.bind(this, language)}); var textarea_id = this.textarea.get('id'), self = this; this.editor.getSession().on('change', function(){ window.fireEvent('phpr_codeeditor_changed', textarea_id); }); this.editor.on('focus', function(){ ui_wrapper.addClass('focused'); phpr_active_code_editor = textarea_id; }); this.editor.on('blur', function(){ui_wrapper.removeClass('focused');}); phpr_code_editors.push({'id': textarea_id, 'editor': this.editor}); window.fireEvent('phpr_codeeditor_initialized', [textarea_id, this.editor]) /* * Configure */ this.editor.wrapper = this; this.editor.setShowInvisibles(this.options.showInvisibles); this.editor.setHighlightActiveLine(this.options.highlightActiveLine); this.editor.renderer.setShowGutter(this.options.showGutter); this.editor.renderer.setShowPrintMargin(this.options.showPrintMargin); this.editor.setHighlightSelectedWord(this.options.highlightSelectedWord); this.editor.renderer.setHScrollBarAlwaysVisible(this.options.hScrollBarAlwaysVisible); this.editor.getSession().setUseSoftTabs(this.options.useSoftTabs); this.editor.getSession().setTabSize(this.options.tabSize); this.editor.setReadOnly(this.options.readOnly); this.editor.getSession().setFoldStyle(this.options.folding); var session = this.editor.getSession(), renderer = this.editor.renderer; switch (this.options.wrapMode) { case "off": session.setUseWrapMode(false); renderer.setPrintMarginColumn(80); break; case "40": session.setUseWrapMode(true); session.setWrapLimitRange(40, 40); renderer.setPrintMarginColumn(40); break; case "80": session.setUseWrapMode(true); session.setWrapLimitRange(80, 80); renderer.setPrintMarginColumn(80); break; case "free": session.setUseWrapMode(true); session.setWrapLimitRange(null, null); renderer.setPrintMarginColumn(80); break; } window.addEvent('phprformsave', this._save.bind(this)); this.code_wrapper.bindKeys({'ctrl+alt+f': function(event) { self._fullscreen_mode(); }}); /* * Create the footer */ var footer = new Element('div', {'class': 'code_editor_footer'}).inject(this.ui_wrapper, 'bottom'); this.resize_handle = new Element('div', {'class': 'resize_handle'}).inject(footer, 'bottom'); new Drag(this.code_wrapper, { 'handle': this.resize_handle, 'modifiers': {'x': '', 'y': 'height'}, 'limit': {'y': [100, 3000]}, onDrag: function(){ this.fireEvent('resize', this); this.editor.resize(); }.bind(this), onComplete: function(){ this.editor.resize(); window.fireEvent('phpr_editor_resized'); Cookie.write(this.field_container.get('id')+'editor_size', this.code_wrapper.getSize().y, {duration: 365, path: '/'}); }.bind(this) }); /* * Create the toolbar */ this.toolbar = new Element('div', {'class': 'code_editor_toolbar hidden'}).inject(this.code_wrapper, 'top'); this.toolbar.set('morph', {duration: 'short', transition: Fx.Transitions.Sine.easeOut, onComplete: this._toolbar_effect_complete.bind(this)}); this.displaying_toolbar = false; this.ui_wrapper.addEvent('mousemove', this._display_toolbar.bind(this)); /* * Create buttons */ var list = new Element('ul').inject(this.toolbar); this.fullscreen_btn = new Element('li', {'class': 'fullscreen tooltip', 'title': this.fullscreen_title_off}).inject(list); var fullscreen_btn_link = new Element('a', {'href': 'javascript:;'}).inject(this.fullscreen_btn); fullscreen_btn_link.addEvent('click', this._fullscreen_mode.bind(this)); new Element('div', {'class': 'clear'}).inject(this.toolbar, 'bottom'); update_tooltips(); /* * Update height from cookies */ if (height !== null) { this.code_wrapper.setStyle('height', height+'px'); window.fireEvent('phpr_editor_resized'); } }, setFontSize: function(size) { this.pre.setStyle('fontSize', size + 'px'); }, update: function() { this.editor.resize(); }, _language_loaded: function(language) { var mode = require('ace/mode/'+language).Mode; this.editor.getSession().setMode(new mode()); }, _save: function() { this.textarea.set('value', this.editor.getSession().getValue()); }, _fullscreen_mode: function() { if (!this.field_container.hasClass('fullscreen')) { this.normal_scroll = window.getScroll(); this.original_container_parent = this.field_container.getParent(); this.field_container.addClass('fullscreen'); document.body.setStyle('overflow', 'hidden'); window.scrollTo(0, 0); // Fix for Chrome this.field_container.style.display= "none"; var redrawFix = this.field_container.offsetHeight; this.field_container.style.display="block"; this._update_size_fullscreen(); window.addEvent('resize', this.bound_resize); document.addEvent('keydown', this.bound_keydown); this.fullscreen_btn.set('title', this.fullscreen_title_on); } else { document.removeEvent('keydown', this.bound_keydown); this.field_container.removeClass('fullscreen') document.body.setStyle('overflow', 'visible'); window.removeEvent('resize', this.bound_resize); this.pre.setStyle('height', 'auto'); window.scrollTo(this.normal_scroll.x, this.normal_scroll.y); this.editor.resize(); this.editor.focus(); this.fullscreen_btn.set('title', this.fullscreen_title_off); } }, _keydown: function(event) { if (event.key == 'esc') { this._fullscreen_mode(); event.stop(); return false; } }, _update_size_fullscreen: function() { var window_size = window.getSize(); this.pre.setStyle('height', window_size.y + 'px'); this.editor.resize(); }, _display_toolbar: function() { if (this.displaying_toolbar) { if (this.hide_toolbar_timer !== undefined) $clear(this.hide_toolbar_timer); this.hide_toolbar_timer = this._hide_toolbar.delay(2000, this); return; } this.displaying_toolbar = true; this.hiding_toolbar = false; this.toolbar.show(); this.toolbar.morph({'opacity': [0, 1]}); }, _hide_toolbar: function() { this.hiding_toolbar = true; this.toolbar.morph({'opacity': [1, 0]}); }, _toolbar_effect_complete: function() { if (this.hiding_toolbar) { this.toolbar.hide(); this.displaying_toolbar = false; } } })
JavaScript
function multi_textarea_init(field_id, set_value) { // Spool exisiting data try { if (set_value != "") jQuery.each(jQuery.parseJSON(set_value), function(k,v){ multi_textarea_build_shell(field_id, v); }); } catch(e) { }; // Bind events jQuery('#multi_textarea'+field_id+' .multi_textarea_field').live('change', function(){ multi_textarea_change(field_id); }); } function multi_textarea_change(field_id) { var field = jQuery('#'+field_id); var obj_data = multi_textarea_compile(field_id); field.val(jQuery.stringify(obj_data)); } function multi_textarea_compile(field_id) { var field_container = jQuery('#multi_textarea' + field_id); var arr = []; field_container.find('.multi_textarea_object').each(function(){ var obj = {}; jQuery(this).find('.multi_textarea_field').each(function() { var obj_name = jQuery(this).attr('data-object-name'); obj[obj_name] = jQuery(this).val(); }); arr.push(obj); }); return arr; } function multi_textarea_add_field(field_id) { return jQuery('#multi_textarea'+field_id+' .multi_textarea_shell') .clone() .removeClass('multi_textarea_shell') .addClass('multi_textarea_object') .show() .appendTo('#multi_textarea'+field_id); } function multi_textarea_build_shell(field_id, data) { var shell = multi_textarea_add_field(field_id); jQuery.each(data, function(k,v) { shell.find('[data-object-name="'+k+'"]').val(v); }); }
JavaScript
var FileUploader = new Class({ Extends: FancyUpload2, initialize: function(fieldId, options) { this.files = []; this.fieldId = fieldId; var defaultOptions = { instantStart: true, allowDuplicates: true, processResponse: true, fieldName: 'file', debug: false, path: phpr_url('modules/db/behaviors/db_formbehavior/resources/swf/Swiff.Uploader.swf') }; options = $merge(defaultOptions, options); if (options.callBacks) { this.addEvents(options.callBacks); options.callBacks = null; } this.parent(null, null, options); }, showProgress: function() { this.linkElement.setStyle('visibility', 'hidden'); this.uploadProgress.removeClass('invisible'); }, hideProgress: function() { this.linkElement.setStyle('visibility', 'visible'); this.uploadProgress.addClass('invisible'); }, onSelect: function(file, index, length) { var errors = []; if (this.options.limitSize && (file.size > this.options.limitSize)) errors.push('size'); if (this.options.limitFiles && (this.countFiles() >= this.options.limitFiles)) errors.push('length'); if (!this.options.allowDuplicates && this.getFile(file)) errors.push('duplicate'); if (!this.options.validateFile.call(this, file, errors)) errors.push('custom'); if (errors.length) { var fn = this.options.fileInvalid; if (fn) fn.call(this, file, errors); return false; } this.files.push(file); this.showProgress(); return true; }, render: function() { this.field = $(this.fieldId); this.linkElement = this.field.getElement('a'); this.uploadProgress = this.field.getElement('img'); this.linkElement.addEvent('click', (function() { this.browse(); return false; }).bind(this)); this.overallProgress = new Fx.ProgressBar(this.uploadProgress, {}); }, updateOverall: function(bytesTotal) { this.bytesTotal = bytesTotal; }, onOpen: function(file, overall) { this.log('Starting upload "{name}".', file); file = this.getFile(file); if(file.element) file.element.addClass('file-uploading'); }, onProgress: function(file, current, overall) { this.overallProgress.start(overall.bytesLoaded, overall.bytesTotal); }, onComplete: function(file, response) { this.log('Completed upload "' + file.name + '".', arguments); (this.options.fileComplete || this.fileComplete).call(this, this.finishFile(file), response); }, onAllSelect: function(files, current, overall) { this.log('Added ' + files.length + ' files, now we have (' + current.bytesTotal + ' bytes).', arguments); this.updateOverall(current.bytesTotal); if (this.files.length && this.options.instantStart) this.upload.delay(10, this); }, onAllComplete: function(current) { this.log('Completed all files, ' + current.bytesTotal + ' bytes.', arguments); this.updateOverall(current.bytesTotal); this.overallProgress.start(100); this.fireEvent.delay(500, this, ['uploadComplete', this]); this.hideProgress.delay(500, this); }, fileComplete: function(file, response) { var json = $H(JSON.decode(response, true)); if (json.get('result') != 'success') { alert('Error uploading file '+file.name+'. '+json.get('error')); } } });
JavaScript
/** * FancyUpload - Flash meets Ajax for powerful and elegant uploads. * * @version 2.1 * * @license MIT License * * @author Harald Kirschner <mail [at] digitarald [dot] de> * @copyright Authors */ var FancyUpload2 = new Class({ Extends: Swiff.Uploader, options: { limitSize: false, limitFiles: 1000, instantStart: false, allowDuplicates: false, validateFile: $lambda(true), // provide a function that returns true for valid and false for invalid files. debug: false, fileInvalid: null, // called for invalid files with error stack as 2nd argument fileCreate: null, // creates file element after select fileUpload: null, // called when file is opened for upload, allows to modify the upload options (2nd argument) for every upload fileComplete: null, // updates the file element to completed state and gets the response (2nd argument) fileRemove: null // removes the element /** * Events: * onBrowse, onSelect, onAllSelect, onCancel, onBeforeOpen, onOpen, onProgress, onComplete, onError, onAllComplete */ }, initialize: function(status, list, options) { this.status = $(status); this.list = $(list); this.files = []; if (options.callBacks) { this.addEvents(options.callBacks); options.callBacks = null; } this.parent(options); this.render(); }, render: function() { this.overallTitle = this.status.getElement('.overall-title'); this.currentTitle = this.status.getElement('.current-title'); this.currentText = this.status.getElement('.current-text'); var progress = this.status.getElement('.overall-progress'); this.overallProgress = new Fx.ProgressBar(progress, { text: new Element('span', {'class': 'progress-text'}).inject(progress, 'after') }); progress = this.status.getElement('.current-progress') this.currentProgress = new Fx.ProgressBar(progress, { text: new Element('span', {'class': 'progress-text'}).inject(progress, 'after') }); }, onLoad: function() { this.log('Uploader ready!'); }, onBeforeOpen: function(file, options) { this.log('Initialize upload for "{name}".', file); var fn = this.options.fileUpload; var obj = (fn) ? fn.call(this, this.getFile(file), options) : options; return obj; }, onOpen: function(file, overall) { this.log('Starting upload "{name}".', file); file = this.getFile(file); if(file.element) file.element.addClass('file-uploading'); this.currentProgress.cancel().set(0); this.currentTitle.set('html', 'File Progress "{name}"'.substitute(file) ); }, onProgress: function(file, current, overall) { this.overallProgress.start(overall.bytesLoaded, overall.bytesTotal); this.currentText.set('html', 'Upload with {rate}/s. Time left: ~{timeLeft}'.substitute({ rate: (current.rate) ? this.sizeToKB(current.rate) : '- B', timeLeft: Date.fancyDuration(current.timeLeft || 0) })); this.currentProgress.start(current.bytesLoaded, current.bytesTotal); }, onSelect: function(file, index, length) { var errors = []; if (this.options.limitSize && (file.size > this.options.limitSize)) errors.push('size'); if (this.options.limitFiles && (this.countFiles() >= this.options.limitFiles)) errors.push('length'); if (!this.options.allowDuplicates && this.getFile(file)) errors.push('duplicate'); if (!this.options.validateFile.call(this, file, errors)) errors.push('custom'); if (errors.length) { var fn = this.options.fileInvalid; if (fn) fn.call(this, file, errors); return false; } (this.options.fileCreate || this.fileCreate).call(this, file); this.files.push(file); return true; }, onAllSelect: function(files, current, overall) { this.log('Added ' + files.length + ' files, now we have (' + current.bytesTotal + ' bytes).', arguments); this.updateOverall(current.bytesTotal); if (this.status) this.status.removeClass('status-browsing'); if (this.files.length && this.options.instantStart) this.upload.delay(10, this); }, onComplete: function(file, response) { this.log('Completed upload "' + file.name + '".', arguments); this.currentText.set('html', 'Upload complete!'); this.currentProgress.start(100); (this.options.fileComplete || this.fileComplete).call(this, this.finishFile(file), response); }, onError: function(file, error, info) { this.log('Upload "' + file.name + '" failed. "{1}": "{2}".', arguments); (this.options.fileError || this.fileError).call(this, this.finishFile(file), error, info); }, onCancel: function() { this.log('Filebrowser cancelled.', arguments); if (this.status) this.status.removeClass('file-browsing'); }, onAllComplete: function(current) { this.log('Completed all files, ' + current.bytesTotal + ' bytes.', arguments); this.updateOverall(current.bytesTotal); this.overallProgress.start(100); if (this.status) this.status.removeClass('file-uploading'); }, browse: function(fileList) { var ret = this.parent(fileList); if (ret !== true){ if (ret) this.log('An error occured: ' + ret); else this.log('Browse in progress.'); } else { this.log('Browse started.'); if (this.status) this.status.addClass('file-browsing'); } }, upload: function(options) { var ret = this.parent(options); if (ret !== true) { this.log('Upload in progress or nothing to upload.'); if (ret) alert(ret); } else { this.log('Upload started.'); if (this.status) this.status.addClass('file-uploading'); this.overallProgress.set(0); } }, removeFile: function(file) { var remove = this.options.fileRemove || this.fileRemove; if (!file) { this.files.each(remove, this); this.files.empty(); this.updateOverall(0); } else { if (!file.element) file = this.getFile(file); this.files.erase(file); remove.call(this, file); this.updateOverall(this.bytesTotal - file.size); } this.parent(file); }, getFile: function(file) { var ret = null; this.files.some(function(value) { if ((value.name != file.name) || (value.size != file.size)) return false; ret = value; return true; }); return ret; }, countFiles: function() { var ret = 0; for (var i = 0, j = this.files.length; i < j; i++) { if (!this.files[i].finished) ret++; } return ret; }, updateOverall: function(bytesTotal) { this.bytesTotal = bytesTotal; this.overallTitle.set('html', 'Overall Progress (' + this.sizeToKB(bytesTotal) + ')'); }, finishFile: function(file) { try { file = this.getFile(file); if ($(file.element)) file.element.removeClass('file-uploading'); file.finished = true; return file; } catch(err) { } }, fileCreate: function(file) { file.info = new Element('span', {'class': 'file-info'}); file.element = new Element('li', {'class': 'file'}).adopt( new Element('span', {'class': 'file-size', 'html': this.sizeToKB(file.size)}), new Element('a', { 'class': 'file-remove', 'href': '#', 'html': 'Remove', 'events': { 'click': function() { this.removeFile(file); return false; }.bind(this) } }), new Element('span', {'class': 'file-name', 'html': file.name}), file.info ).inject(this.list); }, fileComplete: function(file, response) { this.options.processResponse || this var json = $H(JSON.decode(response, true)); if (json.get('result') == 'success') { file.element.addClass('file-success'); file.info.set('html', json.get('size')); } else { file.element.addClass('file-failed'); file.info.set('html', json.get('error') || response); } }, fileError: function(file, error, info) { file.element.addClass('file-failed'); file.info.set('html', '<strong>' + error + '</strong><br />' + info); }, fileRemove: function(file) { file.element.fade('out').retrieve('tween').chain(Element.destroy.bind(Element, file.element)); }, sizeToKB: function(size) { var unit = 'B'; if ((size / 1048576) > 1) { unit = 'MB'; size /= 1048576; } else if ((size / 1024) > 1) { unit = 'kB'; size /= 1024; } return size.round(1) + ' ' + unit; }, log: function(text, args) { if (this.options.debug && window.console) console.log(text.substitute(args || {})); } }); /** * @todo Clean-up, into Date.js */ Date.parseDuration = function(sec) { var units = {}, conv = Date.durations; for (var unit in conv) { var value = Math.floor(sec / conv[unit]); if (value) { units[unit] = value; if (!(sec -= value * conv[unit])) break; } } return units; }; Date.fancyDuration = function(sec) { var ret = [], units = Date.parseDuration(sec); for (var unit in units) ret.push(units[unit] + Date.durationsAbbr[unit]); return ret.join(', '); }; Date.durations = {years: 31556926, months: 2629743.83, days: 86400, hours: 3600, minutes: 60, seconds: 1, milliseconds: 0.001}; Date.durationsAbbr = { years: 'j', months: 'm', days: 'd', hours: 'h', minutes: 'min', seconds: 'sec', milliseconds: 'ms' };
JavaScript
/** * Fx.ProgressBar * * @version 1.0 * * @license MIT License * * @author Harald Kirschner <mail [at] digitarald [dot] de> * @copyright Authors */ Fx.ProgressBar = new Class({ Extends: Fx, options: { text: null, transition: Fx.Transitions.Circ.easeOut, link: 'cancel' }, initialize: function(element, options) { this.element = $(element); this.parent(options); this.text = $(this.options.text); this.set(0); }, start: function(to, total) { return this.parent(this.now, (arguments.length == 1) ? to.limit(0, 100) : to / total * 100); }, set: function(to) { this.now = to; this.element.setStyle('backgroundPosition', (100 - to) + '% 0px'); if (this.text) this.text.set('text', Math.round(to) + '%'); return this; } });
JavaScript
var GridControlManagerClass = new Class({ controls: null, initialize: function(table) { this.controls = new Hash(); }, register_control: function(id, control_obj) { this.controls.set(id, control_obj); }, get_control: function(id) { return this.controls.get(id); } }); var GridControlManager = new GridControlManagerClass(); var GridControl = new Class({ Implements: [Options, Events], table: null, table_id: null, width_set:false, grid_container: null, current_row: null, current_input: null, table_head_cells: null, scroller: null, sortables: null, mouse_move_timer: null, options: { autocomplete_config: [], no_toolbar: false, allow_adding_rows: true, allow_deleting_rows: true, no_sorting: false }, initialize: function(table, options) { this.setOptions(options); this.table = $(table); var reference_control = this.table; if (!this.table) reference_control = $(table + '_editing_disabled'); this.grid_container = reference_control.selectParent('div.grid_container'); this.table_head_cells = this.grid_container.getElements('thead th'); this.table_id = table; this.set_widths(); this.assign_rows_events(); if (this.table) { this.table.bindKeys({ 'ctrl+i': this.on_key_insert_row.bind(this), 'ctrl+d': this.on_key_delete_row.bind(this) }); } var scrollable_element = reference_control.selectParent('div.backend_scroller'); this.scroller = new BackendVScroller(scrollable_element, { slider_height_tweak: -16, auto_hide_slider: true, position_threshold: 9 }); window.addEvent('mousemove', this.trigger_scroller.bind(this)); scrollable_element.addEvent('mousewheel', this.trigger_scroller.bind(this)); GridControlManager.register_control(this.table_id, this); this.init_sortables(); this.autocompleter_visible = false; }, trigger_scroller: function() { this.grid_container.addClass('mouse_move'); $clear(this.mouse_move_timer); this.mouse_move_timer = this.mouse_stop.delay(500, this); }, mouse_stop: function() { $clear(this.mouse_move_timer); this.grid_container.removeClass('mouse_move'); }, init_table: function() { this.table = $(this.table_id); this.width_set = false; if (this.table) { this.table.bindKeys({ 'ctrl+i': this.on_key_insert_row.bind(this), 'ctrl+d': this.on_key_delete_row.bind(this) }); this.set_widths(); this.assign_rows_events(); this.init_sortables(); this.fireEvent('addEnabled', this); } else { this.fireEvent('addDisabled', this); this.fireEvent('deleteDisabled', this); } this.scroller.update(); this.scroller.update_position(); }, assign_rows_events: function() { if (!this.table) return; var rows = this.table.getElements('tbody tr'); var cnt = rows.length; rows.each(this.assign_row_events, this); }, init_sortables: function() { if (!this.table) return; if (this.options.no_sorting) return; if (this.sortables) this.sortables.detach(); this.sortables = new Sortables11(this.table.getElement('tbody'), { startDelay: 300, onDragStart: function(element, ghost){ ghost.destroy(); element.addClass('drag'); }, onDragComplete: function(element, ghost){ this.trash.destroy(); element.removeClass('drag'); } }) }, set_widths: function() { if (!this.table) return; var rows = this.table.getElements('tbody tr'); rows.each(this.set_width, this); window.fireEvent('grid_columns_adjusted', this.table_id); }, set_width: function(row) { if(!this.width_set) { var cells = row.getChildren(); var last_index = cells.length-1; this.table_head_cells.each(function(head_cell, index){ if (cells.length > index && index < last_index) { var tweak = -1; if (index == 0 && !Browser.Engine.gecko) tweak = 0; cells[index].setStyle('width', (head_cell.getSize().x + tweak) + 'px'); } }); this.width_set = true; } }, assign_row_events: function(row) { var cells = row.getElements('td'); var last_index = cells.length-1; cells.each(function(cell, index){ var input = cell.getElement('input'); if ($(input)) { cell.addEvent('click', function(){input.focus()}); $(input).addEvent('focus', this.on_input_focus.bind(this, [row, $(input)])); if (!Browser.Engine.webkit) $(input).addEvent('keypress', this.on_input_keydownn.bindWithEvent(this, [row, $(input)])); else $(input).addEvent('keydown', this.on_input_keydownn.bindWithEvent(this, [row, $(input)])); this.options.autocomplete_config.each(function(ac_params){ if (ac_params.index == index) this.init_autocompleter($(input), ac_params, last_index == index ? null : cells[index + 1]); }, this); } }, this); }, init_autocompleter: function(input, config, next_cell) { if (config.type == 'local') { var width_tweak = 0; if (next_cell) width_tweak += next_cell.getSize().x; else width_tweak = 2; if (Browser.Engine.gecko) width_tweak += 1; var width = config.autowidth ? input.getSize().x + 8 + width_tweak : 300; var common_options = { 'minLength': 1, 'overflow': true, 'className': 'autocompleter-choices grid', 'selectMode': 'selection', 'width': width, 'displayByArrows': false, minLength: 0, delay: 100, onShow: function(){ this.autocompleter_visible = true; }.bind(this), onHide: function(){ this.autocompleter_visible = false; }.bind(this) }; if (!config.depends_on) new Autocompleter.Local(input, config.tokens, common_options); else { new Autocompleter.Request.Local(input, new Hash(config.tokens), $merge( common_options, { requestData: function(request, autocompleter) { var row = input.findParent('tr'); var key = this.get_row_column_value(row, config.depends_on).toUpperCase(); if (autocompleter.tokens.has(key)) return autocompleter.tokens.get(key); return []; }.bind(this) } )); } } }, get_row_column_value: function(row, column_name) { var regex = RegExp("\\["+column_name+"\\]$"); var inputs = row.getElements('input').filter(function(input){ if (regex.test(input.name)) return true; }) if (inputs.length) return inputs[0].value; return ''; }, on_input_focus: function(row, input) { if ($type(row) == 'array') { input = row[1]; row = row[0]; } if (this.options.allow_adding_rows || this.options.allow_deleting_rows) { this.table.getElements('tbody tr').each(function(current_row){ if (row != current_row) current_row.removeClass('current'); }); $(row).addClass('current'); } this.current_row = $(row); this.fireEvent('onRowSelected', [input, this]); this.current_input = $(input); this.check_delete_status(); }, on_input_keydownn: function(event, row, input) { switch (event.key) { case 'right' : if (pos = input.getCaretPosition() == input.value.length) this.move_right(row, input); break; case 'left' : if (input.getCaretPosition() == 0) this.move_left(row, input); break; case 'up' : if (!event.alt) this.move_up(row, input); break; case 'down' : if (!event.alt) this.move_down(row, input); break; case 'tab' : this.scroller.update_position(); break; } }, insert_row: function() { if (!this.table) return; var table_body = this.table.getElement('tbody'); var first_row = table_body.getFirst(); if (!first_row) { alert('Cannot add a row to the empty table'); return; } if (!this.current_row) var row = new Element('tr').inject(table_body); else var row = new Element('tr').inject(this.current_row, 'after'); var first_input = null; var row_index = table_body.getChildren().length; var row_field_name = this.table_id+'_'+row_index+'_'; var column_regexp = new RegExp("^"+this.table_id+"_[0-9]+_"); first_row.getElements('td').each(function(cell_element, index){ var input_element = cell_element.getElement('input'); var column_name = input_element.get('name'); var column = input_element.get('id').replace(column_regexp, ""); var input_id = this.table_id + '_' + row_index + '_' + column; var new_name = column_name.replace(/\[[0-9]+\]\[[^\]]+\]$/, "") + "["+row_index+"]["+column+"]"; var input = new Element('input', {'name': new_name, 'id': input_id, 'type': 'text', 'autocomplete': 'off'}).inject( new Element('div', {'class': 'container'}).inject(new Element('td', {'class': cell_element.className}).inject(row))); if (!first_input) first_input = input; }, this); this.set_width(row); this.assign_row_events(row); first_input.focus(); this.scroller.update(); this.check_delete_status(); this.scroller.update_position.delay(30, this.scroller); this.init_sortables(); this.trigger_scroller(); return false; }, on_key_insert_row: function() { if (this.options.allow_adding_rows) this.insert_row(); }, delete_row: function() { if (!this.table) return; var row = this.current_row; if (!$(row)) return; var prev_row = row.getPrevious(); if (!prev_row) prev_row = row.getNext(); if (!prev_row) return false; var non_empty_inputs = row.getElements('input').filter(function(current_input){ return current_input.value.trim().length > 0; }); if (non_empty_inputs.length) { if (!confirm('Do you really want to delete the current row?')) return false; } var current_input = this.current_input; this.current_input = null; this.current_row = null; if (current_input) this.move_to_row(row, current_input, prev_row); row.destroy(); this.scroller.update(); this.scroller.update_position(); this.check_delete_status(); this.init_sortables(); this.trigger_scroller(); this.width_set = false; var rows = this.table.getElements('tbody tr'); if(rows) this.set_width(rows[0]); }, on_key_delete_row: function() { if (this.options.allow_deleting_rows) this.delete_row(); }, check_delete_status: function() { if (this.table.getElements('tr').length > 1) this.fireEvent('deleteEnabled', this); else this.fireEvent('deleteDisabled', this); }, init_toolbar: function() { if (!this.table) this.fireEvent('addDisabled', this); }, /* * Navigation */ move_right: function(row, input) { var next_cell = input.findParent('td').getNext(); if (next_cell) { input = next_cell.getElement('input'); if (input) input.focus(); return; } else { var next_row = input.findParent('tr').getNext(); if (next_row) { var cells = next_row.getChildren(); if (cells.length > 0) { input = cells[0].getElement('input'); if (input) { input.focus(); this.scroller.update_position(); } } } } }, move_left: function(row, input) { var prev_cell = input.findParent('td').getPrevious(); if (prev_cell) { input = prev_cell.getElement('input'); if (input) input.focus(); return; } else { var prev_row = input.findParent('tr').getPrevious(); if (prev_row) { var cells = prev_row.getChildren(); if (cells.length > 0) { input = cells[cells.length-1].getElement('input'); if (input) { input.focus(); this.scroller.update_position(); } } } } }, move_up: function(row, input) { if (this.autocompleter_visible) return; var prev_row = input.findParent('tr').getPrevious(); if (prev_row) this.move_to_row(row, input, prev_row); }, move_down: function(row, input) { if (this.autocompleter_visible) return; var next_row = input.findParent('tr').getNext(); if (next_row) this.move_to_row(row, input, next_row); }, move_to_row: function(from_row, input, to_row) { var to_cells = to_row.getChildren(); var from_cells = from_row.getChildren(); var from_cell = input.findParent('td'); var index = from_cells.indexOf(from_cell); if (index <= to_cells.length-1) { var input = $(to_cells[index]).getElement('input'); if (input) input.focus(); } this.scroller.update_position(); } });
JavaScript
function filter_add_record(link_element) { /* * Find record ID and description */ link_element = $(link_element); var record_id = link_element.getParent().getElement('input.record_id').value; var cells = link_element.getParent().getParent().getChildren(); var record_name = []; cells.each(function(cell){ if (!cell.hasClass('iconCell') && !cell.hasClass('expandControl')) record_name.push(cell.innerHTML.trim()); }) record_name = record_name.join(', '); var table_body = $('added_filter_list'); /* * Check whether record exists */ var record_exists = table_body.getElements('tr td input.record_id').some(function(field){return field.value == record_id;}) if (record_exists) return false; /* * Create row in the added records list */ var icon_cell_content = '<a class="filter_control" href="#" onclick="return filter_delete_record(this)"><img src="'+phpr_url('modules/db/behaviors/db_filterbehavior/resources/images/remove_record.gif')+'" alt="Remove record" title="Remove record" width="16" height="16"/></a>'; var no_data_row = table_body.getElement('tr.noData'); if (no_data_row) no_data_row.destroy(); var row = new Element('tr').inject(table_body); var iconCell = new Element('td', {'class': 'iconCell'}).inject(row); iconCell.innerHTML = icon_cell_content; var name_cell = new Element('td', {'class': 'last'}).inject(row); name_cell.innerHTML = record_name; new Element('input', {'type': 'hidden', 'name': 'filter_ids[]', 'class': 'record_id', 'value': record_id}).inject(name_cell); if (!(table_body.getChildren().length % 2)) row.addClass('even'); return false; } function filter_delete_record(link_element) { link_element = $(link_element); var table_body = $('added_filter_list'); var row = link_element.getParent().getParent(); row.destroy(); table_body.getChildren().each(function(row, index){ row.removeClass('even'); if (index % 2) row.addClass('even'); }); if (!table_body.getChildren().length) { var row = new Element('tr', {'class': 'noData'}).inject(table_body); var el = new Element('td').inject(row); el.innerHTML = 'No records added'; } return false; }
JavaScript
/* =require foundation/modernizr.foundation =require foundation/jquery.placeholder =require foundation/jquery.foundation.alerts =require foundation/jquery.foundation.accordion =require foundation/jquery.foundation.buttons =require foundation/jquery.foundation.tooltips =require foundation/jquery.foundation.forms =require foundation/jquery.foundation.tabs =require foundation/jquery.foundation.navigation =require foundation/jquery.foundation.topbar =require foundation/jquery.foundation.reveal =require foundation/jquery.foundation.orbit =require foundation/jquery.foundation.mediaQueryToggle =require foundation/app */
JavaScript
;(function ($, window, undefined){ 'use strict'; $.fn.foundationAccordion = function (options) { var $accordion = $('.accordion'); if ($accordion.hasClass('hover') && !Modernizr.touch) { $('.accordion li', this).on({ mouseenter : function () { console.log('due'); var p = $(this).parent(), flyout = $(this).children('.content').first(); $('.content', p).not(flyout).hide().parent('li').removeClass('active'); //changed this flyout.show(0, function () { flyout.parent('li').addClass('active'); }); } }); } else { $('.accordion li', this).on('click.fndtn', function () { var p = $(this).parent(), flyout = $(this).children('.content').first(); $('.content', p).not(flyout).hide().parent('li').removeClass('active'); //changed this flyout.show(0, function () { flyout.parent('li').addClass('active'); }); }); } }; })( jQuery, this );
JavaScript
/* * jQuery Foundation Tooltips 2.0.1 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; var settings = { bodyHeight : 0, targetClass : '.has-tip', tooltipClass : '.tooltip', tipTemplate : function (selector, content) { return '<span data-selector="' + selector + '" class="' + settings.tooltipClass.substring(1) + '">' + content + '<span class="nub"></span></span>'; } }, methods = { init : function (options) { settings = $.extend(settings, options); return this.each(function () { var $body = $('body'); if (Modernizr.touch) { $body.on('click.tooltip touchstart.tooltip touchend.tooltip', settings.targetClass, function (e) { e.preventDefault(); $(settings.tooltipClass).hide(); methods.showOrCreateTip($(this)); }); $body.on('click.tooltip touchstart.tooltip touchend.tooltip', settings.tooltipClass, function (e) { e.preventDefault(); $(this).fadeOut(150); }); } else { $body.on('mouseenter.tooltip mouseleave.tooltip', settings.targetClass, function (e) { var $this = $(this); if (e.type === 'mouseenter') { methods.showOrCreateTip($this); } else if (e.type === 'mouseleave') { methods.hide($this); } }); } $(this).data('tooltips', true); }); }, showOrCreateTip : function ($target) { var $tip = methods.getTip($target); if ($tip && $tip.length > 0) { methods.show($target); } else { methods.create($target); } }, getTip : function ($target) { var selector = methods.selector($target), tip = null; if (selector) { tip = $('span[data-selector=' + selector + ']' + settings.tooltipClass); } return (tip.length > 0) ? tip : false; }, selector : function ($target) { var id = $target.attr('id'), dataSelector = $target.data('selector'); if (id === undefined && dataSelector === undefined) { dataSelector = 'tooltip' + Math.random().toString(36).substring(7); $target.attr('data-selector', dataSelector); } return (id) ? id : dataSelector; }, create : function ($target) { var $tip = $(settings.tipTemplate(methods.selector($target), $('<div>').text($target.attr('title')).html())), classes = methods.inheritable_classes($target); $tip.addClass(classes).appendTo('body'); if (Modernizr.touch) { $tip.append('<span class="tap-to-close">tap to close </span>'); } $target.removeAttr('title'); methods.show($target); }, reposition : function (target, tip, classes) { var width, nub, nubHeight, nubWidth, column, objPos; tip.css('visibility', 'hidden').show(); width = target.data('width'); nub = tip.children('.nub'); nubHeight = nub.outerHeight(); nubWidth = nub.outerWidth(); objPos = function (obj, top, right, bottom, left, width) { return obj.css({ 'top' : top, 'bottom' : bottom, 'left' : left, 'right' : right, 'width' : (width) ? width : 'auto' }).end(); }; objPos(tip, (target.offset().top + target.outerHeight() + 10), 'auto', 'auto', target.offset().left, width); objPos(nub, -nubHeight, 'auto', 'auto', 10); if ($(window).width() < 767) { column = target.closest('.columns'); if (column.length < 0) { // if not using Foundation column = $('body'); } tip.width(column.outerWidth() - 25).css('left', 15).addClass('tip-override'); objPos(nub, -nubHeight, 'auto', 'auto', target.offset().left); } else { if (classes.indexOf('tip-top') > -1) { objPos(tip, (target.offset().top - tip.outerHeight() - nubHeight), 'auto', 'auto', target.offset().left, width) .removeClass('tip-override'); objPos(nub, 'auto', 'auto', -nubHeight, 'auto'); } else if (classes.indexOf('tip-left') > -1) { objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), 'auto', 'auto', (target.offset().left - tip.outerWidth() - 10), width) .removeClass('tip-override'); objPos(nub, (tip.outerHeight() / 2) - (nubHeight / 2), -nubHeight, 'auto', 'auto'); } else if (classes.indexOf('tip-right') > -1) { objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), 'auto', 'auto', (target.offset().left + target.outerWidth() + 10), width) .removeClass('tip-override'); objPos(nub, (tip.outerHeight() / 2) - (nubHeight / 2), 'auto', 'auto', -nubHeight); } } tip.css('visibility', 'visible').hide(); }, inheritable_classes : function (target) { var inheritables = ['tip-top', 'tip-left', 'tip-bottom', 'tip-right', 'noradius'], filtered = $.map(target.attr('class').split(' '), function (el, i) { if ($.inArray(el, inheritables) !== -1) { return el; } }).join(' '); return $.trim(filtered); }, show : function ($target) { var $tip = methods.getTip($target); methods.reposition($target, $tip, $target.attr('class')); $tip.fadeIn(150); }, hide : function ($target) { var $tip = methods.getTip($target); $tip.fadeOut(150); }, reload : function () { var $self = $(this); return ($self.data('tooltips')) ? $self.foundationTooltips('destroy').foundationTooltips('init') : $self.foundationTooltips('init'); }, destroy : function () { return this.each(function () { $(window).off('.tooltip'); $(settings.targetClass).off('.tooltip'); $(settings.tooltipClass).each(function (i) { $($(settings.targetClass).get(i)).attr('title', $(this).text()); }).remove(); }); } }; $.fn.foundationTooltips = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.foundationTooltips'); } }; }(jQuery, this));
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationAlerts = function (options) { var settings = $.extend({ callback: $.noop }, options); $(document).on("click", ".alert-box a.close", function (e) { e.preventDefault(); $(this).closest(".alert-box").fadeOut(function () { $(this).remove(); // Do something else after the alert closes settings.callback(); }); }); }; })(jQuery, this);
JavaScript
;jQuery(document).ready(function($) { 'use strict'; var $doc = $(document), Modernizr = window.Modernizr; $.fn.foundationAlerts ? $doc.foundationAlerts() : null; $.fn.foundationButtons ? $doc.foundationButtons() : null; $.fn.foundationAccordion ? $doc.foundationAccordion() : null; $.fn.foundationNavigation ? $doc.foundationNavigation() : null; $.fn.foundationTopBar ? $doc.foundationTopBar() : null; $.fn.foundationCustomForms ? $doc.foundationCustomForms() : null; $.fn.foundationMediaQueryViewer ? $doc.foundationMediaQueryViewer() : null; $.fn.foundationTabs ? $doc.foundationTabs({callback : $.foundation.customForms.appendCustomMarkup}) : null; $.fn.foundationTooltips ? $doc.foundationTooltips() : null; $('input, textarea').placeholder(); // UNCOMMENT THE LINE YOU WANT BELOW IF YOU WANT IE8 SUPPORT AND ARE USING .block-grids $('.block-grid.two-up>li:nth-child(2n+1)').css({clear: 'both'}); $('.block-grid.three-up>li:nth-child(3n+1)').css({clear: 'both'}); $('.block-grid.four-up>li:nth-child(4n+1)').css({clear: 'both'}); $('.block-grid.five-up>li:nth-child(5n+1)').css({clear: 'both'}); // Hide address bar on mobile devices if (Modernizr.touch) { $(window).load(function () { setTimeout(function () { window.scrollTo(0, 1); }, 0); }); } });
JavaScript
/* * jQuery Reveal Plugin 1.1 * www.ZURB.com * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*globals jQuery */ (function ($) { 'use strict'; // // Global variable. // Helps us determine if the current modal is being queued for display. // var modalQueued = false; // // Bind the live 'click' event to all anchor elemnets with the data-reveal-id attribute. // $(document).on('click', 'a[data-reveal-id]', function ( event ) { // // Prevent default action of the event. // event.preventDefault(); // // Get the clicked anchor data-reveal-id attribute value. // var modalLocation = $( this ).attr( 'data-reveal-id' ); // // Find the element with that modalLocation id and call the reveal plugin. // $( '#' + modalLocation ).reveal( $( this ).data() ); }); /** * @module reveal * @property {Object} [options] Reveal options */ $.fn.reveal = function ( options ) { /* * Cache the document object. */ var $doc = $( document ), /* * Default property values. */ defaults = { /** * Possible options: fade, fadeAndPop, none * * @property animation * @type {String} * @default fadeAndPop */ animation: 'fadeAndPop', /** * Speed at which the reveal should show. How fast animtions are. * * @property animationSpeed * @type {Integer} * @default 300 */ animationSpeed: 300, /** * Should the modal close when the background is clicked? * * @property closeOnBackgroundClick * @type {Boolean} * @default true */ closeOnBackgroundClick: true, /** * Specify a class name for the 'close modal' element. * This element will close an open modal. * @example <a href='#close' class='close-reveal-modal'>Close Me</a> * * @property dismissModalClass * @type {String} * @default close-reveal-modal */ dismissModalClass: 'close-reveal-modal', /** * Specify a callback function that triggers 'before' the modal opens. * * @property open * @type {Function} * @default function(){} */ open: $.noop, /** * Specify a callback function that triggers 'after' the modal is opened. * * @property opened * @type {Function} * @default function(){} */ opened: $.noop, /** * Specify a callback function that triggers 'before' the modal prepares to close. * * @property close * @type {Function} * @default function(){} */ close: $.noop, /** * Specify a callback function that triggers 'after' the modal is closed. * * @property closed * @type {Function} * @default function(){} */ closed: $.noop } ; // // Extend the default options. // This replaces the passed in option (options) values with default values. // options = $.extend( {}, defaults, options ); // // Apply the plugin functionality to each element in the jQuery collection. // return this.not('.reveal-modal.open').each( function () { // // Cache the modal element // var modal = $( this ), // // Get the current css 'top' property value in decimal format. // topMeasure = parseInt( modal.css( 'top' ), 10 ), // // Calculate the top offset. // topOffset = modal.height() + topMeasure, // // Helps determine if the modal is locked. // This way we keep the modal from triggering while it's in the middle of animating. // locked = false, // // Get the modal background element. // modalBg = $( '.reveal-modal-bg' ), // // Show modal properties // cssOpts = { // // Used, when we show the modal. // open : { // // Set the 'top' property to the document scroll minus the calculated top offset. // 'top': 0, // // Opacity gets set to 0. // 'opacity': 0, // // Show the modal // 'visibility': 'visible', // // Ensure it's displayed as a block element. // 'display': 'block' }, // // Used, when we hide the modal. // close : { // // Set the default 'top' property value. // 'top': topMeasure, // // Has full opacity. // 'opacity': 1, // // Hide the modal // 'visibility': 'hidden', // // Ensure the elment is hidden. // 'display': 'none' } }, // // Initial closeButton variable. // $closeButton ; // // Do we have a modal background element? // if ( modalBg.length === 0 ) { // // No we don't. So, let's create one. // modalBg = $( '<div />', { 'class' : 'reveal-modal-bg' } ) // // Then insert it after the modal element. // .insertAfter( modal ); // // Now, fade it out a bit. // modalBg.fadeTo( 'fast', 0.8 ); } // // Helper Methods // /** * Unlock the modal for animation. * * @method unlockModal */ function unlockModal() { locked = false; } /** * Lock the modal to prevent further animation. * * @method lockModal */ function lockModal() { locked = true; } /** * Closes all open modals. * * @method closeOpenModal */ function closeOpenModals() { // // Get all reveal-modal elements with the .open class. // var $openModals = $( ".reveal-modal.open" ); // // Do we have modals to close? // if ( $openModals.length === 1 ) { // // Set the modals for animation queuing. // modalQueued = true; // // Trigger the modal close event. // $openModals.trigger( "reveal:close" ); } } /** * Animates the modal opening. * Handles the modal 'open' event. * * @method openAnimation */ function openAnimation() { // // First, determine if we're in the middle of animation. // if ( !locked ) { // // We're not animating, let's lock the modal for animation. // lockModal(); // // Close any opened modals. // closeOpenModals(); // // Now, add the open class to this modal. // modal.addClass( "open" ); // // Are we executing the 'fadeAndPop' animation? // if ( options.animation === "fadeAndPop" ) { // // Yes, we're doing the 'fadeAndPop' animation. // Okay, set the modal css properties. // // // Set the 'top' property to the document scroll minus the calculated top offset. // cssOpts.open.top = $doc.scrollTop() - topOffset; // // Flip the opacity to 0. // cssOpts.open.opacity = 0; // // Set the css options. // modal.css( cssOpts.open ); // // Fade in the background element, at half the speed of the modal element. // So, faster than the modal element. // modalBg.fadeIn( options.animationSpeed / 2 ); // // Let's delay the next animation queue. // We'll wait until the background element is faded in. // modal.delay( options.animationSpeed / 2 ) // // Animate the following css properties. // .animate( { // // Set the 'top' property to the document scroll plus the calculated top measure. // "top": $doc.scrollTop() + topMeasure + 'px', // // Set it to full opacity. // "opacity": 1 }, /* * Fade speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal reveal:opened event. // This should trigger the functions set in the options.opened property. // modal.trigger( 'reveal:opened' ); }); // end of animate. } // end if 'fadeAndPop' // // Are executing the 'fade' animation? // if ( options.animation === "fade" ) { // // Yes, were executing 'fade'. // Okay, let's set the modal properties. // cssOpts.open.top = $doc.scrollTop() + topMeasure; // // Flip the opacity to 0. // cssOpts.open.opacity = 0; // // Set the css options. // modal.css( cssOpts.open ); // // Fade in the modal background at half the speed of the modal. // So, faster than modal. // modalBg.fadeIn( options.animationSpeed / 2 ); // // Delay the modal animation. // Wait till the modal background is done animating. // modal.delay( options.animationSpeed / 2 ) // // Now animate the modal. // .animate( { // // Set to full opacity. // "opacity": 1 }, /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal reveal:opened event. // This should trigger the functions set in the options.opened property. // modal.trigger( 'reveal:opened' ); }); } // end if 'fade' // // Are we not animating? // if ( options.animation === "none" ) { // // We're not animating. // Okay, let's set the modal css properties. // // // Set the top property. // cssOpts.open.top = $doc.scrollTop() + topMeasure; // // Set the opacity property to full opacity, since we're not fading (animating). // cssOpts.open.opacity = 1; // // Set the css property. // modal.css( cssOpts.open ); // // Show the modal Background. // modalBg.css( { "display": "block" } ); // // Trigger the modal opened event. // modal.trigger( 'reveal:opened' ); } // end if animating 'none' }// end if !locked }// end openAnimation function openVideos() { var video = modal.find('.flex-video'), iframe = video.find('iframe'); if (iframe.length > 0) { iframe.attr("src", iframe.data("src")); video.fadeIn(100); } } // // Bind the reveal 'open' event. // When the event is triggered, openAnimation is called // along with any function set in the options.open property. // modal.bind( 'reveal:open.reveal', openAnimation ); modal.bind( 'reveal:open.reveal', openVideos); /** * Closes the modal element(s) * Handles the modal 'close' event. * * @method closeAnimation */ function closeAnimation() { // // First, determine if we're in the middle of animation. // if ( !locked ) { // // We're not animating, let's lock the modal for animation. // lockModal(); // // Clear the modal of the open class. // modal.removeClass( "open" ); // // Are we using the 'fadeAndPop' animation? // if ( options.animation === "fadeAndPop" ) { // // Yes, okay, let's set the animation properties. // modal.animate( { // // Set the top property to the document scrollTop minus calculated topOffset. // "top": $doc.scrollTop() - topOffset + 'px', // // Fade the modal out, by using the opacity property. // "opacity": 0 }, /* * Fade speed. */ options.animationSpeed / 2, /* * End of animation callback. */ function () { // // Set the css hidden options. // modal.css( cssOpts.close ); }); // // Is the modal animation queued? // if ( !modalQueued ) { // // Oh, the modal(s) are mid animating. // Let's delay the animation queue. // modalBg.delay( options.animationSpeed ) // // Fade out the modal background. // .fadeOut( /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed property. // modal.trigger( 'reveal:closed' ); }); } else { // // We're not mid queue. // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); } // end if !modalQueued } // end if animation 'fadeAndPop' // // Are we using the 'fade' animation. // if ( options.animation === "fade" ) { // // Yes, we're using the 'fade' animation. // modal.animate( { "opacity" : 0 }, /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Set the css close options. // modal.css( cssOpts.close ); }); // end animate // // Are we mid animating the modal(s)? // if ( !modalQueued ) { // // Oh, the modal(s) are mid animating. // Let's delay the animation queue. // modalBg.delay( options.animationSpeed ) // // Let's fade out the modal background element. // .fadeOut( /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); }); // end fadeOut } else { // // We're not mid queue. // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); } // end if !modalQueued } // end if animation 'fade' // // Are we not animating? // if ( options.animation === "none" ) { // // We're not animating. // Set the modal close css options. // modal.css( cssOpts.close ); // // Is the modal in the middle of an animation queue? // if ( !modalQueued ) { // // It's not mid queueu. Just hide it. // modalBg.css( { 'display': 'none' } ); } // // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); } // end if not animating // // Reset the modalQueued variable. // modalQueued = false; } // end if !locked } // end closeAnimation /** * Destroys the modal and it's events. * * @method destroy */ function destroy() { // // Unbind all .reveal events from the modal. // modal.unbind( '.reveal' ); // // Unbind all .reveal events from the modal background. // modalBg.unbind( '.reveal' ); // // Unbind all .reveal events from the modal 'close' button. // $closeButton.unbind( '.reveal' ); // // Unbind all .reveal events from the body. // $( 'body' ).unbind( '.reveal' ); } function closeVideos() { var video = modal.find('.flex-video'), iframe = video.find('iframe'); if (iframe.length > 0) { iframe.data("src", iframe.attr("src")); iframe.attr("src", ""); video.fadeOut(100); } } // // Bind the modal 'close' event // modal.bind( 'reveal:close.reveal', closeAnimation ); modal.bind( 'reveal:closed.reveal', closeVideos ); // // Bind the modal 'opened' + 'closed' event // Calls the unlockModal method. // modal.bind( 'reveal:opened.reveal reveal:closed.reveal', unlockModal ); // // Bind the modal 'closed' event. // Calls the destroy method. // modal.bind( 'reveal:closed.reveal', destroy ); // // Bind the modal 'open' event // Handled by the options.open property function. // modal.bind( 'reveal:open.reveal', options.open ); // // Bind the modal 'opened' event. // Handled by the options.opened property function. // modal.bind( 'reveal:opened.reveal', options.opened ); // // Bind the modal 'close' event. // Handled by the options.close property function. // modal.bind( 'reveal:close.reveal', options.close ); // // Bind the modal 'closed' event. // Handled by the options.closed property function. // modal.bind( 'reveal:closed.reveal', options.closed ); // // We're running this for the first time. // Trigger the modal 'open' event. // modal.trigger( 'reveal:open' ); // // Get the closeButton variable element(s). // $closeButton = $( '.' + options.dismissModalClass ) // // Bind the element 'click' event and handler. // .bind( 'click.reveal', function () { // // Trigger the modal 'close' event. // modal.trigger( 'reveal:close' ); }); // // Should we close the modal background on click? // if ( options.closeOnBackgroundClick ) { // // Yes, close the modal background on 'click' // Set the modal background css 'cursor' propety to pointer. // Adds a pointer symbol when you mouse over the modal background. // modalBg.css( { "cursor": "pointer" } ); // // Bind a 'click' event handler to the modal background. // modalBg.bind( 'click.reveal', function () { // // Trigger the modal 'close' event. // modal.trigger( 'reveal:close' ); }); } // // Bind keyup functions on the body element. // We'll want to close the modal when the 'escape' key is hit. // $( 'body' ).bind( 'keyup.reveal', function ( event ) { // // Did the escape key get triggered? // if ( event.which === 27 ) { // 27 is the keycode for the Escape key // // Escape key was triggered. // Trigger the modal 'close' event. // modal.trigger( 'reveal:close' ); } }); // end $(body) }); // end this.each }; // end $.fn } ( jQuery ) );
JavaScript
;(function (window, document, $) { // Set the negative margin on the top menu for slide-menu pages var $selector1 = $('#topMenu'), events = 'click.fndtn'; if ($selector1.length > 0) $selector1.css("margin-top", $selector1.height() * -1); // Watch for clicks to show the sidebar var $selector2 = $('#sidebarButton'); if ($selector2.length > 0) { $('#sidebarButton').on(events, function (e) { e.preventDefault(); $('body').toggleClass('active'); }); } // Watch for clicks to show the menu for slide-menu pages var $selector3 = $('#menuButton'); if ($selector3.length > 0) { $('#menuButton').on(events, function (e) { e.preventDefault(); $('body').toggleClass('active-menu'); }); } // // Adjust sidebars and sizes when resized // $(window).resize(function() { // // if (!navigator.userAgent.match(/Android/i)) $('body').removeClass('active'); // var $selector4 = $('#topMenu'); // if ($selector4.length > 0) $selector4.css("margin-top", $selector4.height() * -1); // }); // Switch panels for the paneled nav on mobile var $selector5 = $('#switchPanels'); if ($selector5.length > 0) { $('#switchPanels dd').on(events, function (e) { e.preventDefault(); var switchToPanel = $(this).children('a').attr('href'), switchToIndex = $(switchToPanel).index(); $(this).toggleClass('active').siblings().removeClass('active'); $(switchToPanel).parent().css("left", (switchToIndex * (-100) + '%')); }); } $('#nav li a').on(events, function (e) { e.preventDefault(); var href = $(this).attr('href'), $target = $(href); $('html, body').animate({scrollTop : $target.offset().top}, 300); }); }(this, document, jQuery));
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationTabs = function (options) { var settings = $.extend({ callback: $.noop }, options); var activateTab = function ($tab) { var $activeTab = $tab.closest('dl').find('dd.active'), target = $tab.children('a').attr("href"), hasHash = /^#/.test(target), contentLocation = ''; if (hasHash) { contentLocation = target + 'Tab'; // Strip off the current url that IE adds contentLocation = contentLocation.replace(/^.+#/, '#'); //Show Tab Content $(contentLocation).closest('.tabs-content').children('li').removeClass('active').hide(); $(contentLocation).css('display', 'block').addClass('active'); } //Make Tab Active $activeTab.removeClass('active'); $tab.addClass('active'); }; $(document).on('click.fndtn', 'dl.tabs dd a', function (event){ activateTab($(this).parent('dd')); }); if (window.location.hash) { activateTab($('a[href="' + window.location.hash + '"]').parent('dd')); settings.callback(); } }; })(jQuery, this);
JavaScript
/* * jQuery Foundation Top Bar 2.0.1 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; var settings = { index : 0, initialized : false }, methods = { init : function (options) { return this.each(function () { settings = $.extend(settings, options); settings.$w = $(window), settings.$topbar = $('nav.top-bar'); settings.$titlebar = settings.$topbar.children('ul:first'); var breakpoint = $("<div class='top-bar-js-breakpoint'/>").appendTo("body"); settings.breakPoint = breakpoint.width(); breakpoint.remove(); if (!settings.initialized) { methods.assemble(); settings.initialized = true; } if (!settings.height) { methods.largestUL(); } $('.top-bar .toggle-topbar').live('click.fndtn', function (e) { e.preventDefault(); if (methods.breakpoint()) { settings.$topbar.toggleClass('expanded'); settings.$topbar.css('min-height', ''); } }); // Show the Dropdown Levels on Click $('.top-bar .has-dropdown>a').live('click.fndtn', function (e) { e.preventDefault(); if (methods.breakpoint()) { var $this = $(this), $selectedLi = $this.closest('li'), $nextLevelUl = $selectedLi.children('ul'), $section = $this.closest('section'), $nextLevelUlHeight = 0, $largestUl; settings.index += 1; $selectedLi.addClass('moved'); $section.css({'left': -(100 * settings.index) + '%'}); $section.find('>.name').css({'left': 100 * settings.index + '%'}); $this.siblings('ul').height(settings.height + settings.$titlebar.outerHeight(true)); settings.$topbar.css('min-height', settings.height + settings.$titlebar.outerHeight(true) * 2) } }); // Go up a level on Click $('.top-bar .has-dropdown .back').live('click.fndtn', function (e) { e.preventDefault(); var $this = $(this), $movedLi = $this.closest('li.moved'), $section = $this.closest('section'), $previousLevelUl = $movedLi.parent(); settings.index -= 1; $section.css({'left': -(100 * settings.index) + '%'}); $section.find('>.name').css({'left': 100 * settings.index + '%'}); if (settings.index === 0) { settings.$topbar.css('min-height', 0); } setTimeout(function () { $movedLi.removeClass('moved'); }, 300); }); }); }, breakpoint : function () { return settings.$w.width() < settings.breakPoint; }, assemble : function () { var $section = settings.$topbar.children('section'); // Pull element out of the DOM for manipulation $section.detach(); $section.find('.has-dropdown>a').each(function () { var $link = $(this), $dropdown = $link.siblings('.dropdown'), $titleLi = $('<li class="title back js-generated"><h5><a href="#"></a></h5></li>'); // Copy link to subnav $titleLi.find('h5>a').html($link.html()); $dropdown.prepend($titleLi); }); // Put element back in the DOM $section.appendTo(settings.$topbar); }, largestUL : function () { var uls = settings.$topbar.find('section ul ul'), largest = uls.first(), total = 0; uls.each(function () { if ($(this).children('li').length > largest.children('li').length) { largest = $(this); } }); largest.children('li').each(function () { total += $(this).outerHeight(true); }); settings.height = total; } }; $.fn.foundationTopBar = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.foundationTopBar'); } }; }(jQuery, this));
JavaScript
/* * jQuery Orbit Plugin 1.4.0 * www.ZURB.com/playground * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ (function ($) { 'use strict'; $.fn.findFirstImage = function () { return this.first() .find('img') .andSelf().filter('img') .first(); }; var ORBIT = { defaults: { animation: 'horizontal-push', // fade, horizontal-slide, vertical-slide, horizontal-push, vertical-push animationSpeed: 600, // how fast animtions are timer: true, // true or false to have the timer advanceSpeed: 4000, // if timer is enabled, time between transitions pauseOnHover: false, // if you hover pauses the slider startClockOnMouseOut: false, // if clock should start on MouseOut startClockOnMouseOutAfter: 1000, // how long after MouseOut should the timer start again directionalNav: true, // manual advancing directional navs directionalNavRightText: 'Right', // text of right directional element for accessibility directionalNavLeftText: 'Left', // text of left directional element for accessibility captions: true, // do you want captions? captionAnimation: 'fade', // fade, slideOpen, none captionAnimationSpeed: 600, // if so how quickly should they animate in resetTimerOnClick: false, // true resets the timer instead of pausing slideshow progress on manual navigation bullets: false, // true or false to activate the bullet navigation bulletThumbs: false, // thumbnails for the bullets bulletThumbLocation: '', // location from this file where thumbs will be afterSlideChange: $.noop, // empty function afterLoadComplete: $.noop, //callback to execute after everything has been loaded fluid: true, centerBullets: true, // center bullet nav with js, turn this off if you want to position the bullet nav manually singleCycle: false // cycles through orbit slides only once }, activeSlide: 0, numberSlides: 0, orbitWidth: null, orbitHeight: null, locked: null, timerRunning: null, degrees: 0, wrapperHTML: '<div class="orbit-wrapper" />', timerHTML: '<div class="timer"><span class="mask"><span class="rotator"></span></span><span class="pause"></span></div>', captionHTML: '<div class="orbit-caption"></div>', directionalNavHTML: '<div class="slider-nav"><span class="right"></span><span class="left"></span></div>', bulletHTML: '<ul class="orbit-bullets"></ul>', init: function (element, options) { var $imageSlides, imagesLoadedCount = 0, self = this; // Bind functions to correct context this.clickTimer = $.proxy(this.clickTimer, this); this.addBullet = $.proxy(this.addBullet, this); this.resetAndUnlock = $.proxy(this.resetAndUnlock, this); this.stopClock = $.proxy(this.stopClock, this); this.startTimerAfterMouseLeave = $.proxy(this.startTimerAfterMouseLeave, this); this.clearClockMouseLeaveTimer = $.proxy(this.clearClockMouseLeaveTimer, this); this.rotateTimer = $.proxy(this.rotateTimer, this); this.options = $.extend({}, this.defaults, options); if (this.options.timer === 'false') this.options.timer = false; if (this.options.captions === 'false') this.options.captions = false; if (this.options.directionalNav === 'false') this.options.directionalNav = false; this.$element = $(element); this.$wrapper = this.$element.wrap(this.wrapperHTML).parent(); this.$slides = this.$element.children('img, a, div, figure'); this.$element.bind('orbit.next', function () { self.shift('next'); }); this.$element.bind('orbit.prev', function () { self.shift('prev'); }); this.$element.bind('orbit.goto', function (event, index) { self.shift(index); }); this.$element.bind('orbit.start', function (event, index) { self.startClock(); }); this.$element.bind('orbit.stop', function (event, index) { self.stopClock(); }); $imageSlides = this.$slides.filter('img'); if ($imageSlides.length === 0) { this.loaded(); } else { $imageSlides.bind('imageready', function () { imagesLoadedCount += 1; if (imagesLoadedCount === $imageSlides.length) { self.loaded(); } }); } }, loaded: function () { this.$element .addClass('orbit') .css({width: '1px', height: '1px'}); this.$slides.addClass('orbit-slide'); this.setDimentionsFromLargestSlide(); this.updateOptionsIfOnlyOneSlide(); this.setupFirstSlide(); if (this.options.timer) { this.setupTimer(); this.startClock(); } if (this.options.captions) { this.setupCaptions(); } if (this.options.directionalNav) { this.setupDirectionalNav(); } if (this.options.bullets) { this.setupBulletNav(); this.setActiveBullet(); } this.options.afterLoadComplete.call(this); Holder.run(); }, currentSlide: function () { return this.$slides.eq(this.activeSlide); }, setDimentionsFromLargestSlide: function () { //Collect all slides and set slider size of largest image var self = this, $fluidPlaceholder; self.$element.add(self.$wrapper).width(this.$slides.first().outerWidth()); self.$element.add(self.$wrapper).height(this.$slides.first().height()); self.orbitWidth = this.$slides.first().outerWidth(); self.orbitHeight = this.$slides.first().height(); $fluidPlaceholder = this.$slides.first().findFirstImage().clone(); this.$slides.each(function () { var slide = $(this), slideWidth = slide.outerWidth(), slideHeight = slide.height(); if (slideWidth > self.$element.outerWidth()) { self.$element.add(self.$wrapper).width(slideWidth); self.orbitWidth = self.$element.outerWidth(); } if (slideHeight > self.$element.height()) { self.$element.add(self.$wrapper).height(slideHeight); self.orbitHeight = self.$element.height(); $fluidPlaceholder = $(this).findFirstImage().clone(); } self.numberSlides += 1; }); if (this.options.fluid) { if (typeof this.options.fluid === "string") { // $fluidPlaceholder = $("<img>").attr("src", "http://placehold.it/" + this.options.fluid); $fluidPlaceholder = $("<img>").attr("data-src", "holder.js/" + this.options.fluid); //var inner = $("<div/>").css({"display":"inline-block", "width":"2px", "height":"2px"}); //$fluidPlaceholder = $("<div/>").css({"float":"left"}); //$fluidPlaceholder.wrapInner(inner); //$fluidPlaceholder = $("<div/>").css({"height":"1px", "width":"2px"}); //$fluidPlaceholder = $("<div style='display:inline-block;width:2px;height:1px;'></div>"); } self.$element.prepend($fluidPlaceholder); $fluidPlaceholder.addClass('fluid-placeholder'); self.$element.add(self.$wrapper).css({width: 'inherit'}); self.$element.add(self.$wrapper).css({height: 'inherit'}); $(window).bind('resize', function () { self.orbitWidth = self.$element.outerWidth(); self.orbitHeight = self.$element.height(); }); } }, //Animation locking functions lock: function () { this.locked = true; }, unlock: function () { this.locked = false; }, updateOptionsIfOnlyOneSlide: function () { if(this.$slides.length === 1) { this.options.directionalNav = false; this.options.timer = false; this.options.bullets = false; } }, setupFirstSlide: function () { //Set initial front photo z-index and fades it in var self = this; this.$slides.first() .css({"z-index" : 3}) .fadeIn(function() { //brings in all other slides IF css declares a display: none self.$slides.css({"display":"block"}) }); }, startClock: function () { var self = this; if(!this.options.timer) { return false; } if (this.$timer.is(':hidden')) { this.clock = setInterval(function () { self.$element.trigger('orbit.next'); }, this.options.advanceSpeed); } else { this.timerRunning = true; this.$pause.removeClass('active'); this.clock = setInterval(this.rotateTimer, this.options.advanceSpeed / 180, false); } }, rotateTimer: function (reset) { var degreeCSS = "rotate(" + this.degrees + "deg)"; this.degrees += 2; this.$rotator.css({ "-webkit-transform": degreeCSS, "-moz-transform": degreeCSS, "-o-transform": degreeCSS, "-ms-transform": degreeCSS }); if(this.degrees > 180) { this.$rotator.addClass('move'); this.$mask.addClass('move'); } if(this.degrees > 360 || reset) { this.$rotator.removeClass('move'); this.$mask.removeClass('move'); this.degrees = 0; this.$element.trigger('orbit.next'); } }, stopClock: function () { if (!this.options.timer) { return false; } else { this.timerRunning = false; clearInterval(this.clock); this.$pause.addClass('active'); } }, setupTimer: function () { this.$timer = $(this.timerHTML); this.$wrapper.append(this.$timer); this.$rotator = this.$timer.find('.rotator'); this.$mask = this.$timer.find('.mask'); this.$pause = this.$timer.find('.pause'); this.$timer.click(this.clickTimer); if (this.options.startClockOnMouseOut) { this.$wrapper.mouseleave(this.startTimerAfterMouseLeave); this.$wrapper.mouseenter(this.clearClockMouseLeaveTimer); } if (this.options.pauseOnHover) { this.$wrapper.mouseenter(this.stopClock); } }, startTimerAfterMouseLeave: function () { var self = this; this.outTimer = setTimeout(function() { if(!self.timerRunning){ self.startClock(); } }, this.options.startClockOnMouseOutAfter) }, clearClockMouseLeaveTimer: function () { clearTimeout(this.outTimer); }, clickTimer: function () { if(!this.timerRunning) { this.startClock(); } else { this.stopClock(); } }, setupCaptions: function () { this.$caption = $(this.captionHTML); this.$wrapper.append(this.$caption); this.setCaption(); }, setCaption: function () { var captionLocation = this.currentSlide().attr('data-caption'), captionHTML; if (!this.options.captions) { return false; } //Set HTML for the caption if it exists if (captionLocation) { //if caption text is blank, don't show captions if ($.trim($(captionLocation).text()).length < 1){ return false; } captionHTML = $(captionLocation).html(); //get HTML from the matching HTML entity this.$caption .attr('id', captionLocation) // Add ID caption TODO why is the id being set? .html(captionHTML); // Change HTML in Caption //Animations for Caption entrances switch (this.options.captionAnimation) { case 'none': this.$caption.show(); break; case 'fade': this.$caption.fadeIn(this.options.captionAnimationSpeed); break; case 'slideOpen': this.$caption.slideDown(this.options.captionAnimationSpeed); break; } } else { //Animations for Caption exits switch (this.options.captionAnimation) { case 'none': this.$caption.hide(); break; case 'fade': this.$caption.fadeOut(this.options.captionAnimationSpeed); break; case 'slideOpen': this.$caption.slideUp(this.options.captionAnimationSpeed); break; } } }, setupDirectionalNav: function () { var self = this, $directionalNav = $(this.directionalNavHTML); $directionalNav.find('.right').html(this.options.directionalNavRightText); $directionalNav.find('.left').html(this.options.directionalNavLeftText); this.$wrapper.append($directionalNav); this.$wrapper.find('.left').click(function () { self.stopClock(); if (self.options.resetTimerOnClick) { self.rotateTimer(true); self.startClock(); } self.$element.trigger('orbit.prev'); }); this.$wrapper.find('.right').click(function () { self.stopClock(); if (self.options.resetTimerOnClick) { self.rotateTimer(true); self.startClock(); } self.$element.trigger('orbit.next'); }); }, setupBulletNav: function () { this.$bullets = $(this.bulletHTML); this.$wrapper.append(this.$bullets); this.$slides.each(this.addBullet); this.$element.addClass('with-bullets'); if (this.options.centerBullets) this.$bullets.css('margin-left', -this.$bullets.outerWidth() / 2); }, addBullet: function (index, slide) { var position = index + 1, $li = $('<li>' + (position) + '</li>'), thumbName, self = this; if (this.options.bulletThumbs) { thumbName = $(slide).attr('data-thumb'); if (thumbName) { $li .addClass('has-thumb') .css({background: "url(" + this.options.bulletThumbLocation + thumbName + ") no-repeat"});; } } this.$bullets.append($li); $li.data('index', index); $li.click(function () { self.stopClock(); if (self.options.resetTimerOnClick) { self.rotateTimer(true); self.startClock(); } self.$element.trigger('orbit.goto', [$li.data('index')]) }); }, setActiveBullet: function () { if(!this.options.bullets) { return false; } else { this.$bullets.find('li') .removeClass('active') .eq(this.activeSlide) .addClass('active'); } }, resetAndUnlock: function () { this.$slides .eq(this.prevActiveSlide) .css({"z-index" : 1}); this.unlock(); this.options.afterSlideChange.call(this, this.$slides.eq(this.prevActiveSlide), this.$slides.eq(this.activeSlide)); }, shift: function (direction) { var slideDirection = direction; //remember previous activeSlide this.prevActiveSlide = this.activeSlide; //exit function if bullet clicked is same as the current image if (this.prevActiveSlide == slideDirection) { return false; } if (this.$slides.length == "1") { return false; } if (!this.locked) { this.lock(); //deduce the proper activeImage if (direction == "next") { this.activeSlide++; if (this.activeSlide == this.numberSlides) { this.activeSlide = 0; } } else if (direction == "prev") { this.activeSlide-- if (this.activeSlide < 0) { this.activeSlide = this.numberSlides - 1; } } else { this.activeSlide = direction; if (this.prevActiveSlide < this.activeSlide) { slideDirection = "next"; } else if (this.prevActiveSlide > this.activeSlide) { slideDirection = "prev" } } //set to correct bullet this.setActiveBullet(); //set previous slide z-index to one below what new activeSlide will be this.$slides .eq(this.prevActiveSlide) .css({"z-index" : 2}); //fade if (this.options.animation == "fade") { this.$slides .eq(this.activeSlide) .css({"opacity" : 0, "z-index" : 3}) .animate({"opacity" : 1}, this.options.animationSpeed, this.resetAndUnlock); } //horizontal-slide if (this.options.animation == "horizontal-slide") { if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({"left": this.orbitWidth, "z-index" : 3}) .animate({"left" : 0}, this.options.animationSpeed, this.resetAndUnlock); } if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({"left": -this.orbitWidth, "z-index" : 3}) .animate({"left" : 0}, this.options.animationSpeed, this.resetAndUnlock); } } //vertical-slide if (this.options.animation == "vertical-slide") { if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({"top": this.orbitHeight, "z-index" : 3}) .animate({"top" : 0}, this.options.animationSpeed, this.resetAndUnlock); } if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({"top": -this.orbitHeight, "z-index" : 3}) .animate({"top" : 0}, this.options.animationSpeed, this.resetAndUnlock); } } //horizontal-push if (this.options.animation == "horizontal-push") { if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({"left": this.orbitWidth, "z-index" : 3}) .animate({"left" : 0}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({"left" : -this.orbitWidth}, this.options.animationSpeed); } if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({"left": -this.orbitWidth, "z-index" : 3}) .animate({"left" : 0}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({"left" : this.orbitWidth}, this.options.animationSpeed); } } //vertical-push if (this.options.animation == "vertical-push") { if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({top: -this.orbitHeight, "z-index" : 3}) .animate({top : 0}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({top : this.orbitHeight}, this.options.animationSpeed); } if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({top: this.orbitHeight, "z-index" : 3}) .animate({top : 0}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({top : -this.orbitHeight}, this.options.animationSpeed); } } this.setCaption(); } if (this.$slides.last() && this.options.singleCycle) { this.stopClock(); } } }; $.fn.orbit = function (options) { return this.each(function () { var orbit = $.extend({}, ORBIT); orbit.init(this, options); }); }; })(jQuery); /*! * jQuery imageready Plugin * http://www.zurb.com/playground/ * * Copyright 2011, ZURB * Released under the MIT License */ (function ($) { var options = {}; $.event.special.imageready = { setup: function (data, namespaces, eventHandle) { options = data || options; }, add: function (handleObj) { var $this = $(this), src; if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) { if (options.forceLoad) { src = $this.attr('src'); $this.attr('src', ''); bindToLoad(this, handleObj.handler); $this.attr('src', src); } else if ( this.complete || this.readyState === 4 ) { handleObj.handler.apply(this, arguments); } else { bindToLoad(this, handleObj.handler); } } }, teardown: function (namespaces) { $(this).unbind('.imageready'); } }; function bindToLoad(element, callback) { var $this = $(element); $this.bind('load.imageready', function () { callback.apply(element, arguments); $this.unbind('load.imageready'); }); } }(jQuery)); /* Holder - 1.3 - client side image placeholders (c) 2012 Ivan Malopinsky / http://imsky.co Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 Commercial use requires attribution. */ var Holder = Holder || {}; (function (app, win) { var preempted = false, fallback = false, canvas = document.createElement('canvas'); //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}}; //https://gist.github.com/991057 by Jed Schmidt with modifications function selector(a){ a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]); var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret; } //shallow object property extend function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c} function draw(ctx, dimensions, template) { var dimension_arr = [dimensions.height, dimensions.width].sort(); var maxFactor = Math.round(dimension_arr[1] / 16), minFactor = Math.round(dimension_arr[0] / 16); var text_height = Math.max(template.size, maxFactor); canvas.width = dimensions.width; canvas.height = dimensions.height; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = template.background; ctx.fillRect(0, 0, dimensions.width, dimensions.height); ctx.fillStyle = template.foreground; ctx.font = "bold " + text_height + "px sans-serif"; var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height); if (Math.round(ctx.measureText(text).width) / dimensions.width > 1) { text_height = Math.max(minFactor, template.size); } ctx.font = "bold " + text_height + "px sans-serif"; ctx.fillText(text, (dimensions.width / 2), (dimensions.height / 2), dimensions.width); return canvas.toDataURL("image/png"); } if (!canvas.getContext) { fallback = true; } else { if (canvas.toDataURL("image/png").indexOf("data:image/png") < 0) { //Android doesn't support data URI fallback = true; } else { var ctx = canvas.getContext("2d"); } } var settings = { domain: "holder.js", images: "img", themes: { "gray": { background: "#eee", foreground: "#aaa", size: 12 }, "social": { background: "#3a5a97", foreground: "#fff", size: 12 }, "industrial": { background: "#434A52", foreground: "#C2F200", size: 12 } } }; app.flags = { dimensions: { regex: /([0-9]+)x([0-9]+)/, output: function(val){ var exec = this.regex.exec(val); return { width: +exec[1], height: +exec[2] } } }, colors: { regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i, output: function(val){ var exec = this.regex.exec(val); return { size: settings.themes.gray.size, foreground: "#" + exec[2], background: "#" + exec[1] } } }, text: { regex: /text\:(.*)/, output: function(val){ return this.regex.exec(val)[1]; } } } for(var flag in app.flags){ app.flags[flag].match = function (val){ return val.match(this.regex) } } app.add_theme = function (name, theme) { name != null && theme != null && (settings.themes[name] = theme); return app; }; app.add_image = function (src, el) { var node = selector(el); if (node.length) { for (var i = 0, l = node.length; i < l; i++) { var img = document.createElement("img") img.setAttribute("data-src", src); node[i].appendChild(img); } } return app; }; app.run = function (o) { var options = extend(settings, o), images = selector(options.images), preempted = true; for (var l = images.length, i = 0; i < l; i++) { var theme = settings.themes.gray; var src = images[i].getAttribute("data-src") || images[i].getAttribute("src"); if ( !! ~src.indexOf(options.domain)) { var render = false, dimensions = null, text = null; var flags = src.substr(src.indexOf(options.domain) + options.domain.length + 1).split("/"); for (sl = flags.length, j = 0; j < sl; j++) { if (app.flags.dimensions.match(flags[j])) { render = true; dimensions = app.flags.dimensions.output(flags[j]); } else if (app.flags.colors.match(flags[j])) { theme = app.flags.colors.output(flags[j]); } else if (options.themes[flags[j]]) { //If a theme is specified, it will override custom colors theme = options.themes[flags[j]]; } else if (app.flags.text.match(flags[j])) { text = app.flags.text.output(flags[j]); } } if (render) { images[i].setAttribute("data-src", src); var dimensions_caption = dimensions.width + "x" + dimensions.height; images[i].setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); // Fallback // images[i].style.width = dimensions.width + "px"; // images[i].style.height = dimensions.height + "px"; images[i].style.backgroundColor = theme.background; var theme = (text ? extend(theme, { text: text }) : theme); if (!fallback) { images[i].setAttribute("src", draw(ctx, dimensions, theme)); } } } } return app; }; contentLoaded(win, function () { preempted || app.run() }) })(Holder, window);
JavaScript
/*! http://mths.be/placeholder v2.0.7 by @mathias */ ;(function(window, document, $) { var isInputSupported = 'placeholder' in document.createElement('input'), isTextareaSupported = 'placeholder' in document.createElement('textarea'), prototype = $.fn, valHooks = $.valHooks, hooks, placeholder; if (isInputSupported && isTextareaSupported) { placeholder = prototype.placeholder = function() { return this; }; placeholder.input = placeholder.textarea = true; } else { placeholder = prototype.placeholder = function() { var $this = this; $this .filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]') .not('.placeholder') .bind({ 'focus.placeholder': clearPlaceholder, 'blur.placeholder': setPlaceholder }) .data('placeholder-enabled', true) .trigger('blur.placeholder'); return $this; }; placeholder.input = isInputSupported; placeholder.textarea = isTextareaSupported; hooks = { 'get': function(element) { var $element = $(element); return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value; }, 'set': function(element, value) { var $element = $(element); if (!$element.data('placeholder-enabled')) { return element.value = value; } if (value == '') { element.value = value; // Issue #56: Setting the placeholder causes problems if the element continues to have focus. if (element != document.activeElement) { // We can't use `triggerHandler` here because of dummy text/password inputs :( setPlaceholder.call(element); } } else if ($element.hasClass('placeholder')) { clearPlaceholder.call(element, true, value) || (element.value = value); } else { element.value = value; } // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363 return $element; } }; isInputSupported || (valHooks.input = hooks); isTextareaSupported || (valHooks.textarea = hooks); $(function() { // Look for forms $(document).delegate('form', 'submit.placeholder', function() { // Clear the placeholder values so they don't get submitted var $inputs = $('.placeholder', this).each(clearPlaceholder); setTimeout(function() { $inputs.each(setPlaceholder); }, 10); }); }); // Clear placeholder values upon page reload $(window).bind('beforeunload.placeholder', function() { $('.placeholder').each(function() { this.value = ''; }); }); } function args(elem) { // Return an object of element attributes var newAttrs = {}, rinlinejQuery = /^jQuery\d+$/; $.each(elem.attributes, function(i, attr) { if (attr.specified && !rinlinejQuery.test(attr.name)) { newAttrs[attr.name] = attr.value; } }); return newAttrs; } function clearPlaceholder(event, value) { var input = this, $input = $(input); if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) { if ($input.data('placeholder-password')) { $input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id')); // If `clearPlaceholder` was called from `$.valHooks.input.set` if (event === true) { return $input[0].value = value; } $input.focus(); } else { input.value = ''; $input.removeClass('placeholder'); input == document.activeElement && input.select(); } } } function setPlaceholder() { var $replacement, input = this, $input = $(input), $origInput = $input, id = this.id; if (input.value == '') { if (input.type == 'password') { if (!$input.data('placeholder-textinput')) { try { $replacement = $input.clone().attr({ 'type': 'text' }); } catch(e) { $replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' })); } $replacement .removeAttr('name') .data({ 'placeholder-password': true, 'placeholder-id': id }) .bind('focus.placeholder', clearPlaceholder); $input .data({ 'placeholder-textinput': $replacement, 'placeholder-id': id }) .before($replacement); } $input = $input.removeAttr('id').hide().prev().attr('id', id).show(); // Note: `$input[0] != input` now! } $input.addClass('placeholder'); $input[0].value = $input.attr('placeholder'); } else { $input.removeClass('placeholder'); } } }(this, document, jQuery));
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationMediaQueryViewer = function (options) { var settings = $.extend(options,{toggleKey:77}), // Press 'M' $doc = $(document); $doc.on("keyup.mediaQueryViewer", ":input", function (e){ if (e.which === settings.toggleKey) { e.stopPropagation(); } }); $doc.on("keyup.mediaQueryViewer", function (e) { var $mqViewer = $('#fqv'); if (e.which === settings.toggleKey) { if ($mqViewer.length > 0) { $mqViewer.remove(); } else { $('body').prepend('<div id="fqv" style="position:fixed;top:4px;left:4px;z-index:999;color:#fff;"><p style="font-size:12px;background:rgba(0,0,0,0.75);padding:5px;margin-bottom:1px;line-height:1.2;"><span class="left">Media:</span> <span style="font-weight:bold;" class="show-for-xlarge">Extra Large</span><span style="font-weight:bold;" class="show-for-large">Large</span><span style="font-weight:bold;" class="show-for-medium">Medium</span><span style="font-weight:bold;" class="show-for-small">Small</span><span style="font-weight:bold;" class="show-for-landscape">Landscape</span><span style="font-weight:bold;" class="show-for-portrait">Portrait</span><span style="font-weight:bold;" class="show-for-touch">Touch</span></p></div>'); } } }); }; })(jQuery, this);
JavaScript
/* * jQuery Custom Forms Plugin 1.0 * www.ZURB.com * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ (function( $ ){ /** * Helper object used to quickly adjust all hidden parent element's, display and visibility properties. * This is currently used for the custom drop downs. When the dropdowns are contained within a reveal modal * we cannot accurately determine the list-item elements width property, since the modal's display property is set * to 'none'. * * This object will help us work around that problem. * * NOTE: This could also be plugin. * * @function hiddenFix */ var hiddenFix = function() { return { /** * Sets all hidden parent elements and self to visibile. * * @method adjust * @param {jQuery Object} $child */ // We'll use this to temporarily store style properties. tmp : [], // We'll use this to set hidden parent elements. hidden : null, adjust : function( $child ) { // Internal reference. var _self = this; // Set all hidden parent elements, including this element. _self.hidden = $child.parents().andSelf().filter( ":hidden" ); // Loop through all hidden elements. _self.hidden.each( function() { // Cache the element. var $elem = $( this ); // Store the style attribute. // Undefined if element doesn't have a style attribute. _self.tmp.push( $elem.attr( 'style' ) ); // Set the element's display property to block, // but ensure it's visibility is hidden. $elem.css( { 'visibility' : 'hidden', 'display' : 'block' } ); }); }, // end adjust /** * Resets the elements previous state. * * @method reset */ reset : function() { // Internal reference. var _self = this; // Loop through our hidden element collection. _self.hidden.each( function( i ) { // Cache this element. var $elem = $( this ), _tmp = _self.tmp[ i ]; // Get the stored 'style' value for this element. // If the stored value is undefined. if( _tmp === undefined ) // Remove the style attribute. $elem.removeAttr( 'style' ); else // Otherwise, reset the element style attribute. $elem.attr( 'style', _tmp ); }); // Reset the tmp array. _self.tmp = []; // Reset the hidden elements variable. _self.hidden = null; } // end reset }; // end return }; jQuery.foundation = jQuery.foundation || {}; jQuery.foundation.customForms = jQuery.foundation.customForms || {}; $.foundation.customForms.appendCustomMarkup = function ( options ) { var defaults = { disable_class: "js-disable-custom" }; options = $.extend( defaults, options ); function appendCustomMarkup(idx, sel) { var $this = $(sel).hide(), type = $this.attr('type'), $span = $this.next('span.custom.' + type); if ($span.length === 0) { $span = $('<span class="custom ' + type + '"></span>').insertAfter($this); } $span.toggleClass('checked', $this.is(':checked')); $span.toggleClass('disabled', $this.is(':disabled')); } function appendCustomSelect(idx, sel) { var hiddenFixObj = hiddenFix(); // // jQueryify the <select> element and cache it. // var $this = $( sel ), // // Find the custom drop down element. // $customSelect = $this.next( 'div.custom.dropdown' ), // // Find the custom select element within the custom drop down. // $customList = $customSelect.find( 'ul' ), // // Find the custom a.current element. // $selectCurrent = $customSelect.find( ".current" ), // // Find the custom a.selector element (the drop-down icon). // $selector = $customSelect.find( ".selector" ), // // Get the <options> from the <select> element. // $options = $this.find( 'option' ), // // Filter down the selected options // $selectedOption = $options.filter( ':selected' ), // // Initial max width. // maxWidth = 0, // // We'll use this variable to create the <li> elements for our custom select. // liHtml = '', // // We'll use this to cache the created <li> elements within our custom select. // $listItems ; var $currentSelect = false; // // Should we not create a custom list? // if ( $this.hasClass( 'no-custom' ) ) return; // // Did we not create a custom select element yet? // if ( $customSelect.length === 0 ) { // // Let's create our custom select element! // // // Determine what select size to use. // var customSelectSize = $this.hasClass( 'small' ) ? 'small' : $this.hasClass( 'medium' ) ? 'medium' : $this.hasClass( 'large' ) ? 'large' : $this.hasClass( 'expand' ) ? 'expand' : '' ; // // Build our custom list. // $customSelect = $('<div class="' + ['custom', 'dropdown', customSelectSize ].join( ' ' ) + '"><a href="#" class="selector"></a><ul /></div>"'); // // Grab the selector element // $selector = $customSelect.find( ".selector" ); // // Grab the unordered list element from the custom list. // $customList = $customSelect.find( "ul" ); // // Build our <li> elements. // liHtml = $options.map( function() { return "<li>" + $( this ).html() + "</li>"; } ).get().join( '' ); // // Append our <li> elements to the custom list (<ul>). // $customList.append( liHtml ); // // Insert the the currently selected list item before all other elements. // Then, find the element and assign it to $currentSelect. // $currentSelect = $customSelect.prepend( '<a href="#" class="current">' + $selectedOption.html() + '</a>' ).find( ".current" ); // // Add the custom select element after the <select> element. // $this.after( $customSelect ) // //then hide the <select> element. // .hide(); } else { // // Create our list item <li> elements. // liHtml = $options.map( function() { return "<li>" + $( this ).html() + "</li>"; } ).get().join( '' ); // // Refresh the ul with options from the select in case the supplied markup doesn't match. // Clear what's currently in the <ul> element. // $customList.html( '' ) // // Populate the list item <li> elements. // .append( liHtml ); } // endif $customSelect.length === 0 // // Determine whether or not the custom select element should be disabled. // $customSelect.toggleClass( 'disabled', $this.is( ':disabled' ) ); // // Cache our List item elements. // $listItems = $customList.find( 'li' ); // // Determine which elements to select in our custom list. // $options.each( function ( index ) { if ( this.selected ) { // // Add the selected class to the current li element // $listItems.eq( index ).addClass( 'selected' ); // // Update the current element with the option value. // if ($currentSelect) { $currentSelect.html( $( this ).html() ); } } }); // // Update the custom <ul> list width property. // $customList.css( 'width', 'inherit' ); // // Set the custom select width property. // $customSelect.css( 'width', 'inherit' ); // // If we're not specifying a predetermined form size. // if ( !$customSelect.is( '.small, .medium, .large, .expand' ) ) { // ------------------------------------------------------------------------------------ // This is a work-around for when elements are contained within hidden parents. // For example, when custom-form elements are inside of a hidden reveal modal. // // We need to display the current custom list element as well as hidden parent elements // in order to properly calculate the list item element's width property. // ------------------------------------------------------------------------------------- // // Show the drop down. // This should ensure that the list item's width values are properly calculated. // $customSelect.addClass( 'open' ); // // Quickly, display all parent elements. // This should help us calcualate the width of the list item's within the drop down. // hiddenFixObj.adjust( $customList ); // // Grab the largest list item width. // maxWidth = ( $listItems.outerWidth() > maxWidth ) ? $listItems.outerWidth() : maxWidth; // // Okay, now reset the parent elements. // This will hide them again. // hiddenFixObj.reset(); // // Finally, hide the drop down. // $customSelect.removeClass( 'open' ); // // Set the custom list width. // $customSelect.width( maxWidth + 18); // // Set the custom list element (<ul />) width. // $customList.width( maxWidth + 16 ); } // endif } $('form.custom input:radio[data-customforms!=disabled]').each(appendCustomMarkup); $('form.custom input:checkbox[data-customforms!=disabled]').each(appendCustomMarkup); $('form.custom select[data-customforms!=disabled]').each(appendCustomSelect); }; var refreshCustomSelect = function($select) { var maxWidth = 0, $customSelect = $select.next(); $options = $select.find('option'); $customSelect.find('ul').html(''); $options.each(function () { $li = $('<li>' + $(this).html() + '</li>'); $customSelect.find('ul').append($li); }); // re-populate $options.each(function (index) { if (this.selected) { $customSelect.find('li').eq(index).addClass('selected'); $customSelect.find('.current').html($(this).html()); } }); // fix width $customSelect.removeAttr('style') .find('ul').removeAttr('style'); $customSelect.find('li').each(function () { $customSelect.addClass('open'); if ($(this).outerWidth() > maxWidth) { maxWidth = $(this).outerWidth(); } $customSelect.removeClass('open'); }); $customSelect.css('width', maxWidth + 18 + 'px'); $customSelect.find('ul').css('width', maxWidth + 16 + 'px'); }; var toggleCheckbox = function($element) { var $input = $element.prev(), input = $input[0]; if (false === $input.is(':disabled')) { input.checked = ((input.checked) ? false : true); $element.toggleClass('checked'); $input.trigger('change'); } }; var toggleRadio = function($element) { var $input = $element.prev(), input = $input[0]; if (false === $input.is(':disabled')) { $('input:radio[name="' + $input.attr('name') + '"]').next().not($element).removeClass('checked'); if ($element.hasClass('checked')) { // Do Nothing } else { $element.toggleClass('checked'); } input.checked = $element.hasClass('checked'); $input.trigger('change'); } }; $(document).on('click', 'form.custom span.custom.checkbox', function (event) { event.preventDefault(); event.stopPropagation(); toggleCheckbox($(this)); }); $(document).on('click', 'form.custom span.custom.radio', function (event) { event.preventDefault(); event.stopPropagation(); toggleRadio($(this)); }); $(document).on('change', 'form.custom select[data-customforms!=disabled]', function (event) { refreshCustomSelect($(this)); }); $(document).on('click', 'form.custom label', function (event) { var $associatedElement = $('#' + $(this).attr('for')), $customCheckbox, $customRadio; if ($associatedElement.length !== 0) { if ($associatedElement.attr('type') === 'checkbox') { event.preventDefault(); $customCheckbox = $(this).find('span.custom.checkbox'); toggleCheckbox($customCheckbox); } else if ($associatedElement.attr('type') === 'radio') { event.preventDefault(); $customRadio = $(this).find('span.custom.radio'); toggleRadio($customRadio); } } }); $(document).on('click', 'form.custom div.custom.dropdown a.current, form.custom div.custom.dropdown a.selector', function (event) { var $this = $(this), $dropdown = $this.closest('div.custom.dropdown'), $select = $dropdown.prev(); event.preventDefault(); $('div.dropdown').removeClass('open'); if (false === $select.is(':disabled')) { $dropdown.toggleClass('open'); if ($dropdown.hasClass('open')) { $(document).bind('click.customdropdown', function (event) { $dropdown.removeClass('open'); $(document).unbind('.customdropdown'); }); } else { $(document).unbind('.customdropdown'); } return false; } }); $(document).on('click', 'form.custom div.custom.dropdown li', function (event) { var $this = $(this), $customDropdown = $this.closest('div.custom.dropdown'), $select = $customDropdown.prev(), selectedIndex = 0; event.preventDefault(); event.stopPropagation(); $('div.dropdown').removeClass('open'); $this .closest('ul') .find('li') .removeClass('selected'); $this.addClass('selected'); $customDropdown .removeClass('open') .find('a.current') .html($this.html()); $this.closest('ul').find('li').each(function (index) { if ($this[0] == this) { selectedIndex = index; } }); $select[0].selectedIndex = selectedIndex; $select.trigger('change'); }); $.fn.foundationCustomForms = $.foundation.customForms.appendCustomMarkup; })( jQuery );
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationButtons = function(options) { var $doc = $(document); // Prevent event propagation on disabled buttons $doc.on('click.fndtn', '.button.disabled', function (e) { e.preventDefault(); }); $('.button.dropdown > ul', this).addClass('no-hover'); $doc.on('click.fndtn', '.button.dropdown, .button.dropdown.split span', function (e) { // Stops further propagation of the event up the DOM tree when clicked on the button. // Events fired by its descendants are not being blocked. $('.button.dropdown').children('ul').removeClass('show-dropdown'); if (e.target === this) { e.stopPropagation(); } }); $doc.on('click.fndtn', '.button.dropdown.split span', function (e) { e.preventDefault(); $('.button.dropdown', this).not($(this).parent()).children('ul').removeClass('show-dropdown'); $(this).siblings('ul').toggleClass('show-dropdown'); }); $doc.on('click.fndtn', '.button.dropdown:not(.split)', function (e) { $('.button.dropdown', this).not(this).children('ul').removeClass('show-dropdown'); $(this).children('ul').toggleClass('show-dropdown'); }); $doc.on('click.fndtn', 'body, html', function () { $('.button.dropdown ul').removeClass('show-dropdown'); }); // Positioning the Flyout List var normalButtonHeight = $('.button.dropdown:not(.large):not(.small):not(.tiny)', this).outerHeight() - 1, largeButtonHeight = $('.button.large.dropdown', this).outerHeight() - 1, smallButtonHeight = $('.button.small.dropdown', this).outerHeight() - 1, tinyButtonHeight = $('.button.tiny.dropdown', this).outerHeight() - 1; $('.button.dropdown:not(.large):not(.small):not(.tiny) > ul', this).css('top', normalButtonHeight); $('.button.dropdown.large > ul', this).css('top', largeButtonHeight); $('.button.dropdown.small > ul', this).css('top', smallButtonHeight); $('.button.dropdown.tiny > ul', this).css('top', tinyButtonHeight); $('.button.dropdown.up:not(.large):not(.small):not(.tiny) > ul', this).css('top', 'auto').css('bottom', normalButtonHeight - 2); $('.button.dropdown.up.large > ul', this).css('top', 'auto').css('bottom', largeButtonHeight - 2); $('.button.dropdown.up.small > ul', this).css('top', 'auto').css('bottom', smallButtonHeight - 2); $('.button.dropdown.up.tiny > ul', this).css('top', 'auto').css('bottom', tinyButtonHeight - 2); }; })( jQuery, this );
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationNavigation = function (options) { var lockNavBar = false; // Windows Phone, sadly, does not register touch events :( if (Modernizr.touch || navigator.userAgent.match(/Windows Phone/i)) { $(document).on('click.fndtn touchstart.fndtn', '.nav-bar a.flyout-toggle', function (e) { e.preventDefault(); var flyout = $(this).siblings('.flyout').first(); if (lockNavBar === false) { $('.nav-bar .flyout').not(flyout).slideUp(500); flyout.slideToggle(500, function () { lockNavBar = false; }); } lockNavBar = true; }); $('.nav-bar>li.has-flyout', this).addClass('is-touch'); } else { $('.nav-bar>li.has-flyout', this).hover(function () { $(this).children('.flyout').show(); }, function () { $(this).children('.flyout').hide(); }); } }; })( jQuery, this );
JavaScript
// Toggle text between current and data-toggle-text contents $.fn.extend({ toggleText: function() { var self = $(this); var text = self.text(); var ttext = self.data('toggle-text'); var tclass = self.data('toggle-class'); self.text(ttext).data('toggle-text', text).toggleClass(tclass); } });
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ ahoy.common = {}; /** * Settings */ ahoy.settings = { date_format: "dd/mm/yy" } /** * User Menu */ ahoy.common.user_menu = { init: function() { $('#user_menu .user > li').click(function(){ $(this).children('ul:first').slideToggle().end().closest('#user_menu').toggleClass('expanded'); }); } }; /** * Auto init expander plugin */ jQuery(document).ready(function($) { $('.expander').each(function() { var slice_at = $(this).data('slice-point'); var expand_text = $(this).data('expand-text'); $(this).expander({ slicePoint: slice_at, expandText: expand_text, userCollapseText: '' }); }); }); /** * "Click Outside" plugin */ $.fn.extend({ // Calls the handler function if the user has clicked outside the object (and not on any of the exceptions) clickOutside: function(handler, exceptions) { var $this = this; $("body").bind("click", function(event) { if (exceptions && $.inArray(event.target, exceptions) > -1) { return; } else if ($.contains($this[0], event.target)) { return; } else { handler(event, $this); } }); return this; } });
JavaScript
/** * Loading Panel */ window.site = { message: { remove: function() { $.removebar(); }, custom: function(message, params) { if(!message) return; var params = $.extend({ position: 'top', removebutton: false, color: '#666', message: message, time: 5000, background_color: '#393536' }, params || {}); jQuery(document).ready(function($) { $.bar(params); }); } } }; Phpr.showLoadingIndicator = function() { site.message.custom('Processing...', {background_color: '#f7c809', color: '#000', time: 999999}); }; Phpr.hideLoadingIndicator = function() { site.message.remove(); }; Phpr.response.popupError = function() { site.message.custom(this.html.replace('@AJAX-ERROR@', ''), {background_color: '#c32611', color: '#fff', time: 10000}); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /* // Foundation @require frameworks/foundation/modernizr.foundation.js; @require frameworks/foundation/jquery.placeholder.js; @require frameworks/foundation/jquery.foundation.alerts.js; @require frameworks/foundation/jquery.foundation.accordion.js; @require frameworks/foundation/jquery.foundation.buttons.js; @require frameworks/foundation/jquery.foundation.tooltips.js; @require frameworks/foundation/jquery.foundation.forms.js; @require frameworks/foundation/jquery.foundation.tabs.js; @require frameworks/foundation/jquery.foundation.navigation.js; @require frameworks/foundation/jquery.foundation.reveal.js; @require frameworks/foundation/jquery.foundation.orbit.js; @require frameworks/foundation/jquery.offcanvas.js; @require frameworks/foundation/app.js; // Utility @require frameworks/utility/jquery.utility.toggletext.js; @require frameworks/utility/jquery.waterfall.js; // Vendor @require ../vendor/jbar/jquery-bar.js; @require ../vendor/ui/jquery-ui.js; @require ../vendor/date/date.js; @require ../vendor/fileupload/jquery-fileupload.js; @require ../vendor/fileupload/jquery-iframe-transport.js; @require ../vendor/carousel/js/jquery.jcarousel.js; @require ../vendor/stars/jquery-ui-stars.js; @require ../vendor/expander/jquery.expander.js; // Scripts Ahoy! @require ahoy/jquery.validate.js; @require ahoy/jquery.validate.ext.js; @require ahoy/ahoy.validation.js; @require ahoy/ahoy.form.js; @require ahoy/ahoy.post.js; @require ahoy.js; // App @require phpr.js; @require common.js; @require forms.js; @require pages/pages.js; */
JavaScript
var Ahoy_Page = (function(page, $){ page.constructor = $(function() { $('#featured_providers').orbit({ animation: 'horizontal-push', bullets: true, captions: true, directionalNav: false, fluid: true }); $('#banners .sub_banner').click(function(){ window.location = $(this).data('link'); }); }); return page; }(Ahoy_Page || {}, jQuery));
JavaScript
ahoy.page_dashboard = { init: function() { var self = ahoy.page_dashboard; $('#p_dash_offers .sub-nav a').live('click', function(){ var type = $(this).data('filter-type'); self.filter_job_offers(type); }); }, filter_job_offers: function(type) { ahoy.post().action('bluebell:on_dashboard_filter_job_offers').data('filter', type).update('#p_dash_offers', 'dash:offers').send(); } };
JavaScript
/* @require ../behaviors/behavior_upload.js; */ // TODO: Deprecate in favour of behavior ahoy.page_request = { active_step: 'create', init: function() { var self = ahoy.page_request; // Initialize self.style_form(); self.validate_form(); self.bind_required_by(); // Alternative time $('#link_request_alt_time').click(self.click_alt_time); // Remote location $('#location_remote').change(function() { self.click_location_remote(this); }); self.click_location_remote('#location_remote'); // Add photos $('#input_add_photos').behavior(ahoy.behaviors.upload_image_multi, {link_id:'#link_add_photos', param_name:'request_images[]'}); }, style_form: function() { // Bold first word $('#page_request section > label.heading').each(function() { $(this).html($(this).text().replace(/(^\w+|\s+\w+)/,'<strong>$1</strong>')); }); }, // Edit request bind_edit_request: function() { var self = ahoy.page_request; $('#edit_request').click(self.click_edit_request); $('#toggle_login, #toggle_register').click(self.click_account_request); }, // Required by logic bind_required_by: function() { var self = ahoy.page_request; var required_by = $('#page_request section.required_by'); var checked = required_by.find('ul.radio_group label input:checked'); self.click_required_by(checked); required_by.find('label input').change(function() { self.click_required_by(this); }); }, click_required_by: function(element) { var label = $(element).parent(); var required_by = $('#page_request section.required_by'); required_by.find('label').removeClass('selected'); required_by.find('.radio_expand').hide(); label.addClass('selected').next('.radio_expand').show(); }, click_alt_time: function() { $(this).toggleText(); $(this).prev().toggleText(); var container = $('#page_request .firm_date_secondary').toggle(); container.find('select').each(function() { $(this).trigger('change'); }); }, click_location_remote: function(obj) { var checked = $(obj).is(':checked'); var location = $('#request_location'); location.attr('disabled', checked); if (checked) { location.val('').removeClass('error valid').next('.float_error').remove(); } }, validate_form: function(extra_rules, extra_messages) { var options = { messages: ahoy.partial_request_simple_form.validate_messages, rules: ahoy.partial_request_simple_form.validate_rules, submitHandler: ahoy.page_request.submit_form }; if (extra_rules) options.rules = $.extend(true, options.rules, extra_rules); if (extra_messages) options.messages = $.extend(true, options.messages, extra_messages); ahoy.validate.init($('#form_request'), options); }, submit_form: function() { var self = ahoy.page_request; switch (self.active_step) { // Create case 'create': self.check_category(function(result){ $('#request_category_id').val(result.id); $('#request_title').val(result.name); self.display_step('review'); }, function() { self.display_step('assist'); }); break; // Assist case 'assist': self.display_step('review'); break; // Review case 'review': var files = []; $('#panel_photos div.image').each(function(){ files.push($(this).attr('data-image-id')); }); ahoy.post('#form_request').action('bluebell:on_request_submit').data('files', files).send(); break; } return false; }, display_step: function(step_name) { var self = ahoy.page_request; self.active_step = step_name; $('#page_request > section, #page_request > form > section').hide(); switch (step_name) { default: case "create": $('#page_request section.create').show(); break; case "assist": $('#page_request section.assist').show(); self.init_assist(); break; case "review": $('#page_request section.review').show(); ahoy.post($('#form_request')) .action('bluebell:on_request_submit') .data('preview', true) .update('#p_review_form', 'request:review_form') .complete(function(){ self.bind_edit_request(); }, true) .send(); // User not logged in, validate the accounting partial if ($('#p_account').length > 0) self.validate_account_form(); break; } $('html, body').animate({scrollTop:0}, 0); }, check_category: function(success, fail) { ahoy.post($('#request_title')) .action('service:on_search_categories').data('name',$('#request_title').val()) .success(function(raw_data, data){ var result = $.parseJSON(data); var found_category = false; $.each(result, function(k,v){ if (v.parent_id) { // Only allow child categories found_category = true; } }); if (found_category) success(result[0]); else fail(); }) .send(); }, click_edit_request: function() { ahoy.page_request.display_step('create'); }, /** * Account logic */ validate_account_form: function(is_login) { if (is_login) { if (ahoy.partial_site_register_form !== undefined) ahoy.validate.set_rules('#form_request', 'partial_site_register_form', true); if (ahoy.partial_site_login_form !== undefined) ahoy.validate.set_rules('#form_request', 'partial_site_login_form'); } else { if (ahoy.partial_site_login_form !== undefined) ahoy.validate.set_rules('#form_request', 'partial_site_login_form', true); if (ahoy.partial_site_register_form !== undefined) ahoy.validate.set_rules('#form_request', 'partial_site_register_form'); } }, click_account_request: function() { var self = ahoy.page_request; var is_register = $('#title_register').is(':visible'); var ajax = ahoy.post($('#form_request')) .action('core:on_null').success(function(){ $('#title_register, #title_login').toggle(); }) .complete(function(){ self.validate_account_form(is_register); }, true); if (is_register) ajax.update('#p_account', 'site:login_form').send(); else ajax.update('#p_account', 'site:register_form').send(); }, /** * Assist logic */ init_assist: function() { var self = ahoy.page_request; // Assist sub nav $('#page_request section.assist .sub-nav a').click(function() { $(this).parent().siblings().removeClass('active').end().addClass('active'); if ($(this).hasClass('category')) { $('#category_form_select_category').show(); $('#category_form_select_alpha').hide(); } else { $('#category_form_select_category').hide(); $('#category_form_select_alpha').show(); } return false; }); self.populate_categories(); self.validate_assist_form(); // Assist selection $('#select_parent').change(function(){ var parent_id = $(this).val(); $('#select_category').empty(); $('#select_alpha option').each(function() { if ($(this).attr('data-parent-id') == parent_id) $('#select_category').append($(this).clone()); }); }); $('#select_category, #select_alpha').change(function(){ $('#request_category_id').val($(this).val()); $('#request_title').val($(this).children('option:selected').text()); }); }, populate_categories: function() { $('#select_parent, #select_category, #select_alpha').empty(); ahoy.post($('#select_parent')).action('service:on_search_categories').success(function(raw_data, data){ var result = $.parseJSON(data); $.each(result, function(k,v){ if (v.parent_id) $('<option />').val(v.id).text(v.name).attr('data-parent-id',v.parent_id).appendTo($('#select_alpha')); else $('<option />').val(v.id).text(v.name).appendTo($('#select_parent')); }); }).send(); }, validate_assist_form: function() { ahoy.validate.init($('#form_assist'), { rules: { select_category: { required: true }, select_alpha: { required: true } }, submitHandler: ahoy.page_request.submit_form }); } };
JavaScript
/* @require ../frameworks/utility/jquery.gmap3.js; @require ../frameworks/utility/jquery.utility.gmap.js; */ ahoy.page_job_booking = { map: null, address: null, init: function() { var self = ahoy.page_job_booking; // Low priority load $(window).load(self.bind_address_map); // Init others self.bind_question_answers(); self.bind_booking_time(); self.bind_job_cancel(); self.bind_rating_form(); }, bind_question_answers: function() { $('#job_questions span.answer').hide(); $('#job_questions a.question').bind('click', function() { $('#job_questions span.answer').hide(); $(this).next().show(); }) }, bind_address_map: function() { var self = ahoy.page_job_booking; self.map = $('#map_booking_address'); var address = $('#booking_address'); var address_string = address.text(); if (address.length==0 || self.map.length==0) return; self.map.gmap({ start_address: address_string, show_zoom_ui: true, allow_drag: false, allow_scrollwheel: false, alow_dbl_click_zoom: false }).gmap('get_object_from_address_string', address_string, function(address){ self.address = address; self.map .gmap('align_to_address_object', address) .gmap('set_zoom', 9) .gmap('add_marker_from_address_object', address, 'job_tag'); }); // Auto align map to center $(window).bind('resize', function() { self.map.gmap('align_to_address_object', self.address) }); }, // Suggest booking time bind_booking_time: function() { var self = ahoy.page_job_booking; var booking_time_link = $('#link_booking_time_suggest'); var booking_time_form = $('#form_booking_time'); var booking_time_container = $('#booking_time_suggest_container'); booking_time_link.click(function() { booking_time_container.show(); $('#booking_time_time').trigger('change'); }); // Validate ahoy.validate.bind(booking_time_form, 'partial_job_booking_time', function() { return ahoy.post(booking_time_form) .action('bluebell:on_request_booking_time') .update('#p_job_booking_time', 'job:booking_time') .success(function() { self.bind_booking_time(); $.foundation.customForms.appendCustomMarkup(); }) .send(); }); }, // Cancel job bind_job_cancel: function() { ahoy.behavior('#popup_job_cancel', 'popup', { trigger: '#link_job_cancel' }); $('#button_job_cancel').click(function() { var request_id = $(this).data('request-id'); ahoy.post().action('bluebell:on_cancel_booking').data('request_id', request_id).send(); }); }, // Leave a rating bind_rating_form: function() { ahoy.validate.bind($('#form_rating'), 'partial_job_rating_form', function() { ahoy.post('#form_rating').action('service:on_rating_submit').update('#p_job_rating_form', 'job:rating_form').send(); }); } };
JavaScript
/* @require ../behaviors/behavior_upload.js; @require ../behaviors/behavior_portfolio.js; @require ../behaviors/behavior_request_quotes.js; */ ahoy.page_request_manage = { init: function() { var self = ahoy.page_request_manage; // Quotes $('#p_quotes').behavior(ahoy.behaviors.request_quotes); // Init others self.bind_add_description(); self.bind_question_submenu(); self.bind_request_cancel(); self.bind_extend_time(); }, // Add photos bind_add_photos: function() { $('#input_add_photos').behavior(ahoy.behaviors.upload_image_multi, { link_id:'#link_add_photos', param_name:'request_images[]', on_remove: function(obj, file_id) { ahoy.post('#input_add_photos').action('service:on_request_remove_file').data('file_id', file_id).send(); } }); }, // Description // bind_add_description: function() { $('#link_add_description, #link_add_description_cancel').live('click', function(){ $('#panel_add_description').toggle(); $('#link_add_description').toggleText(); }); }, validate_add_description: function(rules, messages) { ahoy.validate.init($('#form_add_description'), { rules: rules, messages: messages, submitHandler: function() { ahoy.post('#form_add_description').action('service:on_request_describe').update('#p_details', 'request:manage_details').send(); } }); }, // Questions // bind_question_submenu: function() { var container = $('#p_questions'); container.find('.answer_form.flagged').hide(); container.find('.sub-nav a').click(function() { var type = $(this).data('filter-type'); container.find('dd').removeClass('active'); $(this).parent().addClass('active'); if (type=="all") container.find('.answer_form').show().end().find('.answer_form.flagged').hide(); else if (type=="unanswered") container.find('.answer_form').hide().end().find('.answer_form.unanswered').show(); else if (type=="flagged") container.find('.answer_form').hide().end().find('.answer_form.flagged').show(); }); }, question_edit_toggle: function(question_id) { var form = $('#form_answer_question_'+question_id); form.find('.view').toggle(); form.find('.edit').toggle(); }, question_flag: function(question_id, remove_flag) { var self = ahoy.page_request_manage; var form = $('#form_answer_question_'+question_id); var ajax = ahoy.post(form).action('service:on_question_flag'); if (remove_flag) ajax.data('remove_flag', true); ajax.update('#p_request_answer_form_'+question_id, 'request:answer_form') .complete(function() { self.question_validate_form(question_id); $('#form_answer_question_'+question_id).parent().hide(); },true); return ajax.send(); }, question_validate_form: function(question_id, status) { var self = ahoy.page_request_manage; var action = (status=="answered") ? 'service:on_answer_update' : 'service:on_answer_submit'; var form = $('#form_answer_question_'+question_id); ahoy.validate.bind(form, 'partial_request_answer_form', function() { return ahoy.post(form) .action(action) .update('#p_request_answer_form_'+question_id, 'request:answer_form') .complete(function() { self.question_validate_form(question_id); },true) .send(); }); }, // Cancel request bind_request_cancel: function() { ahoy.behavior('#popup_request_cancel', 'popup', { trigger: '#link_request_cancel' }); $('#button_request_cancel').click(function() { var request_id = $(this).data('request-id'); ahoy.post().action('service:on_request_cancel').data('request_id', request_id).data('redirect', root_url('dashboard')).send(); }); }, // Extend request time bind_extend_time: function() { var self = ahoy.page_request_manage; $('#link_extend_time').click(function() { var request_id = $(this).data('request-id'); ahoy.post().action('service:on_request_extend_time') .data('request_id', request_id) .update('#p_status_panel', 'request:status_panel') .success(self.bind_extend_time) .send(); }); } };
JavaScript
/* @require ../frameworks/utility/jquery.gmap3.js; @require ../frameworks/utility/jquery.utility.gmap.js; @require ../behaviors/behavior_upload.js; @require ../behaviors/behavior_portfolio.js; @require ../behaviors/behavior_field_editor.js; @require ../behaviors/behavior_provide_hours.js; @require ../behaviors/behavior_provide_radius.js; */ ahoy.page_provide_manage = { init: function() { var self = ahoy.page_provide_manage; // Success popup ahoy.behavior('#popup_profile_success', 'popup', { trigger: '#button_done' }); // Image uploads $('#input_provide_photo').behavior(ahoy.behaviors.upload_image, { link_id: '#link_provide_photo', remove_id: '#link_provide_photo_remove', image_id: '#provide_photo', param_name:'provider_photo', on_success: function(obj, data) { $('#link_provide_photo').hide(); }, on_remove: function() { $('#link_provide_photo').fadeIn(1000); ahoy.post($('#input_provide_photo')).action('service:on_provider_update_photo').data('delete', true).send(); } }); $('#input_provide_logo').behavior(ahoy.behaviors.upload_image, { link_id: '#link_provide_logo', remove_id: '#link_provide_logo_remove', image_id: '#provide_logo', param_name:'provider_logo', on_success: function(obj, data) { $('#link_provide_logo').hide(); }, on_remove: function() { $('#link_provide_logo').fadeIn(1000); $('#provide_logo').hide(); ahoy.post($('#input_provide_logo')).action('service:on_provider_update_logo').data('delete', true).send(); return false; } }); // Init others self.bind_profile_fields(); self.bind_profile_description(); self.bind_profile_testimonials(); self.bind_work_radius(); self.bind_work_hours(); self.bind_portfolio(); self.bind_profile_delete(); }, // Profile fields bind_profile_fields: function() { var self = this; // Save event var save_profile_field = function(object, element, value) { // Check form is valid var form = element.closest('form'); if (form.valid()) { // Save profile field ahoy.post(element).action('bluebell:on_provider_update').send(); } }; // Editing $('#p_profile_form') .behavior(ahoy.behaviors.field_editor, { on_set_field: save_profile_field }) .behavior('apply_validation', [$('#form_provide_details'), 'partial_provide_profile_details']); // Role auto complete ahoy.behavior('#provide_role_name', 'role_select', { on_select: function(obj, value){ $('#provide_role_name').prev('label').text(value); } }); // Select country, populate state ahoy.behavior('#provide_country_id', 'select_country', { state_element_id:'#provide_state_id', after_update: function(obj) { obj.state_element = $('#provide_country_id').parent().next().children().first(); } }); // Marry provide_radius and field_editor functionality $('#profile_details_address').bind('field_editor.field_set', function(e, value) { $('#work_radius_address').val(value).trigger('change'); }); }, // Profile description bind_profile_description: function() { // Popup ahoy.behavior('#popup_profile_description', 'popup', { trigger: '#button_profile_description' }); // Save $('#form_provide_decription').submit(function() { ahoy.post('#form_provide_decription').action('bluebell:on_provider_manage_description').update('#p_provide_description', 'provide:description').send(); $('#popup_profile_description').behavior('close_popup'); return false; }); }, // Testimonials bind_profile_testimonials: function() { // Popup ahoy.behavior('#popup_profile_testimonials', 'popup', { trigger: '#button_profile_testimonials' }); // Save ahoy.validate.bind($('#form_provide_testimonials'), 'partial_provide_testimonials_form', function() { ahoy.post($('#form_provide_testimonials')).action('service:on_testimonial_ask').success(function(){ $('#form_provide_testimonials').hide(); $('#profile_testimonials_success').show(); }).send(); }); // Delete $('#p_provide_testimonials .button_delete_testimonial').live('click', function() { var testimonial_id = $(this).data('testimonial-id'); var provider_id = $(this).data('provider-id'); var confirm = $(this).data('confirm'); ahoy.post().action('service:on_testimonial_remove') .data('testimonial_id', testimonial_id) .data('provider_id', provider_id) .update('#p_provide_testimonials', 'provide:testimonials') .confirm(confirm) .send(); }); }, // Portfolio bind_portfolio: function() { // Popup ahoy.behavior('#popup_profile_portfolio', 'popup', { size: 'expand', trigger: '.button_profile_portfolio', on_close: function() { ahoy.post('#form_provide_portfolio') .action('service:on_refresh_provider_portfolio') .data('is_manage', true) .update('#p_provide_portfolio', 'provide:portfolio') .prepare(function(){ $('#provider_portfolio').behavior('destroy'); }) .send(); } }); // Uploader $('#input_add_photos').behavior(ahoy.behaviors.upload_image_multi, { link_id:'#link_add_photos', param_name:'provider_portfolio[]', on_remove: function(obj, file_id) { ahoy.post('#input_add_photos').action('service:on_provider_update_portfolio').data('file_id', file_id).data('delete', true).send(); } }); }, // Work radius bind_work_radius: function() { // Map $('#p_work_radius_form').provide_radius({ on_complete: function(obj) { $('#provider_service_codes').val('|' + obj.get_nearby_postcodes().join('|') + '|'); }, radius_max: $('#work_radius_max').val(), radius_unit: $('#work_radius_unit').val() }); // Prepopulate map $('#work_radius_address').val($('#profile_details_address label').text()).trigger('change'); // Popup ahoy.behavior('#popup_work_radius', 'popup', { trigger: '#link_work_area', size:'expand' }); // Save $('#form_work_radius').submit(function() { ahoy.post('#form_work_radius').action('bluebell:on_provider_update').send(); $('#popup_work_radius').behavior('close_popup'); return false; }); }, // Work hours bind_work_hours: function() { // Behavior $('#p_work_hours_form').behavior(ahoy.behaviors.provide_hours, { use_general: false }); // Popup ahoy.behavior('#popup_work_hours', 'popup', { trigger: '#link_work_hours', size:'large' }); // Save $('#form_work_hours').submit(function() { ahoy.post('#form_work_hours').action('bluebell:on_provider_update').send(); $('#popup_work_hours').behavior('close_popup'); return false; }); }, // Profile delete bind_profile_delete: function() { ahoy.behavior('#popup_profile_delete', 'popup', { trigger: '#link_delete_profile' }); $('#button_profile_delete').click(function() { var provider_id = $(this).data('provider-id'); ahoy.post().action('service:on_delete_provider').data('provider_id', provider_id).data('redirect', root_url('provide/profiles')).send(); }); } };
JavaScript
/** * Account */ ahoy.page_account = { init: function() { var self = ahoy.page_account; self.bind_work_history(); self.bind_notifications(); }, toggle_edit: function(element) { jQuery(element).parents('.block:first').find('.view:first').slideToggle().next('.edit').slideToggle(); }, bind_country_select: function(element) { element = jQuery(element); var state_field = element.parents('div.form-field:first').next('div.form-field').find('select:first'); ahoy.behavior(element, 'select_country', { state_element_id:state_field, after_update: function(obj) { obj.state_element = element.parents('div.form-field:first').next('div.form-field').find('select:first'); } }); }, filter_history: function(mode, submode, page) { var post_obj = ahoy.post($('#form_work_history')) .action('bluebell:on_account_filter_history') .update('#work_historyTab', 'account:work_history'); if (mode) post_obj = post_obj.data('mode', mode); if (submode) post_obj = post_obj.data('submode', submode); if (page) post_obj= post_obj.data('page', page); post_obj.send(); }, bind_work_history: function() { var self = ahoy.page_account; $('#mode_filter a').live('click', function() { var mode = $(this).data('mode'); self.filter_history(mode, null, null); }); $('#submode_filter_offers a').live('click', function() { var submode = $(this).data('submode'); self.filter_history(null, submode, null); }); $('#p_site_pagination a').live('click', function() { var page = $(this).data('page'); self.filter_history(null, null, page); }); }, bind_notifications: function() { $('#form_user_notifications').submit(function() { ahoy.post($('#form_user_notifications')).action('user:on_preferences_update').send(); return false; }); } };
JavaScript
/* @require ../behaviors/behavior_field_editor.js; */ ahoy.page_pay = { init: function() { var self = ahoy.page_pay; // Invoice field editing ahoy.behavior('#form_invoice_details', 'field_editor', { implode_char: ' ', on_set_field: function() { } }); // Select country, populate state ahoy.behavior('#invoice_billing_country_id', 'select_country', { state_element_id:'#invoice_billing_state_id', after_update: function(obj) { obj.state_element = $('#invoice_billing_country_id').parent().next().children().first(); } }); } };
JavaScript
/* @require ../behaviors/behavior_job_quote.js; */ ahoy.page_job = { init: function() { var self = ahoy.page_job; $('#link_edit_quote').live('click', self.click_edit_quote); $('#link_delete_quote').live('click', self.click_delete_quote); // Init others self.bind_ask_question(); self.bind_request_ignore(); }, // Quote // init_quote_forms: function () { var self = ahoy.page_job; // Styles $(window).load(function() { $('select').trigger('change'); }); // Tabs $(document).foundationTabs({callback:$.foundation.customForms.appendCustomMarkup}); $(document).on('click.fndtn', 'dl.tabs dd a', function (event){ $('form.custom select').trigger('change'); }); // Forms self.bind_quote_flat_rate(); self.bind_quote_onsite(); }, // Flat rate quote bind_quote_flat_rate: function() { if (!$('#p_quote_flat_rate').length) return; // Quote behavior $('#p_quote_flat_rate').behavior(ahoy.behaviors.job_quote, { type: 'flat_rate' }); // Validate ahoy.validate.bind($('#form_quote_flat_rate'), 'partial_job_quote_flat_rate', function() { return ahoy.post($('#form_quote_flat_rate')).action('bluebell:on_quote_submit').update('#p_quote_panel', 'job:quote_summary').send(); }); ahoy.validate.set_rules('#form_quote_flat_rate', 'partial_job_personal_message'); // Message $('#p_personal_message_flat').behavior(ahoy.behaviors.job_quote, { type: 'message' }); }, // On site quote bind_quote_onsite: function() { if (!$('#p_quote_onsite').length) return; // Quote behavior $('#p_quote_onsite').behavior(ahoy.behaviors.job_quote, { type: 'onsite' }); // Validate ahoy.validate.bind($('#form_quote_onsite'), 'partial_job_quote_onsite', function() { return ahoy.post($('#form_quote_onsite')).action('bluebell:on_quote_submit').update('#p_quote_panel', 'job:quote_summary').send(); }); ahoy.validate.set_rules('#form_quote_onsite', 'partial_job_personal_message'); // Message $('#p_personal_message_onsite').behavior(ahoy.behaviors.job_quote, { type: 'message' }); }, // Quote summary // click_edit_quote: function() { return ahoy.post('#form_quote_summary').action('bluebell:on_quote_submit').update('#p_quote_panel', 'job:quote_submit').send(); }, click_delete_quote: function() { return ahoy.post('#form_quote_summary').action('bluebell:on_quote_submit').data('delete', true).update('#p_quote_panel', 'job:quote_submit').send(); }, // Question // bind_ask_question: function() { var self = ahoy.page_job; // Ask a question $('#link_ask_question').click(function() { $(this).hide(); $('#ask_question').show(); }); // Validate ahoy.validate.bind($('#form_ask_question'), 'partial_job_ask_question', function() { return ahoy.post($('#form_ask_question')) .action('service:on_question_submit') .update('#p_ask_question', 'job:ask_question') .complete(function() { self.bind_ask_question(); },true) .send(); }); // Show answers $('#job_questions span.answer').hide(); $('#job_questions a.question').live('click', function() { $('#job_questions span.answer').hide(); $(this).next().show(); }) }, // Ignore request bind_request_ignore: function() { ahoy.behavior('#popup_request_ignore', 'popup', { trigger: '#link_request_ignore' }); $('#button_request_ignore').click(function() { var request_id = $(this).data('request-id'); ahoy.post().action('service:on_request_ignore').data('request_id', request_id).data('redirect', root_url('dashboard')).send(); }); } };
JavaScript
/* @require ../frameworks/utility/jquery.gmap3.js; @require ../frameworks/utility/jquery.utility.gmap.js; @require ../frameworks/utility/jquery.utility.gmap_locator.js; */ ahoy.page_profile = { init: function() { var self = ahoy.page_profile; // Init others self.bind_request_popup(); self.bind_portfolio(); self.bind_other_providers(); }, bind_request_popup: function() { // Popup ahoy.behavior('#popup_contact_provider', 'popup', { trigger: '#button_contact_provider', size:'xlarge' }); ahoy.behavior('#popup_contact_provider_success', 'popup', { size:'xlarge' }); ahoy.validate.bind($('#form_request'), 'partial_request_quick_form', function() { ahoy.post($('#form_request')) .action('bluebell:on_directory_create_request') .success(function() { $('#popup_contact_provider_success').behavior('open_popup'); }) .send(); }); }, bind_portfolio: function() { $('#portfolio_slider').orbit({ bullets: true, bulletThumbs: true, afterLoadComplete: function() { $('.orbit-bullets').addClass('hide-for-small').appendTo($('#portfolio_thumbs')); } // .parent().after($('#portfolio_slider')); } }); }, bind_other_providers: function() { $('#other_providers > ul').addClass('jcarousel-skin-ahoy').jcarousel({scroll:1}); $('#other_providers li').click(function() { var provider_id = $(this).data('id'); if (provider_id) $('#map_other_providers').gmap_locator('focus_location', provider_id); }); $('#map_other_providers').gmap_locator({ container: '#other_providers ul', bubble_id_prefix: '#location_', allow_scrollwheel: false, bubble_on_hover: false, zoom_ui: true }) } };
JavaScript
ahoy.page_messages = { init: function() { var self = ahoy.page_messages; self.bind_message_link(); self.bind_search_form(); self.bind_delete_link(); }, bind_message_link: function() { $('#page_messages .message_link').live('click', function() { window.location = $(this).data('url'); }); }, bind_search_form: function() { $('#form_message_search').submit(function() { return ahoy.post($('#form_message_search')) .action('user:on_messages_search') .update('#p_message_panel', 'messages:message_panel') .send(); }); }, bind_delete_link: function() { $('#page_messages').on('click', '.link_delete', function() { var message_id = $(this).data('message-id'); ahoy.post() .action('user:on_message_remove') .data('message_id', message_id) .update('#p_message_panel', 'messages:message_panel') .send(); }); } }; ahoy.page_message = { init: function() { // Submit reply ahoy.validate.bind($('#form_message_reply'), 'partial_messages_reply_form', function() { return ahoy.post($('#form_message_reply')) .action('bluebell:on_message_send') .update('#p_messages_thread', 'messages:thread') .update('#p_messages_reply_form', 'messages:reply_form') .send(); }); } };
JavaScript
ahoy.page_directory = { init: function() { var self = ahoy.page_directory; // Dress up breadcrumb $('ul.breadcrumbs li:last').addClass('current'); self.bind_request_popup(); self.bind_search_form(); self.bind_request_form(); }, select_letter: function(letter) { return ahoy.post() .action('bluebell:on_directory') .data('letter', letter) .update('#p_directory', 'directory:letter') .send(); }, bind_search_form: function() { var search_form = $('#form_directory_search'); if (search_form.length == 0) return; ahoy.validate.bind(search_form, 'partial_directory_search_form', function() { return ahoy.post(search_form).action('bluebell:on_directory_search').update('#p_directory', 'directory:city').send(); }); }, bind_request_popup: function() { if ($('#popup_request').length == 0) return; ahoy.behavior('#popup_request', 'popup', { trigger: '#button_request_popup', size:'xlarge' }); ahoy.behavior('#popup_request_success', 'popup', { size:'xlarge'}); ahoy.validate.bind($('#form_request'), 'partial_request_quick_form', function() { ahoy.post($('#form_request')) .action('bluebell:on_directory_create_request') .success(function() { $('#popup_request_success').behavior('open_popup'); }) .send(); }); }, bind_request_form: function() { var self = ahoy.page_directory; var validate_extra_options; if ($('#request_role_name').length > 0) { self.bind_role_name(); // Prevent validation and autocomplete conflict validate_extra_options = { onfocusout:self.check_request_role_name }; } ahoy.validate.bind($('#form_request_panel'), 'partial_request_quick_form', function() { ahoy.post($('#form_request_panel')) .action('bluebell:on_directory_create_request') .update('#p_directory_request_panel', 'directory:request_panel') .send(); }, validate_extra_options); }, ignore_role_name_validation: true, bind_role_name: function() { // Role auto complete ahoy.behavior('#request_role_name', 'role_select', { on_select: function() { // Prevent validation and autocomplete conflict self.ignore_role_name_validation = true; setTimeout(function() { self.ignore_role_name_validation = false; }, 0); } }); }, // Prevent validation and autocomplete conflict check_request_role_name: function(element) { if (!$(element).is('#request_role_name') || !ahoy.page_directory.ignore_role_name_validation) { if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) { this.element(element); } } } };
JavaScript