code
stringlengths
1
2.08M
language
stringclasses
1 value
// Copyright 2006 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. // Known Issues: // // * Patterns only support repeat. // * Radial gradient are not implemented. The VML version of these look very // different from the canvas one. // * Clipping paths are not implemented. // * Coordsize. The width and height attribute have higher priority than the // width and height style values which isn't correct. // * Painting mode isn't implemented. // * Canvas width/height should is using content-box by default. IE in // Quirks mode will draw the canvas using border-box. Either change your // doctype to HTML5 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) // or use Box Sizing Behavior from WebFX // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) // * Non uniform scaling does not correctly scale strokes. // * Filling very large shapes (above 5000 points) is buggy. // * Optimize. There is always room for speed improvements. // Only add this code if we do not already have a canvas implementation if (!document.createElement('canvas').getContext) { (function() { // alias some functions to make (compiled) code shorter var m = Math; var mr = m.round; var ms = m.sin; var mc = m.cos; var abs = m.abs; var sqrt = m.sqrt; // this is used for sub pixel precision var Z = 10; var Z2 = Z / 2; /** * This funtion is assigned to the <canvas> elements as element.getContext(). * @this {HTMLElement} * @return {CanvasRenderingContext2D_} */ function getContext() { return this.context_ || (this.context_ = new CanvasRenderingContext2D_(this)); } var slice = Array.prototype.slice; /** * Binds a function to an object. The returned function will always use the * passed in {@code obj} as {@code this}. * * Example: * * g = bind(f, obj, a, b) * g(c, d) // will do f.call(obj, a, b, c, d) * * @param {Function} f The function to bind the object to * @param {Object} obj The object that should act as this when the function * is called * @param {*} var_args Rest arguments that will be used as the initial * arguments when the function is called * @return {Function} A new function that has bound this */ function bind(f, obj, var_args) { var a = slice.call(arguments, 2); return function() { return f.apply(obj, a.concat(slice.call(arguments))); }; } function encodeHtmlAttribute(s) { return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); } function addNamespacesAndStylesheet(doc) { // create xmlns if (!doc.namespaces['g_vml_']) { doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml', '#default#VML'); } if (!doc.namespaces['g_o_']) { doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office', '#default#VML'); } // Setup default CSS. Only add one style sheet per document if (!doc.styleSheets['ex_canvas_']) { var ss = doc.createStyleSheet(); ss.owningElement.id = 'ex_canvas_'; ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + // default size is 300x150 in Gecko and Opera 'text-align:left;width:300px;height:150px}'; } } // Add namespaces and stylesheet at startup. addNamespacesAndStylesheet(document); var G_vmlCanvasManager_ = { init: function(opt_doc) { if (/MSIE/.test(navigator.userAgent) && !window.opera) { var doc = opt_doc || document; // Create a dummy element so that IE will allow canvas elements to be // recognized. doc.createElement('canvas'); doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); } }, init_: function(doc) { // find all canvas elements var els = doc.getElementsByTagName('canvas'); for (var i = 0; i < els.length; i++) { this.initElement(els[i]); } }, /** * Public initializes a canvas element so that it can be used as canvas * element from now on. This is called automatically before the page is * loaded but if you are creating elements using createElement you need to * make sure this is called on the element. * @param {HTMLElement} el The canvas element to initialize. * @return {HTMLElement} the element that was created. */ initElement: function(el) { if (!el.getContext) { el.getContext = getContext; // Add namespaces and stylesheet to document of the element. addNamespacesAndStylesheet(el.ownerDocument); // Remove fallback content. There is no way to hide text nodes so we // just remove all childNodes. We could hide all elements and remove // text nodes but who really cares about the fallback content. el.innerHTML = ''; // do not use inline function because that will leak memory el.attachEvent('onpropertychange', onPropertyChange); el.attachEvent('onresize', onResize); var attrs = el.attributes; if (attrs.width && attrs.width.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setWidth_(attrs.width.nodeValue); el.style.width = attrs.width.nodeValue + 'px'; } else { el.width = el.clientWidth; } if (attrs.height && attrs.height.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setHeight_(attrs.height.nodeValue); el.style.height = attrs.height.nodeValue + 'px'; } else { el.height = el.clientHeight; } //el.getContext().setCoordsize_() } return el; } }; function onPropertyChange(e) { var el = e.srcElement; switch (e.propertyName) { case 'width': el.getContext().clearRect(); el.style.width = el.attributes.width.nodeValue + 'px'; // In IE8 this does not trigger onresize. el.firstChild.style.width = el.clientWidth + 'px'; break; case 'height': el.getContext().clearRect(); el.style.height = el.attributes.height.nodeValue + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; break; } } function onResize(e) { var el = e.srcElement; if (el.firstChild) { el.firstChild.style.width = el.clientWidth + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; } } G_vmlCanvasManager_.init(); // precompute "00" to "FF" var decToHex = []; for (var i = 0; i < 16; i++) { for (var j = 0; j < 16; j++) { decToHex[i * 16 + j] = i.toString(16) + j.toString(16); } } function createMatrixIdentity() { return [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; } function matrixMultiply(m1, m2) { var result = createMatrixIdentity(); for (var x = 0; x < 3; x++) { for (var y = 0; y < 3; y++) { var sum = 0; for (var z = 0; z < 3; z++) { sum += m1[x][z] * m2[z][y]; } result[x][y] = sum; } } return result; } function copyState(o1, o2) { o2.fillStyle = o1.fillStyle; o2.lineCap = o1.lineCap; o2.lineJoin = o1.lineJoin; o2.lineWidth = o1.lineWidth; o2.miterLimit = o1.miterLimit; o2.shadowBlur = o1.shadowBlur; o2.shadowColor = o1.shadowColor; o2.shadowOffsetX = o1.shadowOffsetX; o2.shadowOffsetY = o1.shadowOffsetY; o2.strokeStyle = o1.strokeStyle; o2.globalAlpha = o1.globalAlpha; o2.font = o1.font; o2.textAlign = o1.textAlign; o2.textBaseline = o1.textBaseline; o2.arcScaleX_ = o1.arcScaleX_; o2.arcScaleY_ = o1.arcScaleY_; o2.lineScale_ = o1.lineScale_; } var colorData = { aliceblue: '#F0F8FF', antiquewhite: '#FAEBD7', aquamarine: '#7FFFD4', azure: '#F0FFFF', beige: '#F5F5DC', bisque: '#FFE4C4', black: '#000000', blanchedalmond: '#FFEBCD', 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', 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', gainsboro: '#DCDCDC', ghostwhite: '#F8F8FF', gold: '#FFD700', goldenrod: '#DAA520', grey: '#808080', 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', lightgreen: '#90EE90', lightgrey: '#D3D3D3', lightpink: '#FFB6C1', lightsalmon: '#FFA07A', lightseagreen: '#20B2AA', lightskyblue: '#87CEFA', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#B0C4DE', lightyellow: '#FFFFE0', limegreen: '#32CD32', linen: '#FAF0E6', magenta: '#FF00FF', 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', oldlace: '#FDF5E6', 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', rosybrown: '#BC8F8F', royalblue: '#4169E1', saddlebrown: '#8B4513', salmon: '#FA8072', sandybrown: '#F4A460', seagreen: '#2E8B57', seashell: '#FFF5EE', sienna: '#A0522D', skyblue: '#87CEEB', slateblue: '#6A5ACD', slategray: '#708090', slategrey: '#708090', snow: '#FFFAFA', springgreen: '#00FF7F', steelblue: '#4682B4', tan: '#D2B48C', thistle: '#D8BFD8', tomato: '#FF6347', turquoise: '#40E0D0', violet: '#EE82EE', wheat: '#F5DEB3', whitesmoke: '#F5F5F5', yellowgreen: '#9ACD32' }; function getRgbHslContent(styleString) { var start = styleString.indexOf('(', 3); var end = styleString.indexOf(')', start + 1); var parts = styleString.substring(start + 1, end).split(','); // add alpha if needed if (parts.length == 4 && styleString.substr(3, 1) == 'a') { alpha = Number(parts[3]); } else { parts[3] = 1; } return parts; } function percent(s) { return parseFloat(s) / 100; } function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); } function hslToRgb(parts){ var r, g, b; h = parseFloat(parts[0]) / 360 % 360; if (h < 0) h++; s = clamp(percent(parts[1]), 0, 1); l = clamp(percent(parts[2]), 0, 1); 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 = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return '#' + decToHex[Math.floor(r * 255)] + decToHex[Math.floor(g * 255)] + decToHex[Math.floor(b * 255)]; } function hueToRgb(m1, m2, h) { if (h < 0) h++; if (h > 1) h--; if (6 * h < 1) return m1 + (m2 - m1) * 6 * h; else if (2 * h < 1) return m2; else if (3 * h < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6; else return m1; } function processStyle(styleString) { var str, alpha = 1; styleString = String(styleString); if (styleString.charAt(0) == '#') { str = styleString; } else if (/^rgb/.test(styleString)) { var parts = getRgbHslContent(styleString); var str = '#', n; for (var i = 0; i < 3; i++) { if (parts[i].indexOf('%') != -1) { n = Math.floor(percent(parts[i]) * 255); } else { n = Number(parts[i]); } str += decToHex[clamp(n, 0, 255)]; } alpha = parts[3]; } else if (/^hsl/.test(styleString)) { var parts = getRgbHslContent(styleString); str = hslToRgb(parts); alpha = parts[3]; } else { str = colorData[styleString] || styleString; } return {color: str, alpha: alpha}; } var DEFAULT_STYLE = { style: 'normal', variant: 'normal', weight: 'normal', size: 10, family: 'sans-serif' }; // Internal text style cache var fontStyleCache = {}; function processFontStyle(styleString) { if (fontStyleCache[styleString]) { return fontStyleCache[styleString]; } var el = document.createElement('div'); var style = el.style; try { style.font = styleString; } catch (ex) { // Ignore failures to set to invalid font. } return fontStyleCache[styleString] = { style: style.fontStyle || DEFAULT_STYLE.style, variant: style.fontVariant || DEFAULT_STYLE.variant, weight: style.fontWeight || DEFAULT_STYLE.weight, size: style.fontSize || DEFAULT_STYLE.size, family: style.fontFamily || DEFAULT_STYLE.family }; } function getComputedStyle(style, element) { var computedStyle = {}; for (var p in style) { computedStyle[p] = style[p]; } // Compute the size var canvasFontSize = parseFloat(element.currentStyle.fontSize), fontSize = parseFloat(style.size); if (typeof style.size == 'number') { computedStyle.size = style.size; } else if (style.size.indexOf('px') != -1) { computedStyle.size = fontSize; } else if (style.size.indexOf('em') != -1) { computedStyle.size = canvasFontSize * fontSize; } else if(style.size.indexOf('%') != -1) { computedStyle.size = (canvasFontSize / 100) * fontSize; } else if (style.size.indexOf('pt') != -1) { computedStyle.size = fontSize / .75; } else { computedStyle.size = canvasFontSize; } // Different scaling between normal text and VML text. This was found using // trial and error to get the same size as non VML text. computedStyle.size *= 0.981; return computedStyle; } function buildStyle(style) { return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + style.size + 'px ' + style.family; } function processLineCap(lineCap) { switch (lineCap) { case 'butt': return 'flat'; case 'round': return 'round'; case 'square': default: return 'square'; } } /** * This class implements CanvasRenderingContext2D interface as described by * the WHATWG. * @param {HTMLElement} surfaceElement The element that the 2D context should * be associated with */ function CanvasRenderingContext2D_(surfaceElement) { this.m_ = createMatrixIdentity(); this.mStack_ = []; this.aStack_ = []; this.currentPath_ = []; // Canvas context properties this.strokeStyle = '#000'; this.fillStyle = '#000'; this.lineWidth = 1; this.lineJoin = 'miter'; this.lineCap = 'butt'; this.miterLimit = Z * 1; this.globalAlpha = 1; this.font = '10px sans-serif'; this.textAlign = 'left'; this.textBaseline = 'alphabetic'; this.canvas = surfaceElement; var el = surfaceElement.ownerDocument.createElement('div'); el.style.width = surfaceElement.clientWidth + 'px'; el.style.height = surfaceElement.clientHeight + 'px'; el.style.overflow = 'hidden'; el.style.position = 'absolute'; surfaceElement.appendChild(el); this.element_ = el; this.arcScaleX_ = 1; this.arcScaleY_ = 1; this.lineScale_ = 1; } var contextPrototype = CanvasRenderingContext2D_.prototype; contextPrototype.clearRect = function() { if (this.textMeasureEl_) { this.textMeasureEl_.removeNode(true); this.textMeasureEl_ = null; } this.element_.innerHTML = ''; }; contextPrototype.beginPath = function() { // TODO: Branch current matrix so that save/restore has no effect // as per safari docs. this.currentPath_ = []; }; contextPrototype.moveTo = function(aX, aY) { var p = this.getCoords_(aX, aY); this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.lineTo = function(aX, aY) { var p = this.getCoords_(aX, aY); this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { var p = this.getCoords_(aX, aY); var cp1 = this.getCoords_(aCP1x, aCP1y); var cp2 = this.getCoords_(aCP2x, aCP2y); bezierCurveTo(this, cp1, cp2, p); }; // Helper function that takes the already fixed cordinates. function bezierCurveTo(self, cp1, cp2, p) { self.currentPath_.push({ type: 'bezierCurveTo', cp1x: cp1.x, cp1y: cp1.y, cp2x: cp2.x, cp2y: cp2.y, x: p.x, y: p.y }); self.currentX_ = p.x; self.currentY_ = p.y; } contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { // the following is lifted almost directly from // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes var cp = this.getCoords_(aCPx, aCPy); var p = this.getCoords_(aX, aY); var cp1 = { x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) }; var cp2 = { x: cp1.x + (p.x - this.currentX_) / 3.0, y: cp1.y + (p.y - this.currentY_) / 3.0 }; bezierCurveTo(this, cp1, cp2, p); }; contextPrototype.arc = function(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { aRadius *= Z; var arcType = aClockwise ? 'at' : 'wa'; var xStart = aX + mc(aStartAngle) * aRadius - Z2; var yStart = aY + ms(aStartAngle) * aRadius - Z2; var xEnd = aX + mc(aEndAngle) * aRadius - Z2; var yEnd = aY + ms(aEndAngle) * aRadius - Z2; // IE won't render arches drawn counter clockwise if xStart == xEnd. if (xStart == xEnd && !aClockwise) { xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something // that can be represented in binary } var p = this.getCoords_(aX, aY); var pStart = this.getCoords_(xStart, yStart); var pEnd = this.getCoords_(xEnd, yEnd); this.currentPath_.push({type: arcType, x: p.x, y: p.y, radius: aRadius, xStart: pStart.x, yStart: pStart.y, xEnd: pEnd.x, yEnd: pEnd.y}); }; contextPrototype.rect = function(aX, aY, aWidth, aHeight) { this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); }; contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.stroke(); this.currentPath_ = oldPath; }; contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.fill(); this.currentPath_ = oldPath; }; contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { var gradient = new CanvasGradient_('gradient'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.x1_ = aX1; gradient.y1_ = aY1; return gradient; }; contextPrototype.createRadialGradient = function(aX0, aY0, aR0, aX1, aY1, aR1) { var gradient = new CanvasGradient_('gradientradial'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.r0_ = aR0; gradient.x1_ = aX1; gradient.y1_ = aY1; gradient.r1_ = aR1; return gradient; }; contextPrototype.drawImage = function(image, var_args) { var dx, dy, dw, dh, sx, sy, sw, sh; // to find the original width we overide the width and height var oldRuntimeWidth = image.runtimeStyle.width; var oldRuntimeHeight = image.runtimeStyle.height; image.runtimeStyle.width = 'auto'; image.runtimeStyle.height = 'auto'; // get the original size var w = image.width; var h = image.height; // and remove overides image.runtimeStyle.width = oldRuntimeWidth; image.runtimeStyle.height = oldRuntimeHeight; if (arguments.length == 3) { dx = arguments[1]; dy = arguments[2]; sx = sy = 0; sw = dw = w; sh = dh = h; } else if (arguments.length == 5) { dx = arguments[1]; dy = arguments[2]; dw = arguments[3]; dh = arguments[4]; sx = sy = 0; sw = w; sh = h; } else if (arguments.length == 9) { sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else { throw Error('Invalid number of arguments'); } var d = this.getCoords_(dx, dy); var w2 = sw / 2; var h2 = sh / 2; var vmlStr = []; var W = 10; var H = 10; // For some reason that I've now forgotten, using divs didn't work vmlStr.push(' <g_vml_:group', ' coordsize="', Z * W, ',', Z * H, '"', ' coordorigin="0,0"' , ' style="width:', W, 'px;height:', H, 'px;position:absolute;'); // If filters are necessary (rotation exists), create them // filters are bog-slow, so only create them if abbsolutely necessary // The following check doesn't account for skews (which don't exist // in the canvas spec (yet) anyway. if (this.m_[0][0] != 1 || this.m_[0][1] || this.m_[1][1] != 1 || this.m_[1][0]) { var filter = []; // Note the 12/21 reversal filter.push('M11=', this.m_[0][0], ',', 'M12=', this.m_[1][0], ',', 'M21=', this.m_[0][1], ',', 'M22=', this.m_[1][1], ',', 'Dx=', mr(d.x / Z), ',', 'Dy=', mr(d.y / Z), ''); // Bounding box calculation (need to minimize displayed area so that // filters don't waste time on unused pixels. var max = d; var c2 = this.getCoords_(dx + dw, dy); var c3 = this.getCoords_(dx, dy + dh); var c4 = this.getCoords_(dx + dw, dy + dh); max.x = m.max(max.x, c2.x, c3.x, c4.x); max.y = m.max(max.y, c2.y, c3.y, c4.y); vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z), 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(', filter.join(''), ", sizingmethod='clip');"); } else { vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;'); } vmlStr.push(' ">' , '<g_vml_:image src="', image.src, '"', ' style="width:', Z * dw, 'px;', ' height:', Z * dh, 'px"', ' cropleft="', sx / w, '"', ' croptop="', sy / h, '"', ' cropright="', (w - sx - sw) / w, '"', ' cropbottom="', (h - sy - sh) / h, '"', ' />', '</g_vml_:group>'); this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); }; contextPrototype.stroke = function(aFill) { var W = 10; var H = 10; // Divide the shape into chunks if it's too long because IE has a limit // somewhere for how long a VML shape can be. This simple division does // not work with fills, only strokes, unfortunately. var chunkSize = 5000; var min = {x: null, y: null}; var max = {x: null, y: null}; for (var j = 0; j < this.currentPath_.length; j += chunkSize) { var lineStr = []; var lineOpen = false; lineStr.push('<g_vml_:shape', ' filled="', !!aFill, '"', ' style="position:absolute;width:', W, 'px;height:', H, 'px;"', ' coordorigin="0,0"', ' coordsize="', Z * W, ',', Z * H, '"', ' stroked="', !aFill, '"', ' path="'); var newSeq = false; for (var i = j; i < Math.min(j + chunkSize, this.currentPath_.length); i++) { if (i % chunkSize == 0 && i > 0) { // move into position for next chunk lineStr.push(' m ', mr(this.currentPath_[i-1].x), ',', mr(this.currentPath_[i-1].y)); } var p = this.currentPath_[i]; var c; switch (p.type) { case 'moveTo': c = p; lineStr.push(' m ', mr(p.x), ',', mr(p.y)); break; case 'lineTo': lineStr.push(' l ', mr(p.x), ',', mr(p.y)); break; case 'close': lineStr.push(' x '); p = null; break; case 'bezierCurveTo': lineStr.push(' c ', mr(p.cp1x), ',', mr(p.cp1y), ',', mr(p.cp2x), ',', mr(p.cp2y), ',', mr(p.x), ',', mr(p.y)); break; case 'at': case 'wa': lineStr.push(' ', p.type, ' ', mr(p.x - this.arcScaleX_ * p.radius), ',', mr(p.y - this.arcScaleY_ * p.radius), ' ', mr(p.x + this.arcScaleX_ * p.radius), ',', mr(p.y + this.arcScaleY_ * p.radius), ' ', mr(p.xStart), ',', mr(p.yStart), ' ', mr(p.xEnd), ',', mr(p.yEnd)); break; } // TODO: Following is broken for curves due to // move to proper paths. // Figure out dimensions so we can do gradient fills // properly if (p) { if (min.x == null || p.x < min.x) { min.x = p.x; } if (max.x == null || p.x > max.x) { max.x = p.x; } if (min.y == null || p.y < min.y) { min.y = p.y; } if (max.y == null || p.y > max.y) { max.y = p.y; } } } lineStr.push(' ">'); if (!aFill) { appendStroke(this, lineStr); } else { appendFill(this, lineStr, min, max); } lineStr.push('</g_vml_:shape>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); } }; function appendStroke(ctx, lineStr) { var a = processStyle(ctx.strokeStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; var lineWidth = ctx.lineScale_ * ctx.lineWidth; // VML cannot correctly render a line if the width is less than 1px. // In that case, we dilute the color to make the line look thinner. if (lineWidth < 1) { opacity *= lineWidth; } lineStr.push( '<g_vml_:stroke', ' opacity="', opacity, '"', ' joinstyle="', ctx.lineJoin, '"', ' miterlimit="', ctx.miterLimit, '"', ' endcap="', processLineCap(ctx.lineCap), '"', ' weight="', lineWidth, 'px"', ' color="', color, '" />' ); } function appendFill(ctx, lineStr, min, max) { var fillStyle = ctx.fillStyle; var arcScaleX = ctx.arcScaleX_; var arcScaleY = ctx.arcScaleY_; var width = max.x - min.x; var height = max.y - min.y; if (fillStyle instanceof CanvasGradient_) { // TODO: Gradients transformed with the transformation matrix. var angle = 0; var focus = {x: 0, y: 0}; // additional offset var shift = 0; // scale factor for offset var expansion = 1; if (fillStyle.type_ == 'gradient') { var x0 = fillStyle.x0_ / arcScaleX; var y0 = fillStyle.y0_ / arcScaleY; var x1 = fillStyle.x1_ / arcScaleX; var y1 = fillStyle.y1_ / arcScaleY; var p0 = ctx.getCoords_(x0, y0); var p1 = ctx.getCoords_(x1, y1); var dx = p1.x - p0.x; var dy = p1.y - p0.y; angle = Math.atan2(dx, dy) * 180 / Math.PI; // The angle should be a non-negative number. if (angle < 0) { angle += 360; } // Very small angles produce an unexpected result because they are // converted to a scientific notation string. if (angle < 1e-6) { angle = 0; } } else { var p0 = ctx.getCoords_(fillStyle.x0_, fillStyle.y0_); focus = { x: (p0.x - min.x) / width, y: (p0.y - min.y) / height }; width /= arcScaleX * Z; height /= arcScaleY * Z; var dimension = m.max(width, height); shift = 2 * fillStyle.r0_ / dimension; expansion = 2 * fillStyle.r1_ / dimension - shift; } // We need to sort the color stops in ascending order by offset, // otherwise IE won't interpret it correctly. var stops = fillStyle.colors_; stops.sort(function(cs1, cs2) { return cs1.offset - cs2.offset; }); var length = stops.length; var color1 = stops[0].color; var color2 = stops[length - 1].color; var opacity1 = stops[0].alpha * ctx.globalAlpha; var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; var colors = []; for (var i = 0; i < length; i++) { var stop = stops[i]; colors.push(stop.offset * expansion + shift + ' ' + stop.color); } // When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"', ' method="none" focus="100%"', ' color="', color1, '"', ' color2="', color2, '"', ' colors="', colors.join(','), '"', ' opacity="', opacity2, '"', ' g_o_:opacity2="', opacity1, '"', ' angle="', angle, '"', ' focusposition="', focus.x, ',', focus.y, '" />'); } else if (fillStyle instanceof CanvasPattern_) { if (width && height) { var deltaLeft = -min.x; var deltaTop = -min.y; lineStr.push('<g_vml_:fill', ' position="', deltaLeft / width * arcScaleX * arcScaleX, ',', deltaTop / height * arcScaleY * arcScaleY, '"', ' type="tile"', // TODO: Figure out the correct size to fit the scale. //' size="', w, 'px ', h, 'px"', ' src="', fillStyle.src_, '" />'); } } else { var a = processStyle(ctx.fillStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />'); } } contextPrototype.fill = function() { this.stroke(true); }; contextPrototype.closePath = function() { this.currentPath_.push({type: 'close'}); }; /** * @private */ contextPrototype.getCoords_ = function(aX, aY) { var m = this.m_; return { x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 }; }; contextPrototype.save = function() { var o = {}; copyState(this, o); this.aStack_.push(o); this.mStack_.push(this.m_); this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); }; contextPrototype.restore = function() { if (this.aStack_.length) { copyState(this.aStack_.pop(), this); this.m_ = this.mStack_.pop(); } }; function matrixIsFinite(m) { return isFinite(m[0][0]) && isFinite(m[0][1]) && isFinite(m[1][0]) && isFinite(m[1][1]) && isFinite(m[2][0]) && isFinite(m[2][1]); } function setM(ctx, m, updateLineScale) { if (!matrixIsFinite(m)) { return; } ctx.m_ = m; if (updateLineScale) { // Get the line scale. // Determinant of this.m_ means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; ctx.lineScale_ = sqrt(abs(det)); } } contextPrototype.translate = function(aX, aY) { var m1 = [ [1, 0, 0], [0, 1, 0], [aX, aY, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.rotate = function(aRot) { var c = mc(aRot); var s = ms(aRot); var m1 = [ [c, s, 0], [-s, c, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.scale = function(aX, aY) { this.arcScaleX_ *= aX; this.arcScaleY_ *= aY; var m1 = [ [aX, 0, 0], [0, aY, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { var m1 = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { var m = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, m, true); }; /** * The text drawing function. * The maxWidth argument isn't taken in account, since no browser supports * it yet. */ contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { var m = this.m_, delta = 1000, left = 0, right = delta, offset = {x: 0, y: 0}, lineStr = []; var fontStyle = getComputedStyle(processFontStyle(this.font), this.element_); var fontStyleString = buildStyle(fontStyle); var elementStyle = this.element_.currentStyle; var textAlign = this.textAlign.toLowerCase(); switch (textAlign) { case 'left': case 'center': case 'right': break; case 'end': textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; break; case 'start': textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; break; default: textAlign = 'left'; } // 1.75 is an arbitrary number, as there is no info about the text baseline switch (this.textBaseline) { case 'hanging': case 'top': offset.y = fontStyle.size / 1.75; break; case 'middle': break; default: case null: case 'alphabetic': case 'ideographic': case 'bottom': offset.y = -fontStyle.size / 2.25; break; } switch(textAlign) { case 'right': left = delta; right = 0.05; break; case 'center': left = right = delta / 2; break; } var d = this.getCoords_(x + offset.x, y + offset.y); lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ', ' coordsize="100 100" coordorigin="0 0"', ' filled="', !stroke, '" stroked="', !!stroke, '" style="position:absolute;width:1px;height:1px;">'); if (stroke) { appendStroke(this, lineStr); } else { // TODO: Fix the min and max params. appendFill(this, lineStr, {x: -left, y: 0}, {x: right, y: fontStyle.size}); } var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ', ' offset="', skewOffset, '" origin="', left ,' 0" />', '<g_vml_:path textpathok="true" />', '<g_vml_:textpath on="true" string="', encodeHtmlAttribute(text), '" style="v-text-align:', textAlign, ';font:', encodeHtmlAttribute(fontStyleString), '" /></g_vml_:line>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; contextPrototype.fillText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, false); }; contextPrototype.strokeText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, true); }; contextPrototype.measureText = function(text) { if (!this.textMeasureEl_) { var s = '<span style="position:absolute;' + 'top:-20000px;left:0;padding:0;margin:0;border:none;' + 'white-space:pre;"></span>'; this.element_.insertAdjacentHTML('beforeEnd', s); this.textMeasureEl_ = this.element_.lastChild; } var doc = this.element_.ownerDocument; this.textMeasureEl_.innerHTML = ''; this.textMeasureEl_.style.font = this.font; // Don't use innerHTML or innerText because they allow markup/whitespace. this.textMeasureEl_.appendChild(doc.createTextNode(text)); return {width: this.textMeasureEl_.offsetWidth}; }; /******** STUBS ********/ contextPrototype.clip = function() { // TODO: Implement }; contextPrototype.arcTo = function() { // TODO: Implement }; contextPrototype.createPattern = function(image, repetition) { return new CanvasPattern_(image, repetition); }; // Gradient / Pattern Stubs function CanvasGradient_(aType) { this.type_ = aType; this.x0_ = 0; this.y0_ = 0; this.r0_ = 0; this.x1_ = 0; this.y1_ = 0; this.r1_ = 0; this.colors_ = []; } CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { aColor = processStyle(aColor); this.colors_.push({offset: aOffset, color: aColor.color, alpha: aColor.alpha}); }; function CanvasPattern_(image, repetition) { assertImageIsValid(image); switch (repetition) { case 'repeat': case null: case '': this.repetition_ = 'repeat'; break case 'repeat-x': case 'repeat-y': case 'no-repeat': this.repetition_ = repetition; break; default: throwException('SYNTAX_ERR'); } this.src_ = image.src; this.width_ = image.width; this.height_ = image.height; } function throwException(s) { throw new DOMException_(s); } function assertImageIsValid(img) { if (!img || img.nodeType != 1 || img.tagName != 'IMG') { throwException('TYPE_MISMATCH_ERR'); } if (img.readyState != 'complete') { throwException('INVALID_STATE_ERR'); } } function DOMException_(s) { this.code = this[s]; this.message = s +': DOM Exception ' + this.code; } var p = DOMException_.prototype = new Error; p.INDEX_SIZE_ERR = 1; p.DOMSTRING_SIZE_ERR = 2; p.HIERARCHY_REQUEST_ERR = 3; p.WRONG_DOCUMENT_ERR = 4; p.INVALID_CHARACTER_ERR = 5; p.NO_DATA_ALLOWED_ERR = 6; p.NO_MODIFICATION_ALLOWED_ERR = 7; p.NOT_FOUND_ERR = 8; p.NOT_SUPPORTED_ERR = 9; p.INUSE_ATTRIBUTE_ERR = 10; p.INVALID_STATE_ERR = 11; p.SYNTAX_ERR = 12; p.INVALID_MODIFICATION_ERR = 13; p.NAMESPACE_ERR = 14; p.INVALID_ACCESS_ERR = 15; p.VALIDATION_ERR = 16; p.TYPE_MISMATCH_ERR = 17; // set up externs G_vmlCanvasManager = G_vmlCanvasManager_; CanvasRenderingContext2D = CanvasRenderingContext2D_; CanvasGradient = CanvasGradient_; CanvasPattern = CanvasPattern_; DOMException = DOMException_; })(); } // if
JavaScript
// Copyright 2006 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. // Known Issues: // // * Patterns only support repeat. // * Radial gradient are not implemented. The VML version of these look very // different from the canvas one. // * Clipping paths are not implemented. // * Coordsize. The width and height attribute have higher priority than the // width and height style values which isn't correct. // * Painting mode isn't implemented. // * Canvas width/height should is using content-box by default. IE in // Quirks mode will draw the canvas using border-box. Either change your // doctype to HTML5 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) // or use Box Sizing Behavior from WebFX // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) // * Non uniform scaling does not correctly scale strokes. // * Filling very large shapes (above 5000 points) is buggy. // * Optimize. There is always room for speed improvements. // Only add this code if we do not already have a canvas implementation if (!document.createElement('canvas').getContext) { (function() { // alias some functions to make (compiled) code shorter var m = Math; var mr = m.round; var ms = m.sin; var mc = m.cos; var abs = m.abs; var sqrt = m.sqrt; // this is used for sub pixel precision var Z = 10; var Z2 = Z / 2; /** * This funtion is assigned to the <canvas> elements as element.getContext(). * @this {HTMLElement} * @return {CanvasRenderingContext2D_} */ function getContext() { return this.context_ || (this.context_ = new CanvasRenderingContext2D_(this)); } var slice = Array.prototype.slice; /** * Binds a function to an object. The returned function will always use the * passed in {@code obj} as {@code this}. * * Example: * * g = bind(f, obj, a, b) * g(c, d) // will do f.call(obj, a, b, c, d) * * @param {Function} f The function to bind the object to * @param {Object} obj The object that should act as this when the function * is called * @param {*} var_args Rest arguments that will be used as the initial * arguments when the function is called * @return {Function} A new function that has bound this */ function bind(f, obj, var_args) { var a = slice.call(arguments, 2); return function() { return f.apply(obj, a.concat(slice.call(arguments))); }; } function encodeHtmlAttribute(s) { return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); } function addNamespacesAndStylesheet(doc) { // create xmlns if (!doc.namespaces['g_vml_']) { doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml', '#default#VML'); } if (!doc.namespaces['g_o_']) { doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office', '#default#VML'); } // Setup default CSS. Only add one style sheet per document if (!doc.styleSheets['ex_canvas_']) { var ss = doc.createStyleSheet(); ss.owningElement.id = 'ex_canvas_'; ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + // default size is 300x150 in Gecko and Opera 'text-align:left;width:300px;height:150px}'; } } // Add namespaces and stylesheet at startup. addNamespacesAndStylesheet(document); var G_vmlCanvasManager_ = { init: function(opt_doc) { if (/MSIE/.test(navigator.userAgent) && !window.opera) { var doc = opt_doc || document; // Create a dummy element so that IE will allow canvas elements to be // recognized. doc.createElement('canvas'); doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); } }, init_: function(doc) { // find all canvas elements var els = doc.getElementsByTagName('canvas'); for (var i = 0; i < els.length; i++) { this.initElement(els[i]); } }, /** * Public initializes a canvas element so that it can be used as canvas * element from now on. This is called automatically before the page is * loaded but if you are creating elements using createElement you need to * make sure this is called on the element. * @param {HTMLElement} el The canvas element to initialize. * @return {HTMLElement} the element that was created. */ initElement: function(el) { if (!el.getContext) { el.getContext = getContext; // Add namespaces and stylesheet to document of the element. addNamespacesAndStylesheet(el.ownerDocument); // Remove fallback content. There is no way to hide text nodes so we // just remove all childNodes. We could hide all elements and remove // text nodes but who really cares about the fallback content. el.innerHTML = ''; // do not use inline function because that will leak memory el.attachEvent('onpropertychange', onPropertyChange); el.attachEvent('onresize', onResize); var attrs = el.attributes; if (attrs.width && attrs.width.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setWidth_(attrs.width.nodeValue); el.style.width = attrs.width.nodeValue + 'px'; } else { el.width = el.clientWidth; } if (attrs.height && attrs.height.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setHeight_(attrs.height.nodeValue); el.style.height = attrs.height.nodeValue + 'px'; } else { el.height = el.clientHeight; } //el.getContext().setCoordsize_() } return el; } }; function onPropertyChange(e) { var el = e.srcElement; switch (e.propertyName) { case 'width': el.getContext().clearRect(); el.style.width = el.attributes.width.nodeValue + 'px'; // In IE8 this does not trigger onresize. el.firstChild.style.width = el.clientWidth + 'px'; break; case 'height': el.getContext().clearRect(); el.style.height = el.attributes.height.nodeValue + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; break; } } function onResize(e) { var el = e.srcElement; if (el.firstChild) { el.firstChild.style.width = el.clientWidth + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; } } G_vmlCanvasManager_.init(); // precompute "00" to "FF" var decToHex = []; for (var i = 0; i < 16; i++) { for (var j = 0; j < 16; j++) { decToHex[i * 16 + j] = i.toString(16) + j.toString(16); } } function createMatrixIdentity() { return [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; } function matrixMultiply(m1, m2) { var result = createMatrixIdentity(); for (var x = 0; x < 3; x++) { for (var y = 0; y < 3; y++) { var sum = 0; for (var z = 0; z < 3; z++) { sum += m1[x][z] * m2[z][y]; } result[x][y] = sum; } } return result; } function copyState(o1, o2) { o2.fillStyle = o1.fillStyle; o2.lineCap = o1.lineCap; o2.lineJoin = o1.lineJoin; o2.lineWidth = o1.lineWidth; o2.miterLimit = o1.miterLimit; o2.shadowBlur = o1.shadowBlur; o2.shadowColor = o1.shadowColor; o2.shadowOffsetX = o1.shadowOffsetX; o2.shadowOffsetY = o1.shadowOffsetY; o2.strokeStyle = o1.strokeStyle; o2.globalAlpha = o1.globalAlpha; o2.font = o1.font; o2.textAlign = o1.textAlign; o2.textBaseline = o1.textBaseline; o2.arcScaleX_ = o1.arcScaleX_; o2.arcScaleY_ = o1.arcScaleY_; o2.lineScale_ = o1.lineScale_; } var colorData = { aliceblue: '#F0F8FF', antiquewhite: '#FAEBD7', aquamarine: '#7FFFD4', azure: '#F0FFFF', beige: '#F5F5DC', bisque: '#FFE4C4', black: '#000000', blanchedalmond: '#FFEBCD', 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', 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', gainsboro: '#DCDCDC', ghostwhite: '#F8F8FF', gold: '#FFD700', goldenrod: '#DAA520', grey: '#808080', 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', lightgreen: '#90EE90', lightgrey: '#D3D3D3', lightpink: '#FFB6C1', lightsalmon: '#FFA07A', lightseagreen: '#20B2AA', lightskyblue: '#87CEFA', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#B0C4DE', lightyellow: '#FFFFE0', limegreen: '#32CD32', linen: '#FAF0E6', magenta: '#FF00FF', 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', oldlace: '#FDF5E6', 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', rosybrown: '#BC8F8F', royalblue: '#4169E1', saddlebrown: '#8B4513', salmon: '#FA8072', sandybrown: '#F4A460', seagreen: '#2E8B57', seashell: '#FFF5EE', sienna: '#A0522D', skyblue: '#87CEEB', slateblue: '#6A5ACD', slategray: '#708090', slategrey: '#708090', snow: '#FFFAFA', springgreen: '#00FF7F', steelblue: '#4682B4', tan: '#D2B48C', thistle: '#D8BFD8', tomato: '#FF6347', turquoise: '#40E0D0', violet: '#EE82EE', wheat: '#F5DEB3', whitesmoke: '#F5F5F5', yellowgreen: '#9ACD32' }; function getRgbHslContent(styleString) { var start = styleString.indexOf('(', 3); var end = styleString.indexOf(')', start + 1); var parts = styleString.substring(start + 1, end).split(','); // add alpha if needed if (parts.length == 4 && styleString.substr(3, 1) == 'a') { alpha = Number(parts[3]); } else { parts[3] = 1; } return parts; } function percent(s) { return parseFloat(s) / 100; } function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); } function hslToRgb(parts){ var r, g, b; h = parseFloat(parts[0]) / 360 % 360; if (h < 0) h++; s = clamp(percent(parts[1]), 0, 1); l = clamp(percent(parts[2]), 0, 1); 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 = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return '#' + decToHex[Math.floor(r * 255)] + decToHex[Math.floor(g * 255)] + decToHex[Math.floor(b * 255)]; } function hueToRgb(m1, m2, h) { if (h < 0) h++; if (h > 1) h--; if (6 * h < 1) return m1 + (m2 - m1) * 6 * h; else if (2 * h < 1) return m2; else if (3 * h < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6; else return m1; } function processStyle(styleString) { var str, alpha = 1; styleString = String(styleString); if (styleString.charAt(0) == '#') { str = styleString; } else if (/^rgb/.test(styleString)) { var parts = getRgbHslContent(styleString); var str = '#', n; for (var i = 0; i < 3; i++) { if (parts[i].indexOf('%') != -1) { n = Math.floor(percent(parts[i]) * 255); } else { n = Number(parts[i]); } str += decToHex[clamp(n, 0, 255)]; } alpha = parts[3]; } else if (/^hsl/.test(styleString)) { var parts = getRgbHslContent(styleString); str = hslToRgb(parts); alpha = parts[3]; } else { str = colorData[styleString] || styleString; } return {color: str, alpha: alpha}; } var DEFAULT_STYLE = { style: 'normal', variant: 'normal', weight: 'normal', size: 10, family: 'sans-serif' }; // Internal text style cache var fontStyleCache = {}; function processFontStyle(styleString) { if (fontStyleCache[styleString]) { return fontStyleCache[styleString]; } var el = document.createElement('div'); var style = el.style; try { style.font = styleString; } catch (ex) { // Ignore failures to set to invalid font. } return fontStyleCache[styleString] = { style: style.fontStyle || DEFAULT_STYLE.style, variant: style.fontVariant || DEFAULT_STYLE.variant, weight: style.fontWeight || DEFAULT_STYLE.weight, size: style.fontSize || DEFAULT_STYLE.size, family: style.fontFamily || DEFAULT_STYLE.family }; } function getComputedStyle(style, element) { var computedStyle = {}; for (var p in style) { computedStyle[p] = style[p]; } // Compute the size var canvasFontSize = parseFloat(element.currentStyle.fontSize), fontSize = parseFloat(style.size); if (typeof style.size == 'number') { computedStyle.size = style.size; } else if (style.size.indexOf('px') != -1) { computedStyle.size = fontSize; } else if (style.size.indexOf('em') != -1) { computedStyle.size = canvasFontSize * fontSize; } else if(style.size.indexOf('%') != -1) { computedStyle.size = (canvasFontSize / 100) * fontSize; } else if (style.size.indexOf('pt') != -1) { computedStyle.size = fontSize / .75; } else { computedStyle.size = canvasFontSize; } // Different scaling between normal text and VML text. This was found using // trial and error to get the same size as non VML text. computedStyle.size *= 0.981; return computedStyle; } function buildStyle(style) { return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + style.size + 'px ' + style.family; } function processLineCap(lineCap) { switch (lineCap) { case 'butt': return 'flat'; case 'round': return 'round'; case 'square': default: return 'square'; } } /** * This class implements CanvasRenderingContext2D interface as described by * the WHATWG. * @param {HTMLElement} surfaceElement The element that the 2D context should * be associated with */ function CanvasRenderingContext2D_(surfaceElement) { this.m_ = createMatrixIdentity(); this.mStack_ = []; this.aStack_ = []; this.currentPath_ = []; // Canvas context properties this.strokeStyle = '#000'; this.fillStyle = '#000'; this.lineWidth = 1; this.lineJoin = 'miter'; this.lineCap = 'butt'; this.miterLimit = Z * 1; this.globalAlpha = 1; this.font = '10px sans-serif'; this.textAlign = 'left'; this.textBaseline = 'alphabetic'; this.canvas = surfaceElement; var el = surfaceElement.ownerDocument.createElement('div'); el.style.width = surfaceElement.clientWidth + 'px'; el.style.height = surfaceElement.clientHeight + 'px'; el.style.overflow = 'hidden'; el.style.position = 'absolute'; surfaceElement.appendChild(el); this.element_ = el; this.arcScaleX_ = 1; this.arcScaleY_ = 1; this.lineScale_ = 1; } var contextPrototype = CanvasRenderingContext2D_.prototype; contextPrototype.clearRect = function() { if (this.textMeasureEl_) { this.textMeasureEl_.removeNode(true); this.textMeasureEl_ = null; } this.element_.innerHTML = ''; }; contextPrototype.beginPath = function() { // TODO: Branch current matrix so that save/restore has no effect // as per safari docs. this.currentPath_ = []; }; contextPrototype.moveTo = function(aX, aY) { var p = this.getCoords_(aX, aY); this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.lineTo = function(aX, aY) { var p = this.getCoords_(aX, aY); this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { var p = this.getCoords_(aX, aY); var cp1 = this.getCoords_(aCP1x, aCP1y); var cp2 = this.getCoords_(aCP2x, aCP2y); bezierCurveTo(this, cp1, cp2, p); }; // Helper function that takes the already fixed cordinates. function bezierCurveTo(self, cp1, cp2, p) { self.currentPath_.push({ type: 'bezierCurveTo', cp1x: cp1.x, cp1y: cp1.y, cp2x: cp2.x, cp2y: cp2.y, x: p.x, y: p.y }); self.currentX_ = p.x; self.currentY_ = p.y; } contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { // the following is lifted almost directly from // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes var cp = this.getCoords_(aCPx, aCPy); var p = this.getCoords_(aX, aY); var cp1 = { x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) }; var cp2 = { x: cp1.x + (p.x - this.currentX_) / 3.0, y: cp1.y + (p.y - this.currentY_) / 3.0 }; bezierCurveTo(this, cp1, cp2, p); }; contextPrototype.arc = function(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { aRadius *= Z; var arcType = aClockwise ? 'at' : 'wa'; var xStart = aX + mc(aStartAngle) * aRadius - Z2; var yStart = aY + ms(aStartAngle) * aRadius - Z2; var xEnd = aX + mc(aEndAngle) * aRadius - Z2; var yEnd = aY + ms(aEndAngle) * aRadius - Z2; // IE won't render arches drawn counter clockwise if xStart == xEnd. if (xStart == xEnd && !aClockwise) { xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something // that can be represented in binary } var p = this.getCoords_(aX, aY); var pStart = this.getCoords_(xStart, yStart); var pEnd = this.getCoords_(xEnd, yEnd); this.currentPath_.push({type: arcType, x: p.x, y: p.y, radius: aRadius, xStart: pStart.x, yStart: pStart.y, xEnd: pEnd.x, yEnd: pEnd.y}); }; contextPrototype.rect = function(aX, aY, aWidth, aHeight) { this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); }; contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.stroke(); this.currentPath_ = oldPath; }; contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.fill(); this.currentPath_ = oldPath; }; contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { var gradient = new CanvasGradient_('gradient'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.x1_ = aX1; gradient.y1_ = aY1; return gradient; }; contextPrototype.createRadialGradient = function(aX0, aY0, aR0, aX1, aY1, aR1) { var gradient = new CanvasGradient_('gradientradial'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.r0_ = aR0; gradient.x1_ = aX1; gradient.y1_ = aY1; gradient.r1_ = aR1; return gradient; }; contextPrototype.drawImage = function(image, var_args) { var dx, dy, dw, dh, sx, sy, sw, sh; // to find the original width we overide the width and height var oldRuntimeWidth = image.runtimeStyle.width; var oldRuntimeHeight = image.runtimeStyle.height; image.runtimeStyle.width = 'auto'; image.runtimeStyle.height = 'auto'; // get the original size var w = image.width; var h = image.height; // and remove overides image.runtimeStyle.width = oldRuntimeWidth; image.runtimeStyle.height = oldRuntimeHeight; if (arguments.length == 3) { dx = arguments[1]; dy = arguments[2]; sx = sy = 0; sw = dw = w; sh = dh = h; } else if (arguments.length == 5) { dx = arguments[1]; dy = arguments[2]; dw = arguments[3]; dh = arguments[4]; sx = sy = 0; sw = w; sh = h; } else if (arguments.length == 9) { sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else { throw Error('Invalid number of arguments'); } var d = this.getCoords_(dx, dy); var w2 = sw / 2; var h2 = sh / 2; var vmlStr = []; var W = 10; var H = 10; // For some reason that I've now forgotten, using divs didn't work vmlStr.push(' <g_vml_:group', ' coordsize="', Z * W, ',', Z * H, '"', ' coordorigin="0,0"' , ' style="width:', W, 'px;height:', H, 'px;position:absolute;'); // If filters are necessary (rotation exists), create them // filters are bog-slow, so only create them if abbsolutely necessary // The following check doesn't account for skews (which don't exist // in the canvas spec (yet) anyway. if (this.m_[0][0] != 1 || this.m_[0][1] || this.m_[1][1] != 1 || this.m_[1][0]) { var filter = []; // Note the 12/21 reversal filter.push('M11=', this.m_[0][0], ',', 'M12=', this.m_[1][0], ',', 'M21=', this.m_[0][1], ',', 'M22=', this.m_[1][1], ',', 'Dx=', mr(d.x / Z), ',', 'Dy=', mr(d.y / Z), ''); // Bounding box calculation (need to minimize displayed area so that // filters don't waste time on unused pixels. var max = d; var c2 = this.getCoords_(dx + dw, dy); var c3 = this.getCoords_(dx, dy + dh); var c4 = this.getCoords_(dx + dw, dy + dh); max.x = m.max(max.x, c2.x, c3.x, c4.x); max.y = m.max(max.y, c2.y, c3.y, c4.y); vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z), 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(', filter.join(''), ", sizingmethod='clip');"); } else { vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;'); } vmlStr.push(' ">' , '<g_vml_:image src="', image.src, '"', ' style="width:', Z * dw, 'px;', ' height:', Z * dh, 'px"', ' cropleft="', sx / w, '"', ' croptop="', sy / h, '"', ' cropright="', (w - sx - sw) / w, '"', ' cropbottom="', (h - sy - sh) / h, '"', ' />', '</g_vml_:group>'); this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); }; contextPrototype.stroke = function(aFill) { var W = 10; var H = 10; // Divide the shape into chunks if it's too long because IE has a limit // somewhere for how long a VML shape can be. This simple division does // not work with fills, only strokes, unfortunately. var chunkSize = 5000; var min = {x: null, y: null}; var max = {x: null, y: null}; for (var j = 0; j < this.currentPath_.length; j += chunkSize) { var lineStr = []; var lineOpen = false; lineStr.push('<g_vml_:shape', ' filled="', !!aFill, '"', ' style="position:absolute;width:', W, 'px;height:', H, 'px;"', ' coordorigin="0,0"', ' coordsize="', Z * W, ',', Z * H, '"', ' stroked="', !aFill, '"', ' path="'); var newSeq = false; for (var i = j; i < Math.min(j + chunkSize, this.currentPath_.length); i++) { if (i % chunkSize == 0 && i > 0) { // move into position for next chunk lineStr.push(' m ', mr(this.currentPath_[i-1].x), ',', mr(this.currentPath_[i-1].y)); } var p = this.currentPath_[i]; var c; switch (p.type) { case 'moveTo': c = p; lineStr.push(' m ', mr(p.x), ',', mr(p.y)); break; case 'lineTo': lineStr.push(' l ', mr(p.x), ',', mr(p.y)); break; case 'close': lineStr.push(' x '); p = null; break; case 'bezierCurveTo': lineStr.push(' c ', mr(p.cp1x), ',', mr(p.cp1y), ',', mr(p.cp2x), ',', mr(p.cp2y), ',', mr(p.x), ',', mr(p.y)); break; case 'at': case 'wa': lineStr.push(' ', p.type, ' ', mr(p.x - this.arcScaleX_ * p.radius), ',', mr(p.y - this.arcScaleY_ * p.radius), ' ', mr(p.x + this.arcScaleX_ * p.radius), ',', mr(p.y + this.arcScaleY_ * p.radius), ' ', mr(p.xStart), ',', mr(p.yStart), ' ', mr(p.xEnd), ',', mr(p.yEnd)); break; } // TODO: Following is broken for curves due to // move to proper paths. // Figure out dimensions so we can do gradient fills // properly if (p) { if (min.x == null || p.x < min.x) { min.x = p.x; } if (max.x == null || p.x > max.x) { max.x = p.x; } if (min.y == null || p.y < min.y) { min.y = p.y; } if (max.y == null || p.y > max.y) { max.y = p.y; } } } lineStr.push(' ">'); if (!aFill) { appendStroke(this, lineStr); } else { appendFill(this, lineStr, min, max); } lineStr.push('</g_vml_:shape>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); } }; function appendStroke(ctx, lineStr) { var a = processStyle(ctx.strokeStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; var lineWidth = ctx.lineScale_ * ctx.lineWidth; // VML cannot correctly render a line if the width is less than 1px. // In that case, we dilute the color to make the line look thinner. if (lineWidth < 1) { opacity *= lineWidth; } lineStr.push( '<g_vml_:stroke', ' opacity="', opacity, '"', ' joinstyle="', ctx.lineJoin, '"', ' miterlimit="', ctx.miterLimit, '"', ' endcap="', processLineCap(ctx.lineCap), '"', ' weight="', lineWidth, 'px"', ' color="', color, '" />' ); } function appendFill(ctx, lineStr, min, max) { var fillStyle = ctx.fillStyle; var arcScaleX = ctx.arcScaleX_; var arcScaleY = ctx.arcScaleY_; var width = max.x - min.x; var height = max.y - min.y; if (fillStyle instanceof CanvasGradient_) { // TODO: Gradients transformed with the transformation matrix. var angle = 0; var focus = {x: 0, y: 0}; // additional offset var shift = 0; // scale factor for offset var expansion = 1; if (fillStyle.type_ == 'gradient') { var x0 = fillStyle.x0_ / arcScaleX; var y0 = fillStyle.y0_ / arcScaleY; var x1 = fillStyle.x1_ / arcScaleX; var y1 = fillStyle.y1_ / arcScaleY; var p0 = ctx.getCoords_(x0, y0); var p1 = ctx.getCoords_(x1, y1); var dx = p1.x - p0.x; var dy = p1.y - p0.y; angle = Math.atan2(dx, dy) * 180 / Math.PI; // The angle should be a non-negative number. if (angle < 0) { angle += 360; } // Very small angles produce an unexpected result because they are // converted to a scientific notation string. if (angle < 1e-6) { angle = 0; } } else { var p0 = ctx.getCoords_(fillStyle.x0_, fillStyle.y0_); focus = { x: (p0.x - min.x) / width, y: (p0.y - min.y) / height }; width /= arcScaleX * Z; height /= arcScaleY * Z; var dimension = m.max(width, height); shift = 2 * fillStyle.r0_ / dimension; expansion = 2 * fillStyle.r1_ / dimension - shift; } // We need to sort the color stops in ascending order by offset, // otherwise IE won't interpret it correctly. var stops = fillStyle.colors_; stops.sort(function(cs1, cs2) { return cs1.offset - cs2.offset; }); var length = stops.length; var color1 = stops[0].color; var color2 = stops[length - 1].color; var opacity1 = stops[0].alpha * ctx.globalAlpha; var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; var colors = []; for (var i = 0; i < length; i++) { var stop = stops[i]; colors.push(stop.offset * expansion + shift + ' ' + stop.color); } // When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"', ' method="none" focus="100%"', ' color="', color1, '"', ' color2="', color2, '"', ' colors="', colors.join(','), '"', ' opacity="', opacity2, '"', ' g_o_:opacity2="', opacity1, '"', ' angle="', angle, '"', ' focusposition="', focus.x, ',', focus.y, '" />'); } else if (fillStyle instanceof CanvasPattern_) { if (width && height) { var deltaLeft = -min.x; var deltaTop = -min.y; lineStr.push('<g_vml_:fill', ' position="', deltaLeft / width * arcScaleX * arcScaleX, ',', deltaTop / height * arcScaleY * arcScaleY, '"', ' type="tile"', // TODO: Figure out the correct size to fit the scale. //' size="', w, 'px ', h, 'px"', ' src="', fillStyle.src_, '" />'); } } else { var a = processStyle(ctx.fillStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />'); } } contextPrototype.fill = function() { this.stroke(true); }; contextPrototype.closePath = function() { this.currentPath_.push({type: 'close'}); }; /** * @private */ contextPrototype.getCoords_ = function(aX, aY) { var m = this.m_; return { x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 }; }; contextPrototype.save = function() { var o = {}; copyState(this, o); this.aStack_.push(o); this.mStack_.push(this.m_); this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); }; contextPrototype.restore = function() { if (this.aStack_.length) { copyState(this.aStack_.pop(), this); this.m_ = this.mStack_.pop(); } }; function matrixIsFinite(m) { return isFinite(m[0][0]) && isFinite(m[0][1]) && isFinite(m[1][0]) && isFinite(m[1][1]) && isFinite(m[2][0]) && isFinite(m[2][1]); } function setM(ctx, m, updateLineScale) { if (!matrixIsFinite(m)) { return; } ctx.m_ = m; if (updateLineScale) { // Get the line scale. // Determinant of this.m_ means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; ctx.lineScale_ = sqrt(abs(det)); } } contextPrototype.translate = function(aX, aY) { var m1 = [ [1, 0, 0], [0, 1, 0], [aX, aY, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.rotate = function(aRot) { var c = mc(aRot); var s = ms(aRot); var m1 = [ [c, s, 0], [-s, c, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.scale = function(aX, aY) { this.arcScaleX_ *= aX; this.arcScaleY_ *= aY; var m1 = [ [aX, 0, 0], [0, aY, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { var m1 = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { var m = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, m, true); }; /** * The text drawing function. * The maxWidth argument isn't taken in account, since no browser supports * it yet. */ contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { var m = this.m_, delta = 1000, left = 0, right = delta, offset = {x: 0, y: 0}, lineStr = []; var fontStyle = getComputedStyle(processFontStyle(this.font), this.element_); var fontStyleString = buildStyle(fontStyle); var elementStyle = this.element_.currentStyle; var textAlign = this.textAlign.toLowerCase(); switch (textAlign) { case 'left': case 'center': case 'right': break; case 'end': textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; break; case 'start': textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; break; default: textAlign = 'left'; } // 1.75 is an arbitrary number, as there is no info about the text baseline switch (this.textBaseline) { case 'hanging': case 'top': offset.y = fontStyle.size / 1.75; break; case 'middle': break; default: case null: case 'alphabetic': case 'ideographic': case 'bottom': offset.y = -fontStyle.size / 2.25; break; } switch(textAlign) { case 'right': left = delta; right = 0.05; break; case 'center': left = right = delta / 2; break; } var d = this.getCoords_(x + offset.x, y + offset.y); lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ', ' coordsize="100 100" coordorigin="0 0"', ' filled="', !stroke, '" stroked="', !!stroke, '" style="position:absolute;width:1px;height:1px;">'); if (stroke) { appendStroke(this, lineStr); } else { // TODO: Fix the min and max params. appendFill(this, lineStr, {x: -left, y: 0}, {x: right, y: fontStyle.size}); } var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ', ' offset="', skewOffset, '" origin="', left ,' 0" />', '<g_vml_:path textpathok="true" />', '<g_vml_:textpath on="true" string="', encodeHtmlAttribute(text), '" style="v-text-align:', textAlign, ';font:', encodeHtmlAttribute(fontStyleString), '" /></g_vml_:line>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; contextPrototype.fillText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, false); }; contextPrototype.strokeText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, true); }; contextPrototype.measureText = function(text) { if (!this.textMeasureEl_) { var s = '<span style="position:absolute;' + 'top:-20000px;left:0;padding:0;margin:0;border:none;' + 'white-space:pre;"></span>'; this.element_.insertAdjacentHTML('beforeEnd', s); this.textMeasureEl_ = this.element_.lastChild; } var doc = this.element_.ownerDocument; this.textMeasureEl_.innerHTML = ''; this.textMeasureEl_.style.font = this.font; // Don't use innerHTML or innerText because they allow markup/whitespace. this.textMeasureEl_.appendChild(doc.createTextNode(text)); return {width: this.textMeasureEl_.offsetWidth}; }; /******** STUBS ********/ contextPrototype.clip = function() { // TODO: Implement }; contextPrototype.arcTo = function() { // TODO: Implement }; contextPrototype.createPattern = function(image, repetition) { return new CanvasPattern_(image, repetition); }; // Gradient / Pattern Stubs function CanvasGradient_(aType) { this.type_ = aType; this.x0_ = 0; this.y0_ = 0; this.r0_ = 0; this.x1_ = 0; this.y1_ = 0; this.r1_ = 0; this.colors_ = []; } CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { aColor = processStyle(aColor); this.colors_.push({offset: aOffset, color: aColor.color, alpha: aColor.alpha}); }; function CanvasPattern_(image, repetition) { assertImageIsValid(image); switch (repetition) { case 'repeat': case null: case '': this.repetition_ = 'repeat'; break case 'repeat-x': case 'repeat-y': case 'no-repeat': this.repetition_ = repetition; break; default: throwException('SYNTAX_ERR'); } this.src_ = image.src; this.width_ = image.width; this.height_ = image.height; } function throwException(s) { throw new DOMException_(s); } function assertImageIsValid(img) { if (!img || img.nodeType != 1 || img.tagName != 'IMG') { throwException('TYPE_MISMATCH_ERR'); } if (img.readyState != 'complete') { throwException('INVALID_STATE_ERR'); } } function DOMException_(s) { this.code = this[s]; this.message = s +': DOM Exception ' + this.code; } var p = DOMException_.prototype = new Error; p.INDEX_SIZE_ERR = 1; p.DOMSTRING_SIZE_ERR = 2; p.HIERARCHY_REQUEST_ERR = 3; p.WRONG_DOCUMENT_ERR = 4; p.INVALID_CHARACTER_ERR = 5; p.NO_DATA_ALLOWED_ERR = 6; p.NO_MODIFICATION_ALLOWED_ERR = 7; p.NOT_FOUND_ERR = 8; p.NOT_SUPPORTED_ERR = 9; p.INUSE_ATTRIBUTE_ERR = 10; p.INVALID_STATE_ERR = 11; p.SYNTAX_ERR = 12; p.INVALID_MODIFICATION_ERR = 13; p.NAMESPACE_ERR = 14; p.INVALID_ACCESS_ERR = 15; p.VALIDATION_ERR = 16; p.TYPE_MISMATCH_ERR = 17; // set up externs G_vmlCanvasManager = G_vmlCanvasManager_; CanvasRenderingContext2D = CanvasRenderingContext2D_; CanvasGradient = CanvasGradient_; CanvasPattern = CanvasPattern_; DOMException = DOMException_; })(); } // if
JavaScript
/** * Creates a new level control. * @constructor * @param {IoMap} iomap the IO map controller. * @param {Array.<string>} levels the levels to create switchers for. */ function LevelControl(iomap, levels) { var that = this; this.iomap_ = iomap; this.el_ = this.initDom_(levels); google.maps.event.addListener(iomap, 'level_changed', function() { that.changeLevel_(iomap.get('level')); }); } /** * Gets the DOM element for the control. * @return {Element} */ LevelControl.prototype.getElement = function() { return this.el_; }; /** * Creates the necessary DOM for the control. * @return {Element} */ LevelControl.prototype.initDom_ = function(levelDefinition) { var controlDiv = document.createElement('DIV'); controlDiv.setAttribute('id', 'levels-wrapper'); var levels = document.createElement('DIV'); levels.setAttribute('id', 'levels'); controlDiv.appendChild(levels); var levelSelect = this.levelSelect_ = document.createElement('DIV'); levelSelect.setAttribute('id', 'level-select'); levels.appendChild(levelSelect); this.levelDivs_ = []; var that = this; for (var i = 0, level; level = levelDefinition[i]; i++) { var div = document.createElement('DIV'); div.innerHTML = 'Level ' + level; div.setAttribute('id', 'level-' + level); div.className = 'level'; levels.appendChild(div); this.levelDivs_.push(div); google.maps.event.addDomListener(div, 'click', function(e) { var id = e.currentTarget.getAttribute('id'); var level = parseInt(id.replace('level-', ''), 10); that.iomap_.setHash('level' + level); }); } controlDiv.index = 1; return controlDiv; }; /** * Changes the highlighted level in the control. * @param {number} level the level number to select. */ LevelControl.prototype.changeLevel_ = function(level) { if (this.currentLevelDiv_) { this.currentLevelDiv_.className = this.currentLevelDiv_.className.replace(' level-selected', ''); } var h = 25; if (window['ioEmbed']) { h = (window.screen.availWidth > 600) ? 34 : 24; } this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px'; var div = this.levelDivs_[level - 1]; div.className += ' level-selected'; this.currentLevelDiv_ = div; };
JavaScript
// Copyright 2011 Google /** * 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. */ /** * The Google IO Map * @constructor */ var IoMap = function() { var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025); /** @type {Node} */ this.mapDiv_ = document.getElementById(this.MAP_ID); var ioStyle = [ { 'featureType': 'road', stylers: [ { hue: '#00aaff' }, { gamma: 1.67 }, { saturation: -24 }, { lightness: -38 } ] },{ 'featureType': 'road', 'elementType': 'labels', stylers: [ { invert_lightness: true } ] }]; /** @type {boolean} */ this.ready_ = false; /** @type {google.maps.Map} */ this.map_ = new google.maps.Map(this.mapDiv_, { zoom: 18, center: moscone, navigationControl: true, mapTypeControl: false, scaleControl: true, mapTypeId: 'io', streetViewControl: false }); var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle)); this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style)); google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['onMapReady'](); } }); /** @type {Array.<Floor>} */ this.floors_ = []; for (var i = 0; i < this.LEVELS_.length; i++) { this.floors_.push(new Floor(this.map_)); } this.addLevelControl_(); this.addMapOverlay_(); this.loadMapContent_(); this.initLocationHashWatcher_(); if (!document.location.hash) { this.showLevel(1, true); } } IoMap.prototype = new google.maps.MVCObject; /** * The id of the Element to add the map to. * * @type {string} * @const */ IoMap.prototype.MAP_ID = 'map-canvas'; /** * The levels of the Moscone Center. * * @type {Array.<string>} * @private */ IoMap.prototype.LEVELS_ = ['1', '2', '3']; /** * Location where the tiles are hosted. * * @type {string} * @private */ IoMap.prototype.BASE_TILE_URL_ = 'http://www.gstatic.com/io2010maps/tiles/5/'; /** * The minimum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MIN_ZOOM_ = 16; /** * The maximum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MAX_ZOOM_ = 20; /** * The template for loading tiles. Replace {L} with the level, {Z} with the * zoom level, {X} and {Y} with respective tile coordinates. * * @type {string} * @private */ IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + 'L{L}_{Z}_{X}_{Y}.png'; /** * @type {string} * @private */ IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png'; /** * The extent of the overlay at certain zoom levels. * * @type {Object.<string, Array.<Array.<number>>>} * @private */ IoMap.prototype.RESOLUTION_BOUNDS_ = { 16: [[10484, 10485], [25328, 25329]], 17: [[20969, 20970], [50657, 50658]], 18: [[41939, 41940], [101315, 101317]], 19: [[83878, 83881], [202631, 202634]], 20: [[167757, 167763], [405263, 405269]] }; /** * The previous hash to compare against. * * @type {string?} * @private */ IoMap.prototype.prevHash_ = null; /** * Initialise the location hash watcher. * * @private */ IoMap.prototype.initLocationHashWatcher_ = function() { var that = this; if ('onhashchange' in window) { window.addEventListener('hashchange', function() { that.parseHash_(); }, true); } else { var that = this window.setInterval(function() { that.parseHash_(); }, 100); } this.parseHash_(); }; /** * Called from Android. * * @param {Number} x A percentage to pan left by. */ IoMap.prototype.panLeft = function(x) { var div = this.map_.getDiv(); var left = div.clientWidth * x; this.map_.panBy(left, 0); }; IoMap.prototype['panLeft'] = IoMap.prototype.panLeft; /** * Adds the level switcher to the top left of the map. * * @private */ IoMap.prototype.addLevelControl_ = function() { var control = new LevelControl(this, this.LEVELS_).getElement(); this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control); }; /** * Shows a floor based on the content of location.hash. * * @private */ IoMap.prototype.parseHash_ = function() { var hash = document.location.hash; if (hash == this.prevHash_) { return; } this.prevHash_ = hash; var level = 1; if (hash) { var match = hash.match(/level(\d)(?:\:([\w-]+))?/); if (match && match[1]) { level = parseInt(match[1], 10); } } this.showLevel(level, true); }; /** * Updates location.hash based on the currently shown floor. * * @param {string?} opt_hash */ IoMap.prototype.setHash = function(opt_hash) { var hash = document.location.hash.substring(1); if (hash == opt_hash) { return; } if (opt_hash) { document.location.hash = opt_hash; } else { document.location.hash = 'level' + this.get('level'); } }; IoMap.prototype['setHash'] = IoMap.prototype.setHash; /** * Called from spreadsheets. */ IoMap.prototype.loadSandboxCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.companyName = entry['gsx$companyname']['$t']; item.companyUrl = entry['gsx$companyurl']['$t']; var p = entry['gsx$companypod']['$t']; item.pod = p; p = p.toLowerCase().replace(/\s+/, ''); item.sessionRoom = p; contentItems.push(item); }; this.sandboxItems_ = contentItems; this.ready_ = true; this.addMapContent_(); }; /** * Called from spreadsheets. * * @param {Object} json The json feed from the spreadsheet. */ IoMap.prototype.loadSessionsCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.sessionDate = entry['gsx$sessiondate']['$t']; item.sessionAbstract = entry['gsx$sessionabstract']['$t']; item.sessionHashtag = entry['gsx$sessionhashtag']['$t']; item.sessionLevel = entry['gsx$sessionlevel']['$t']; item.sessionTitle = entry['gsx$sessiontitle']['$t']; item.sessionTrack = entry['gsx$sessiontrack']['$t']; item.sessionUrl = entry['gsx$sessionurl']['$t']; item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t']; item.sessionTime = entry['gsx$sessiontime']['$t']; item.sessionRoom = entry['gsx$sessionroom']['$t']; item.sessionTags = entry['gsx$sessiontags']['$t']; item.sessionSpeakers = entry['gsx$sessionspeakers']['$t']; if (item.sessionDate.indexOf('10') != -1) { item.sessionDay = 10; } else { item.sessionDay = 11; } var timeParts = item.sessionTime.split('-'); item.sessionStart = this.convertTo24Hour_(timeParts[0]); item.sessionEnd = this.convertTo24Hour_(timeParts[1]); contentItems.push(item); } this.sessionItems_ = contentItems; }; /** * Converts the time in the spread sheet to 24 hour time. * * @param {string} time The time like 10:42am. */ IoMap.prototype.convertTo24Hour_ = function(time) { var pm = time.indexOf('pm') != -1; time = time.replace(/[am|pm]/ig, ''); if (pm) { var bits = time.split(':'); var hr = parseInt(bits[0], 10); if (hr < 12) { time = (hr + 12) + ':' + bits[1]; } } return time; }; /** * Loads the map content from Google Spreadsheets. * * @private */ IoMap.prototype.loadMapContent_ = function() { // Initiate a JSONP request. var that = this; // Add a exposed call back function window['loadSessionsCallback'] = function(json) { that.loadSessionsCallback(json); } // Add a exposed call back function window['loadSandboxCallback'] = function(json) { that.loadSandboxCallback(json); } var key = 'tmaLiaNqIWYYtuuhmIyG0uQ'; var worksheetIDs = { sessions: 'od6', sandbox: 'od4' }; var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sessions + '/public/values' + '?alt=json-in-script&callback=loadSessionsCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sandbox + '/public/values' + '?alt=json-in-script&callback=loadSandboxCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); }; /** * Called from Android. * * @param {string} roomId The id of the room to load. */ IoMap.prototype.showLocationById = function(roomId) { var locations = this.LOCATIONS_; for (var level in locations) { var levelId = level.replace('LEVEL', ''); for (var loc in locations[level]) { var room = locations[level][loc]; if (loc == roomId) { var pos = new google.maps.LatLng(room.lat, room.lng); this.map_.panTo(pos); this.map_.setZoom(19); this.showLevel(levelId); if (room.marker_) { room.marker_.setAnimation(google.maps.Animation.BOUNCE); // Disable the animation after 5 seconds. window.setTimeout(function() { room.marker_.setAnimation(); }, 5000); } return; } } } }; IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById; /** * Called when the level is changed. Hides and shows floors. */ IoMap.prototype['level_changed'] = function() { var level = this.get('level'); if (this.infoWindow_) { this.infoWindow_.setMap(null); } for (var i = 1, floor; floor = this.floors_[i - 1]; i++) { if (i == level) { floor.show(); } else { floor.hide(); } } this.setHash('level' + level); }; /** * Shows a particular floor. * * @param {string} level The level to show. * @param {boolean=} opt_force if true, changes the floor even if it's already * the current floor. */ IoMap.prototype.showLevel = function(level, opt_force) { if (!opt_force && level == this.get('level')) { return; } this.set('level', level); }; IoMap.prototype['showLevel'] = IoMap.prototype.showLevel; /** * Create a marker with the content item's correct icon. * * @param {Object} item The content item for the marker. * @return {google.maps.Marker} The new marker. * @private */ IoMap.prototype.createContentMarker_ = function(item) { if (!item.icon) { item.icon = 'generic'; } var image; var shadow; switch(item.icon) { case 'generic': case 'info': case 'media': var image = new google.maps.MarkerImage( 'marker-' + item.icon + '.png', new google.maps.Size(30, 28), new google.maps.Point(0, 0), new google.maps.Point(13, 26)); var shadow = new google.maps.MarkerImage( 'marker-shadow.png', new google.maps.Size(30, 28), new google.maps.Point(0,0), new google.maps.Point(13, 26)); break; case 'toilets': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(35, 35), new google.maps.Point(0, 0), new google.maps.Point(17, 17)); break; case 'elevator': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(48, 26), new google.maps.Point(0, 0), new google.maps.Point(24, 13)); break; } var inactive = item.type == 'inactive'; var latLng = new google.maps.LatLng(item.lat, item.lng); var marker = new SmartMarker({ position: latLng, shadow: shadow, icon: image, title: item.title, minZoom: inactive ? 19 : 18, clickable: !inactive }); marker['type_'] = item.type; if (!inactive) { var that = this; google.maps.event.addListener(marker, 'click', function() { that.openContentInfo_(item); }); } return marker; }; /** * Create a label with the content item's title atribute, if it exists. * * @param {Object} item The content item for the marker. * @return {MapLabel?} The new label. * @private */ IoMap.prototype.createContentLabel_ = function(item) { if (!item.title || item.suppressLabel) { return null; } var latLng = new google.maps.LatLng(item.lat, item.lng); return new MapLabel({ 'text': item.title, 'position': latLng, 'minZoom': item.labelMinZoom || 18, 'align': item.labelAlign || 'center', 'fontColor': item.labelColor, 'fontSize': item.labelSize || 12 }); } /** * Open a info window a content item. * * @param {Object} item A content item with content and a marker. */ IoMap.prototype.openContentInfo_ = function(item) { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['openContentInfo'](item.room); return; } var sessionBase = 'http://www.google.com/events/io/2011/sessions.html'; var now = new Date(); var may11 = new Date('May 11, 2011'); var day = now < may11 ? 10 : 11; var type = item.type; var id = item.id; var title = item.title; var content = ['<div class="infowindow">']; var sessions = []; var empty = true; if (item.type == 'session') { if (day == 10) { content.push('<h3>' + title + ' - Tuesday May 10</h3>'); } else { content.push('<h3>' + title + ' - Wednesday May 11</h3>'); } for (var i = 0, session; session = this.sessionItems_[i]; i++) { if (session.sessionRoom == item.room && session.sessionDay == day) { sessions.push(session); empty = false; } } sessions.sort(this.sortSessions_); for (var i = 0, session; session = sessions[i]; i++) { content.push('<div class="session"><div class="session-time">' + session.sessionTime + '</div><div class="session-title"><a href="' + session.sessionUrl + '">' + session.sessionTitle + '</a></div></div>'); } } if (item.type == 'sandbox') { var sandboxName; for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) { if (sandbox.sessionRoom == item.room) { if (!sandboxName) { sandboxName = sandbox.pod; content.push('<h3>' + sandbox.pod + '</h3>'); content.push('<div class="sandbox">'); } content.push('<div class="sandbox-items"><a href="http://' + sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>'); empty = false; } } content.push('</div>'); empty = false; } if (empty) { return; } content.push('</div>'); var pos = new google.maps.LatLng(item.lat, item.lng); if (!this.infoWindow_) { this.infoWindow_ = new google.maps.InfoWindow(); } this.infoWindow_.setContent(content.join('')); this.infoWindow_.setPosition(pos); this.infoWindow_.open(this.map_); }; /** * A custom sort function to sort the sessions by start time. * * @param {string} a SessionA<enter description here>. * @param {string} b SessionB. * @return {boolean} True if sessionA is after sessionB. */ IoMap.prototype.sortSessions_ = function(a, b) { var aStart = parseInt(a.sessionStart.replace(':', ''), 10); var bStart = parseInt(b.sessionStart.replace(':', ''), 10); return aStart > bStart; }; /** * Adds all overlays (markers, labels) to the map. */ IoMap.prototype.addMapContent_ = function() { if (!this.ready_) { return; } for (var i = 0, level; level = this.LEVELS_[i]; i++) { var floor = this.floors_[i]; var locations = this.LOCATIONS_['LEVEL' + level]; for (var roomId in locations) { var room = locations[roomId]; if (room.room == undefined) { room.room = roomId; } if (room.type != 'label') { var marker = this.createContentMarker_(room); floor.addOverlay(marker); room.marker_ = marker; } var label = this.createContentLabel_(room); floor.addOverlay(label); } } }; /** * Gets the correct tile url for the coordinates and zoom. * * @param {google.maps.Point} coord The coordinate of the tile. * @param {Number} zoom The current zoom level. * @return {string} The url to the tile. */ IoMap.prototype.getTileUrl = function(coord, zoom) { // Ensure that the requested resolution exists for this tile layer. if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) { return ''; } // Ensure that the requested tile x,y exists. if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x || coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) || (this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y || coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) { return ''; } var template = this.TILE_TEMPLATE_URL_; if (16 <= zoom && zoom <= 17) { template = this.SIMPLE_TILE_TEMPLATE_URL_; } return template .replace('{L}', /** @type string */(this.get('level'))) .replace('{Z}', /** @type string */(zoom)) .replace('{X}', /** @type string */(coord.x)) .replace('{Y}', /** @type string */(coord.y)); }; /** * Add the floor overlay to the map. * * @private */ IoMap.prototype.addMapOverlay_ = function() { var that = this; var overlay = new google.maps.ImageMapType({ getTileUrl: function(coord, zoom) { return that.getTileUrl(coord, zoom); }, tileSize: new google.maps.Size(256, 256) }); google.maps.event.addListener(this, 'level_changed', function() { var overlays = that.map_.overlayMapTypes; if (overlays.length) { overlays.removeAt(0); } overlays.push(overlay); }); }; /** * All the features of the map. * @type {Object.<string, Object.<string, Object.<string, *>>>} */ IoMap.prototype.LOCATIONS_ = { 'LEVEL1': { 'northentrance': { lat: 37.78381535905965, lng: -122.40362226963043, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'eastentrance': { lat: 37.78328434094279, lng: -122.40319311618805, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'lunchroom': { lat: 37.783112633669575, lng: -122.40407556295395, title: 'Lunch Room' }, 'restroom1a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator1a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'gearpickup': { lat: 37.78367863020862, lng: -122.4037617444992, title: 'Gear Pickup', type: 'label' }, 'checkin': { lat: 37.78334369645064, lng: -122.40335404872894, title: 'Check In', type: 'label' }, 'escalators1': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' } }, 'LEVEL2': { 'escalators2': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left', labelMinZoom: 19 }, 'press': { lat: 37.78316774962791, lng: -122.40360751748085, title: 'Press Room', type: 'label' }, 'restroom2a': { lat: 37.7835334217721, lng: -122.40386635065079, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom2b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator2a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, '1': { lat: 37.78346240732338, lng: -122.40415401756763, icon: 'media', title: 'Room 1', type: 'session', room: '1' }, '2': { lat: 37.78335005596647, lng: -122.40431495010853, icon: 'media', title: 'Room 2', type: 'session', room: '2' }, '3': { lat: 37.783215446097124, lng: -122.404490634799, icon: 'media', title: 'Room 3', type: 'session', room: '3' }, '4': { lat: 37.78332461789977, lng: -122.40381203591824, icon: 'media', title: 'Room 4', type: 'session', room: '4' }, '5': { lat: 37.783186828219335, lng: -122.4039850383997, icon: 'media', title: 'Room 5', type: 'session', room: '5' }, '6': { lat: 37.783013000871364, lng: -122.40420497953892, icon: 'media', title: 'Room 6', type: 'session', room: '6' }, '7': { lat: 37.7828783903882, lng: -122.40438133478165, icon: 'media', title: 'Room 7', type: 'session', room: '7' }, '8': { lat: 37.78305009820564, lng: -122.40378588438034, icon: 'media', title: 'Room 8', type: 'session', room: '8' }, '9': { lat: 37.78286673120095, lng: -122.40402393043041, icon: 'media', title: 'Room 9', type: 'session', room: '9' }, '10': { lat: 37.782719401312626, lng: -122.40420028567314, icon: 'media', title: 'Room 10', type: 'session', room: '10' }, 'appengine': { lat: 37.783362774996625, lng: -122.40335941314697, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'App Engine' }, 'chrome': { lat: 37.783730566003555, lng: -122.40378990769386, type: 'sandbox', icon: 'generic', title: 'Chrome' }, 'googleapps': { lat: 37.783303419504094, lng: -122.40320384502411, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Apps' }, 'geo': { lat: 37.783365954753805, lng: -122.40314483642578, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Geo' }, 'accessibility': { lat: 37.783414711013485, lng: -122.40342646837234, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Accessibility' }, 'developertools': { lat: 37.783457107734876, lng: -122.40347877144814, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Dev Tools' }, 'commerce': { lat: 37.78349102509448, lng: -122.40351900458336, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Commerce' }, 'youtube': { lat: 37.783537661438515, lng: -122.40358605980873, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'YouTube' }, 'officehoursfloor2a': { lat: 37.78249045644304, lng: -122.40410104393959, title: 'Office Hours', type: 'label' }, 'officehoursfloor2': { lat: 37.78266852473624, lng: -122.40387573838234, title: 'Office Hours', type: 'label' }, 'officehoursfloor2b': { lat: 37.782844472747406, lng: -122.40365579724312, title: 'Office Hours', type: 'label' } }, 'LEVEL3': { 'escalators3': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' }, 'restroom3a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom3b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator3a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'keynote': { lat: 37.783250423488326, lng: -122.40417748689651, icon: 'media', title: 'Keynote', type: 'label' }, '11': { lat: 37.78283069370135, lng: -122.40408763289452, icon: 'media', title: 'Room 11', type: 'session', room: '11' }, 'googletv': { lat: 37.7837125474666, lng: -122.40362092852592, type: 'sandbox', icon: 'generic', title: 'Google TV' }, 'android': { lat: 37.783530242022124, lng: -122.40358874201775, type: 'sandbox', icon: 'generic', title: 'Android' }, 'officehoursfloor3': { lat: 37.782843412820846, lng: -122.40365579724312, title: 'Office Hours', type: 'label' }, 'officehoursfloor3a': { lat: 37.78267170452323, lng: -122.40387842059135, title: 'Office Hours', type: 'label' } } }; google.maps.event.addDomListener(window, 'load', function() { window['IoMap'] = new IoMap(); });
JavaScript
/** * Creates a new Floor. * @constructor * @param {google.maps.Map=} opt_map */ function Floor(opt_map) { /** * @type Array.<google.maps.MVCObject> */ this.overlays_ = []; /** * @type boolean */ this.shown_ = true; if (opt_map) { this.setMap(opt_map); } } /** * @param {google.maps.Map} map */ Floor.prototype.setMap = function(map) { this.map_ = map; }; /** * @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel. * Requires a setMap method. */ Floor.prototype.addOverlay = function(overlay) { if (!overlay) return; this.overlays_.push(overlay); overlay.setMap(this.shown_ ? this.map_ : null); }; /** * Sets the map on all the overlays * @param {google.maps.Map} map The map to set. */ Floor.prototype.setMapAll_ = function(map) { this.shown_ = !!map; for (var i = 0, overlay; overlay = this.overlays_[i]; i++) { overlay.setMap(map); } }; /** * Hides the floor and all associated overlays. */ Floor.prototype.hide = function() { this.setMapAll_(null); }; /** * Shows the floor and all associated overlays. */ Floor.prototype.show = function() { this.setMapAll_(this.map_); };
JavaScript
/** * @license * * Copyright 2011 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. */ /** * @fileoverview SmartMarker. * * @author Chris Broadfoot (cbro@google.com) */ /** * A google.maps.Marker that has some smarts about the zoom levels it should be * shown. * * Options are the same as google.maps.Marker, with the addition of minZoom and * maxZoom. These zoom levels are inclusive. That is, a SmartMarker with * a minZoom and maxZoom of 13 will only be shown at zoom level 13. * @constructor * @extends google.maps.Marker * @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom. */ function SmartMarker(opts) { var marker = new google.maps.Marker; // default min/max Zoom - shows the marker all the time. marker.setValues({ 'minZoom': 0, 'maxZoom': Infinity }); // the current listener (if any), triggered on map zoom_changed var mapZoomListener; google.maps.event.addListener(marker, 'map_changed', function() { if (mapZoomListener) { google.maps.event.removeListener(mapZoomListener); } var map = marker.getMap(); if (map) { var listener = SmartMarker.newZoomListener_(marker); mapZoomListener = google.maps.event.addListener(map, 'zoom_changed', listener); // Call the listener straight away. The map may already be initialized, // so it will take user input for zoom_changed to be fired. listener(); } }); marker.setValues(opts); return marker; } window['SmartMarker'] = SmartMarker; /** * Creates a new listener to be triggered on 'zoom_changed' event. * Hides and shows the target Marker based on the map's zoom level. * @param {google.maps.Marker} marker The target marker. * @return Function */ SmartMarker.newZoomListener_ = function(marker) { var map = marker.getMap(); return function() { var zoom = map.getZoom(); var minZoom = Number(marker.get('minZoom')); var maxZoom = Number(marker.get('maxZoom')); marker.setVisible(zoom >= minZoom && zoom <= maxZoom); }; };
JavaScript
/* * Copyright (C) 2011 The Code Bakers * Authors: Gilmar Costa * e-mail: thecodebakers@gmail.com e gilmarcs@gmail.com * Project: https://code.google.com/p/open-source-android-blackjack/ * Site: http://thecodebakers.blogspot.com * * Licensed under the GNU GPL, Version 3.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://gplv3.fsf.org/ * * 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. * * @author Gilmar Costa - thecodebakers@gmail.com */ var Control = ( function( ) { const MOVE = 4, // até aqui não será feito nenhum tipo de avaliação no checkEnd. LENGTH = 3; var privates = { intMove : 0 }; return { reset: function( ) { privates.intMove = 0; }, checkMove: function( strMove ) { if (strMove === "") { privates.intMove++; return { bolValid: true, strMessage: "" }; } else { return { bolValid: false, strMessage: "Jogada Inválida!" }; } }, checkEnd: function( arrMoves ) { var i = 0, bolEnd = false; if ( privates.intMove > MOVE ) { // verificará horizontais e verticais for ( i = 0; i < LENGTH; i++ ) { if ( (arrMoves[i][0] !== "") && (arrMoves[i][0] === arrMoves[i][1] && arrMoves[i][2] === arrMoves[i][1]) || ( arrMoves[0][i] !== "") && (arrMoves[0][i] === arrMoves[1][i] && arrMoves[2][i] === arrMoves[1][i]) ) { bolEnd = true; } } // verificará diagonais if ( arrMoves[1][1] !== "" ) { if ( (arrMoves[0][0] === arrMoves[1][1] && arrMoves[2][2] === arrMoves[1][1]) || ( arrMoves[0][2] === arrMoves[1][1] && arrMoves[2][0] === arrMoves[1][1]) ) { bolEnd = true; } } if ( !bolEnd ) { if ( privates.intMove === 9 ) { return { bolEnd: true, strBy: "draw" }; } else if ( privates.intMove !== 9 ) { return { bolEnd: false, strBy: "" }; } } else { return { bolEnd: true, strBy: "player" }; } } return { bolEnd: false, strBy: "" }; } }; })( );
JavaScript
/* * Copyright (C) 2011 The Code Bakers * Authors: Gilmar Costa * e-mail: thecodebakers@gmail.com e gilmarcs@gmail.com * Project: https://code.google.com/p/open-source-android-blackjack/ * Site: http://thecodebakers.blogspot.com * * Licensed under the GNU GPL, Version 3.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://gplv3.fsf.org/ * * 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. * * @author Gilmar Costa - thecodebakers@gmail.com */ var Game = ( function( ) { var privates = { arrMoves: [ ], bolPlayer: true, // TRUE: indica o player 1 e FALSE: indica o player 2. //bolWin: false, bolPlaying: false, timeMove: null // armazenará o tempo restante de cada movimento, para exibição de mensagem. }; return { gameStart: function( ) { //console.log("gameStart"); Game.init(); Info.init(Strings.playerOne); Board.init(); }, endGame: function( objEnd ) { clearTimeout(privates.timeMove); navigator.notification.vibrate(1500); if (objEnd.strBy === "player") { if (Game.getPlayer()) { Info.update(Strings.gameEndOne); } else { Info.update(Strings.gameEndTwo); } Board.disable(false); } else if (objEnd.strBy === "draw") { Info.update(Strings.draw); Board.disable(false); } else if (objEnd.strBy === "finalize") { Info.update(Strings.finalize); Board.destroy(); } else if (objEnd.strBy === "over") { Info.update(Strings.over); } privates.bolPlaying = false; }, init: function( ) { //console.log("init"); privates.intMoves = 0; privates.arrMoves = [ ["", "", ""],["", "", ""],["","",""] ]; privates.bolPlayer = true; privates.bolPlaying = true; Control.reset(); //privates.bolWin = false; }, getMove: function(intCol, intRow) { return privates.arrMoves[ intCol ][ intRow ]; }, setMove: function(intCol, intRow, strPlay) { privates.arrMoves[ intCol ][ intRow ] = strPlay; }, updateMove: function( intCol, intRow ) { clearTimeout(privates.timeMove); var objValidate = Control.checkMove(Game.getMove(intCol, intRow)), strPlay = (Game.getPlayer()) ? "x" : "o", objEnd; if (objValidate.bolValid) { Board.setBoard(intCol, intRow, strPlay); Game.setMove(intCol, intRow, strPlay); objEnd = Control.checkEnd(privates.arrMoves); if ( objEnd.bolEnd ) { Game.endGame(objEnd); } else { Game.updatePlayer(); } } else { Info.update(objValidate.strMessage); } }, updatePlayer: function( ) { privates.timeMove = setTimeout(function(){ Info.adjust(Strings.wait); }, 8000); if( !Game.getPlayer() ) { Info.update(Strings.playerOne); } else { Info.update(Strings.playerTwo); } navigator.notification.vibrate(70); Game.setPlayer(Game.getPlayer()); }, getGameMoves: function( ) { return privates.arrMoves; }, getPlayer: function( ) { return privates.bolPlayer; }, setPlayer: function(bolPlayer) { privates.bolPlayer = ( !bolPlayer ); }, getPlaying: function( ) { return privates.bolPlaying; }, setPlaying: function(bolPlaying) { privates.bolPlaying = bolPlaying; } }; })( );
JavaScript
/* * Copyright (C) 2011 The Code Bakers * Authors: Gilmar Costa * e-mail: thecodebakers@gmail.com e gilmarcs@gmail.com * Project: https://code.google.com/p/open-source-android-blackjack/ * Site: http://thecodebakers.blogspot.com * * Licensed under the GNU GPL, Version 3.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://gplv3.fsf.org/ * * 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. * * @author Gilmar Costa - thecodebakers@gmail.com */ var Menu = ( function( ) { var privates = { enable: function(arrEnable){ var length = arrEnable.length; for (var i = 0; i < length; i++) { View.getViewMenu().listen(arrEnable[i]); } }, disable: function(arrDisable) { var length = arrDisable.length; for (var i = 0; i < length; i++) { View.getViewMenu().unlisten(arrDisable[i]); } } }; return { start: function() { privates.enable(["start"]); }, restart: function() { privates.enable(["restart"]); privates.disable(["end"]); }, startGame: function() { //console.log("startGame"); privates.disable(["start"]); privates.enable(["restart", "end"]); //Board.disable(true); Game.gameStart(); //game.startGame(); //info.start(); //return true; }, restartGame: function() { privates.disable(["start"]); //privates.enable(["end"]); Game.gameStart(); //return true; //board.disable(true); //game.startGame(); //info.start(); }, endGame: function() { privates.disable(["restart", "end"]); privates.enable(["start"]); if (Game.getPlaying()){ Game.endGame({strBy: "finalize"}); } else { Game.endGame({strBy: "over"}); } //board.disable(false); //game.finalize(); //info.update(strings.finalize); } }; })( );
JavaScript
/* * Copyright (C) 2011 The Code Bakers * Authors: Gilmar Costa * e-mail: thecodebakers@gmail.com e gilmarcs@gmail.com * Project: https://code.google.com/p/open-source-android-blackjack/ * Site: http://thecodebakers.blogspot.com * * Licensed under the GNU GPL, Version 3.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://gplv3.fsf.org/ * * 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. * * @author Gilmar Costa - thecodebakers@gmail.com */ var Info = ( function( ) { return { init: function(strUpdate) { View.getViewInfo().clean(); if (strUpdate !== null) { Info.update(strUpdate); } else { Info.update(""); } }, update: function(strUpdate){ View.getViewInfo().clean(); View.getViewInfo().adjust(strUpdate); }, adjust: function(strUpdate) { View.getViewInfo().adjust(strUpdate); } }; })( );
JavaScript
/* * Copyright (C) 2011 The Code Bakers * Authors: Gilmar Costa * e-mail: thecodebakers@gmail.com e gilmarcs@gmail.com * Project: https://code.google.com/p/open-source-android-blackjack/ * Site: http://thecodebakers.blogspot.com * * Licensed under the GNU GPL, Version 3.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://gplv3.fsf.org/ * * 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. * * @author Gilmar Costa - thecodebakers@gmail.com */ var Board = ( function( ){ const LENGTH = 3; var privates = { arrBoard: [ ], startBoard: function( ) { privates.arrBoard = [ [document.getElementById("top1"), document.getElementById("top2"), document.getElementById("top3")], [document.getElementById("center1"), document.getElementById("center2"), document.getElementById("center3")], [document.getElementById("bottom1"), document.getElementById("bottom2"), document.getElementById("bottom3")] ]; }, finalizeBoard: function( ) { privates.arrBoard = [ ]; }, shot: function( intI, intJ ) { //alert("clicou" + intI + intJ ); /*var strValue = Board.getArrBoard(intI, intJ); Control.checkMove(strValue);*/ Game.updateMove(intI, intJ); } }; return { init: function( ) { //console.log("Board.init"); privates.startBoard(); Board.disable(true) Board.enable(); Board.show(); }, destroy: function( ) { View.getViewBoard().hide(); Board.disable(); //privates.finalizeBoard(); }, enable: function( ){ for (var i = 0; i < LENGTH; i++) { // 3 linhas for (var j = 0; j < LENGTH; j++) { // 3 colunas // realiza (habilita a escuta) dos elementos do tabuleiro View.getViewBoard().listen(privates.arrBoard[i][j], "click", privates.shot, i, j); } } }, disable: function( bolClean ) { for ( var i = 0; i < LENGTH; i++ ) { for ( var j = 0; j < LENGTH; j++ ) { View.getViewBoard().unlisten(privates.arrBoard[i][j]); if ( bolClean ) { // limpa células View.getViewBoard().cleanCell(privates.arrBoard[i][j]); } } } }, getArrBoard: function( intI, intJ ) { return privates.arrBoard[intI][intJ]; }, setBoard: function(intI, intJ, strValue) { View.getViewBoard().markCell(privates.arrBoard[intI][intJ], strValue); }, enableCell: function(intCol, intRow) { View.getViewBoard().listen(privates.arrBoard[intCol][intRow], "click", privates.shot, intCol, intRow); }, disableCell: function(intCol, intRow) { View.getViewBoard().unlisten(arrBoard[intCol][intRow]); }, hide: function( ) { View.getViewBoard().hide(); }, show: function( ) { View.getViewBoard().show(); } }; })();
JavaScript
/* * Copyright (C) 2011 The Code Bakers * Authors: Gilmar Costa * e-mail: thecodebakers@gmail.com e gilmarcs@gmail.com * Project: https://code.google.com/p/open-source-android-blackjack/ * Site: http://thecodebakers.blogspot.com * * Licensed under the GNU GPL, Version 3.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://gplv3.fsf.org/ * * 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. * * @author Gilmar Costa - thecodebakers@gmail.com */ var View = ( function( ) { return { getViewBoard: function( ) { return { listen: function(objElement, strEvent, objFunctionCall, intCol, intRow){ $( objElement ).bind( strEvent, function( ){ objFunctionCall( intCol, intRow ); }); }, unlisten: function(objElement){ $( objElement ).unbind(); }, markCell: function(objCell, strValue){ objCell.className += " " + strValue; }, unmarkCell: function(objCell, strValue){ $(objCell).removeClass(strValue); }, cleanCell: function(objCell){ $(objCell).removeClass("x"); $(objCell).removeClass("o"); }, hide: function(){ document.getElementById("board").style.display = "none"; }, show: function(){ document.getElementById("board").style.display = "block"; } }; }, getViewInfo: function( ) { return { adjust: function(strUpdate) { document.getElementById("info").innerHTML += strUpdate; }, clean: function() { document.getElementById("info").innerHTML = ""; } }; }, getViewMenu: function( ) { return { listen: function(strButtom) { // rever funcção que chamará if ( strButtom === null ) { // habilitará todos $(document.getElementById("start")).bind("click", function(){ Menu.startGame(); }).addClass("select"); $(document.getElementById("restart")).bind("click", function(){ Menu.restartGame(); }).addClass("select"); $(document.getElementById("end")).bind("click", function(){ Menu.endGame(); }).addClass("select"); } else if ( strButtom === "start" ) { // habilitará start $(document.getElementById("start")).bind("click", function(){ Menu.startGame(); }).addClass("select"); } else if ( strButtom === "restart" ) { // habilitará restart $(document.getElementById("restart")).bind("click", function(){ Menu.restartGame(); }).addClass("select"); } else if ( strButtom === "end" ) { // habilitará end $(document.getElementById("end")).bind("click", function(){ Menu.endGame(); }).addClass("select"); } }, unlisten: function(strButtom) { if ( strButtom === null ) { // desabilitará todos $(document.getElementById("start")).unbind().removeClass("select"); $(document.getElementById("restart")).unbind().removeClass("select"); $(document.getElementById("end")).unbind().removeClass("select"); } else if ( strButtom === "start" ) { // desabilitará start $(document.getElementById("start")).unbind().removeClass("select"); } else if ( strButtom === "restart" ) { // desabilitará restart $(document.getElementById("restart")).unbind().removeClass("select"); } else if ( strButtom === "end" ) { // desabilitará end $(document.getElementById("end")).unbind().removeClass("select"); } }, updateStart: function() { } }; } }; })();
JavaScript
/* * Copyright (C) 2011 The Code Bakers * Authors: Gilmar Costa * e-mail: thecodebakers@gmail.com e gilmarcs@gmail.com * Project: https://code.google.com/p/open-source-android-blackjack/ * Site: http://thecodebakers.blogspot.com * * Licensed under the GNU GPL, Version 3.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://gplv3.fsf.org/ * * 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. * * @author Gilmar Costa - thecodebakers@gmail.com */ var Strings = { playerOne: 'Jogador 1 &eacute; a sua vez. Seu s&iacute;mbolo &eacute; o "X"!', playerTwo: 'Jogador 2 &eacute; a sua vez. Seu s&iacute;mbolo &eacute; o "O"!', finalize: 'Jogo encerrado, sem vencedor...\nClique no bot&atilde;o Iniciar para um novo jogo!', gameEndOne: 'Fim de Jogo!! Parab&eacute;ns Jogador 1, voc&ecirc; &eacute o vencedor!!', gameEndTwo: 'Fim de Jogo!! Parab&eacute;ns Jogador 2, voc&ecirc; &eacute o vencedor!!', draw: 'Empate!!', invalidMove: 'Jogada Inv&aacute;lida', over: 'O jogo j&aacute; terminou, clique em Iniciar para um novo jogo.', wait: ' Voc&ecirc; est&aacute; demorando para jogar...' };
JavaScript
/* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * The order of events during page load and PhoneGap startup is as follows: * * onDOMContentLoaded Internal event that is received when the web page is loaded and parsed. * window.onload Body onload event. * onNativeReady Internal event that indicates the PhoneGap native side is ready. * onPhoneGapInit Internal event that kicks off creation of all PhoneGap JavaScript objects (runs constructors). * onPhoneGapReady Internal event fired when all PhoneGap JavaScript objects have been created * onPhoneGapInfoReady Internal event fired when device properties are available * onDeviceReady User event fired to indicate that PhoneGap is ready * onResume User event fired to indicate a start/resume lifecycle event * * The only PhoneGap events that user code should register for are: * onDeviceReady * onResume * * Listeners can be registered as: * document.addEventListener("deviceready", myDeviceReadyListener, false); * document.addEventListener("resume", myResumeListener, false); */ if (typeof(DeviceInfo) != 'object') DeviceInfo = {}; /** * This represents the PhoneGap API itself, and provides a global namespace for accessing * information about the state of PhoneGap. * @class */ var PhoneGap = { queue: { ready: true, commands: [], timer: null } }; /** * Custom pub-sub channel that can have functions subscribed to it */ PhoneGap.Channel = function(type) { this.type = type; this.handlers = {}; this.guid = 0; this.fired = false; this.enabled = true; }; /** * Subscribes the given function to the channel. Any time that * Channel.fire is called so too will the function. * Optionally specify an execution context for the function * and a guid that can be used to stop subscribing to the channel. * Returns the guid. */ PhoneGap.Channel.prototype.subscribe = function(f, c, g) { // need a function to call if (f == null) { return; } var func = f; if (typeof c == "object" && f instanceof Function) { func = PhoneGap.close(c, f); } g = g || func.observer_guid || f.observer_guid || this.guid++; func.observer_guid = g; f.observer_guid = g; this.handlers[g] = func; return g; }; /** * Like subscribe but the function is only called once and then it * auto-unsubscribes itself. */ PhoneGap.Channel.prototype.subscribeOnce = function(f, c) { var g = null; var _this = this; var m = function() { f.apply(c || null, arguments); _this.unsubscribe(g); } if (this.fired) { if (typeof c == "object" && f instanceof Function) { f = PhoneGap.close(c, f); } f.apply(this, this.fireArgs); } else { g = this.subscribe(m); } return g; }; /** * Unsubscribes the function with the given guid from the channel. */ PhoneGap.Channel.prototype.unsubscribe = function(g) { if (g instanceof Function) { g = g.observer_guid; } this.handlers[g] = null; delete this.handlers[g]; }; /** * Calls all functions subscribed to this channel. */ PhoneGap.Channel.prototype.fire = function(e) { if (this.enabled) { var fail = false; for (var item in this.handlers) { var handler = this.handlers[item]; if (handler instanceof Function) { var rv = (handler.apply(this, arguments)==false); fail = fail || rv; } } this.fired = true; this.fireArgs = arguments; return !fail; } return true; }; /** * Calls the provided function only after all of the channels specified * have been fired. */ PhoneGap.Channel.join = function(h, c) { var i = c.length; var f = function() { if (!(--i)) h(); } var len = i; for (var j=0; j<len; j++) { if (!c[j].fired) { c[j].subscribeOnce(f); } else { i--; } } if (!i) h(); }; /** * Boolean flag indicating if the PhoneGap API is available and initialized. */ // TODO: Remove this, it is unused here ... -jm PhoneGap.available = DeviceInfo.uuid != undefined; /** * Add an initialization function to a queue that ensures it will run and initialize * application constructors only once PhoneGap has been initialized. * @param {Function} func The function callback you want run once PhoneGap is initialized */ PhoneGap.addConstructor = function(func) { PhoneGap.onPhoneGapInit.subscribeOnce(function() { try { func(); } catch(e) { console.log("Failed to run constructor: " + e); } }); }; /** * Plugins object */ if (!window.plugins) { window.plugins = {}; } /** * Adds a plugin object to window.plugins. * The plugin is accessed using window.plugins.<name> * * @param name The plugin name * @param obj The plugin object */ PhoneGap.addPlugin = function(name, obj) { if (!window.plugins[name]) { window.plugins[name] = obj; } else { console.log("Error: Plugin "+name+" already exists."); } } /** * onDOMContentLoaded channel is fired when the DOM content * of the page has been parsed. */ PhoneGap.onDOMContentLoaded = new PhoneGap.Channel('onDOMContentLoaded'); /** * onNativeReady channel is fired when the PhoneGap native code * has been initialized. */ PhoneGap.onNativeReady = new PhoneGap.Channel('onNativeReady'); /** * onPhoneGapInit channel is fired when the web page is fully loaded and * PhoneGap native code has been initialized. */ PhoneGap.onPhoneGapInit = new PhoneGap.Channel('onPhoneGapInit'); /** * onPhoneGapReady channel is fired when the JS PhoneGap objects have been created. */ PhoneGap.onPhoneGapReady = new PhoneGap.Channel('onPhoneGapReady'); /** * onPhoneGapInfoReady channel is fired when the PhoneGap device properties * has been set. */ PhoneGap.onPhoneGapInfoReady = new PhoneGap.Channel('onPhoneGapInfoReady'); /** * onResume channel is fired when the PhoneGap native code * resumes. */ PhoneGap.onResume = new PhoneGap.Channel('onResume'); /** * onPause channel is fired when the PhoneGap native code * pauses. */ PhoneGap.onPause = new PhoneGap.Channel('onPause'); // _nativeReady is global variable that the native side can set // to signify that the native code is ready. It is a global since // it may be called before any PhoneGap JS is ready. if (typeof _nativeReady !== 'undefined') { PhoneGap.onNativeReady.fire(); } /** * onDeviceReady is fired only after all PhoneGap objects are created and * the device properties are set. */ PhoneGap.onDeviceReady = new PhoneGap.Channel('onDeviceReady'); // Array of channels that must fire before "deviceready" is fired PhoneGap.deviceReadyChannelsArray = [ PhoneGap.onPhoneGapReady, PhoneGap.onPhoneGapInfoReady]; // Hashtable of user defined channels that must also fire before "deviceready" is fired PhoneGap.deviceReadyChannelsMap = {}; /** * Indicate that a feature needs to be initialized before it is ready to be used. * This holds up PhoneGap's "deviceready" event until the feature has been initialized * and PhoneGap.initComplete(feature) is called. * * @param feature {String} The unique feature name */ PhoneGap.waitForInitialization = function(feature) { if (feature) { var channel = new PhoneGap.Channel(feature); PhoneGap.deviceReadyChannelsMap[feature] = channel; PhoneGap.deviceReadyChannelsArray.push(channel); } }; /** * Indicate that initialization code has completed and the feature is ready to be used. * * @param feature {String} The unique feature name */ PhoneGap.initializationComplete = function(feature) { var channel = PhoneGap.deviceReadyChannelsMap[feature]; if (channel) { channel.fire(); } }; /** * Create all PhoneGap objects once page has fully loaded and native side is ready. */ PhoneGap.Channel.join(function() { // Start listening for XHR callbacks setTimeout(function() { if (CallbackServer.usePolling()) { PhoneGap.JSCallbackPolling(); } else { PhoneGap.JSCallback(); } }, 1); // Run PhoneGap constructors PhoneGap.onPhoneGapInit.fire(); // Fire event to notify that all objects are created PhoneGap.onPhoneGapReady.fire(); PhoneGap.Channel.join(function() { // Turn off app loading dialog navigator.notification.activityStop(); PhoneGap.onDeviceReady.fire(); // Fire the onresume event, since first one happens before JavaScript is loaded PhoneGap.onResume.fire(); }, PhoneGap.deviceReadyChannelsArray); }, [ PhoneGap.onDOMContentLoaded, PhoneGap.onNativeReady ]); /** * Fire onDeviceReady event once all constructors have run and PhoneGap info has been * received from native side. */ /* PhoneGap.Channel.join(function() { // Turn off app loading dialog navigator.notification.activityStop(); PhoneGap.onDeviceReady.fire(); // Fire the onresume event, since first one happens before JavaScript is loaded PhoneGap.onResume.fire(); }, [ PhoneGap.onPhoneGapReady, PhoneGap.onPhoneGapInfoReady]); */ // Listen for DOMContentLoaded and notify our channel subscribers document.addEventListener('DOMContentLoaded', function() { PhoneGap.onDOMContentLoaded.fire(); }, false); // Intercept calls to document.addEventListener and watch for deviceready PhoneGap.m_document_addEventListener = document.addEventListener; document.addEventListener = function(evt, handler, capture) { var e = evt.toLowerCase(); if (e == 'deviceready') { PhoneGap.onDeviceReady.subscribeOnce(handler); } else if (e == 'resume') { PhoneGap.onResume.subscribe(handler); if (PhoneGap.onDeviceReady.fired) { PhoneGap.onResume.fire(); } } else if (e == 'pause') { PhoneGap.onPause.subscribe(handler); } else { PhoneGap.m_document_addEventListener.call(document, evt, handler, capture); } }; /** * If JSON not included, use our own stringify. (Android 1.6) * The restriction on ours is that it must be an array of simple types. * * @param args * @return */ PhoneGap.stringify = function(args) { if (typeof JSON == "undefined") { var s = "["; for (var i=0; i<args.length; i++) { if (i > 0) { s = s + ","; } var type = typeof args[i]; if ((type == "number") || (type == "boolean")) { s = s + args[i]; } else if (args[i] instanceof Array) { s = s + "[" + args[i] + "]"; } else if (args[i] instanceof Object) { var start = true; s = s + '{'; for (var name in args[i]) { if (args[i][name] != null) { if (!start) { s = s + ','; } s = s + '"' + name + '":'; var nameType = typeof args[i][name]; if ((nameType == "number") || (nameType == "boolean")) { s = s + args[i][name]; } else if ((typeof args[i][name]) == 'function') { // don't copy the functions s = s + '""'; } else if (args[i][name] instanceof Object) { s = s + this.stringify(args[i][name]); } else { s = s + '"' + args[i][name] + '"'; } start=false; } } s = s + '}'; } else { var a = args[i].replace(/\\/g, '\\\\'); a = a.replace(/"/g, '\\"'); s = s + '"' + a + '"'; } } s = s + "]"; return s; } else { return JSON.stringify(args); } }; /** * Does a deep clone of the object. * * @param obj * @return */ PhoneGap.clone = function(obj) { if(!obj) { return obj; } if(obj instanceof Array){ var retVal = new Array(); for(var i = 0; i < obj.length; ++i){ retVal.push(PhoneGap.clone(obj[i])); } return retVal; } if (obj instanceof Function) { return obj; } if(!(obj instanceof Object)){ return obj; } if (obj instanceof Date) { return obj; } retVal = new Object(); for(i in obj){ if(!(i in retVal) || retVal[i] != obj[i]) { retVal[i] = PhoneGap.clone(obj[i]); } } return retVal; }; PhoneGap.callbackId = 0; PhoneGap.callbacks = {}; PhoneGap.callbackStatus = { NO_RESULT: 0, OK: 1, CLASS_NOT_FOUND_EXCEPTION: 2, ILLEGAL_ACCESS_EXCEPTION: 3, INSTANTIATION_EXCEPTION: 4, MALFORMED_URL_EXCEPTION: 5, IO_EXCEPTION: 6, INVALID_ACTION: 7, JSON_EXCEPTION: 8, ERROR: 9 }; /** * Execute a PhoneGap command. It is up to the native side whether this action is synch or async. * The native side can return: * Synchronous: PluginResult object as a JSON string * Asynchrounous: Empty string "" * If async, the native side will PhoneGap.callbackSuccess or PhoneGap.callbackError, * depending upon the result of the action. * * @param {Function} success The success callback * @param {Function} fail The fail callback * @param {String} service The name of the service to use * @param {String} action Action to be run in PhoneGap * @param {String[]} [args] Zero or more arguments to pass to the method */ PhoneGap.exec = function(success, fail, service, action, args) { try { var callbackId = service + PhoneGap.callbackId++; if (success || fail) { PhoneGap.callbacks[callbackId] = {success:success, fail:fail}; } // Note: Device returns string, but for some reason emulator returns object - so convert to string. var r = ""+PluginManager.exec(service, action, callbackId, this.stringify(args), true); // If a result was returned if (r.length > 0) { eval("var v="+r+";"); // If status is OK, then return value back to caller if (v.status == PhoneGap.callbackStatus.OK) { // If there is a success callback, then call it now with returned value if (success) { try { success(v.message); } catch (e) { console.log("Error in success callback: "+callbackId+" = "+e); } // Clear callback if not expecting any more results if (!v.keepCallback) { delete PhoneGap.callbacks[callbackId]; } } return v.message; } // If no result else if (v.status == PhoneGap.callbackStatus.NO_RESULT) { // Clear callback if not expecting any more results if (!v.keepCallback) { delete PhoneGap.callbacks[callbackId]; } } // If error, then display error else { console.log("Error: Status="+r.status+" Message="+v.message); // If there is a fail callback, then call it now with returned value if (fail) { try { fail(v.message); } catch (e) { console.log("Error in error callback: "+callbackId+" = "+e); } // Clear callback if not expecting any more results if (!v.keepCallback) { delete PhoneGap.callbacks[callbackId]; } } return null; } } } catch (e) { console.log("Error: "+e); } }; /** * Called by native code when returning successful result from an action. * * @param callbackId * @param args */ PhoneGap.callbackSuccess = function(callbackId, args) { if (PhoneGap.callbacks[callbackId]) { // If result is to be sent to callback if (args.status == PhoneGap.callbackStatus.OK) { try { if (PhoneGap.callbacks[callbackId].success) { PhoneGap.callbacks[callbackId].success(args.message); } } catch (e) { console.log("Error in success callback: "+callbackId+" = "+e); } } // Clear callback if not expecting any more results if (!args.keepCallback) { delete PhoneGap.callbacks[callbackId]; } } }; /** * Called by native code when returning error result from an action. * * @param callbackId * @param args */ PhoneGap.callbackError = function(callbackId, args) { if (PhoneGap.callbacks[callbackId]) { try { if (PhoneGap.callbacks[callbackId].fail) { PhoneGap.callbacks[callbackId].fail(args.message); } } catch (e) { console.log("Error in error callback: "+callbackId+" = "+e); } // Clear callback if not expecting any more results if (!args.keepCallback) { delete PhoneGap.callbacks[callbackId]; } } }; /** * Internal function used to dispatch the request to PhoneGap. It processes the * command queue and executes the next command on the list. If one of the * arguments is a JavaScript object, it will be passed on the QueryString of the * url, which will be turned into a dictionary on the other end. * @private */ // TODO: Is this used? PhoneGap.run_command = function() { if (!PhoneGap.available || !PhoneGap.queue.ready) return; PhoneGap.queue.ready = false; var args = PhoneGap.queue.commands.shift(); if (PhoneGap.queue.commands.length == 0) { clearInterval(PhoneGap.queue.timer); PhoneGap.queue.timer = null; } var uri = []; var dict = null; for (var i = 1; i < args.length; i++) { var arg = args[i]; if (arg == undefined || arg == null) arg = ''; if (typeof(arg) == 'object') dict = arg; else uri.push(encodeURIComponent(arg)); } var url = "gap://" + args[0] + "/" + uri.join("/"); if (dict != null) { var query_args = []; for (var name in dict) { if (typeof(name) != 'string') continue; query_args.push(encodeURIComponent(name) + "=" + encodeURIComponent(dict[name])); } if (query_args.length > 0) url += "?" + query_args.join("&"); } document.location = url; }; PhoneGap.JSCallbackPort = null; PhoneGap.JSCallbackToken = null; /** * This is only for Android. * * Internal function that uses XHR to call into PhoneGap Java code and retrieve * any JavaScript code that needs to be run. This is used for callbacks from * Java to JavaScript. */ PhoneGap.JSCallback = function() { var xmlhttp = new XMLHttpRequest(); // Callback function when XMLHttpRequest is ready xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState == 4){ // If callback has JavaScript statement to execute if (xmlhttp.status == 200) { var msg = xmlhttp.responseText; setTimeout(function() { try { var t = eval(msg); } catch (e) { // If we're getting an error here, seeing the message will help in debugging console.log("JSCallback: Message from Server: " + msg); console.log("JSCallback Error: "+e); } }, 1); setTimeout(PhoneGap.JSCallback, 1); } // If callback ping (used to keep XHR request from timing out) else if (xmlhttp.status == 404) { setTimeout(PhoneGap.JSCallback, 10); } // If security error else if (xmlhttp.status == 403) { console.log("JSCallback Error: Invalid token. Stopping callbacks."); } // If server is stopping else if (xmlhttp.status == 503) { console.log("JSCallback Error: Service unavailable. Stopping callbacks."); } // If request wasn't GET else if (xmlhttp.status == 400) { console.log("JSCallback Error: Bad request. Stopping callbacks."); } // If error, restart callback server else { console.log("JSCallback Error: Request failed."); CallbackServer.restartServer(); PhoneGap.JSCallbackPort = null; PhoneGap.JSCallbackToken = null; setTimeout(PhoneGap.JSCallback, 100); } } } if (PhoneGap.JSCallbackPort == null) { PhoneGap.JSCallbackPort = CallbackServer.getPort(); } if (PhoneGap.JSCallbackToken == null) { PhoneGap.JSCallbackToken = CallbackServer.getToken(); } xmlhttp.open("GET", "http://127.0.0.1:"+PhoneGap.JSCallbackPort+"/"+PhoneGap.JSCallbackToken , true); xmlhttp.send(); }; /** * The polling period to use with JSCallbackPolling. * This can be changed by the application. The default is 50ms. */ PhoneGap.JSCallbackPollingPeriod = 50; /** * This is only for Android. * * Internal function that uses polling to call into PhoneGap Java code and retrieve * any JavaScript code that needs to be run. This is used for callbacks from * Java to JavaScript. */ PhoneGap.JSCallbackPolling = function() { var msg = CallbackServer.getJavascript(); if (msg) { setTimeout(function() { try { var t = eval(""+msg); } catch (e) { console.log("JSCallbackPolling: Message from Server: " + msg); console.log("JSCallbackPolling Error: "+e); } }, 1); setTimeout(PhoneGap.JSCallbackPolling, 1); } else { setTimeout(PhoneGap.JSCallbackPolling, PhoneGap.JSCallbackPollingPeriod); } }; /** * Create a UUID * * @return */ PhoneGap.createUUID = function() { return PhoneGap.UUIDcreatePart(4) + '-' + PhoneGap.UUIDcreatePart(2) + '-' + PhoneGap.UUIDcreatePart(2) + '-' + PhoneGap.UUIDcreatePart(2) + '-' + PhoneGap.UUIDcreatePart(6); }; PhoneGap.UUIDcreatePart = function(length) { var uuidpart = ""; for (var i=0; i<length; i++) { var uuidchar = parseInt((Math.random() * 256)).toString(16); if (uuidchar.length == 1) { uuidchar = "0" + uuidchar; } uuidpart += uuidchar; } return uuidpart; }; PhoneGap.close = function(context, func, params) { if (typeof params === 'undefined') { return function() { return func.apply(context, arguments); } } else { return function() { return func.apply(context, params); } } }; /** * Load a JavaScript file after page has loaded. * * @param {String} jsfile The url of the JavaScript file to load. * @param {Function} successCallback The callback to call when the file has been loaded. */ PhoneGap.includeJavascript = function(jsfile, successCallback) { var id = document.getElementsByTagName("head")[0]; var el = document.createElement('script'); el.type = 'text/javascript'; if (typeof successCallback == 'function') { el.onload = successCallback; } el.src = jsfile; id.appendChild(el); }; /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ function Acceleration(x, y, z) { this.x = x; this.y = y; this.z = z; this.timestamp = new Date().getTime(); }; /** * This class provides access to device accelerometer data. * @constructor */ function Accelerometer() { /** * The last known acceleration. type=Acceleration() */ this.lastAcceleration = null; /** * List of accelerometer watch timers */ this.timers = {}; }; Accelerometer.ERROR_MSG = ["Not running", "Starting", "", "Failed to start"]; /** * Asynchronously aquires the current acceleration. * * @param {Function} successCallback The function to call when the acceleration data is available * @param {Function} errorCallback The function to call when there is an error getting the acceleration data. (OPTIONAL) * @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL) */ Accelerometer.prototype.getCurrentAcceleration = function(successCallback, errorCallback, options) { // successCallback required if (typeof successCallback != "function") { console.log("Accelerometer Error: successCallback is not a function"); return; } // errorCallback optional if (errorCallback && (typeof errorCallback != "function")) { console.log("Accelerometer Error: errorCallback is not a function"); return; } // Get acceleration PhoneGap.exec(successCallback, errorCallback, "Accelerometer", "getAcceleration", []); }; /** * Asynchronously aquires the acceleration repeatedly at a given interval. * * @param {Function} successCallback The function to call each time the acceleration data is available * @param {Function} errorCallback The function to call when there is an error getting the acceleration data. (OPTIONAL) * @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL) * @return String The watch id that must be passed to #clearWatch to stop watching. */ Accelerometer.prototype.watchAcceleration = function(successCallback, errorCallback, options) { // Default interval (10 sec) var frequency = (options != undefined)? options.frequency : 10000; // successCallback required if (typeof successCallback != "function") { console.log("Accelerometer Error: successCallback is not a function"); return; } // errorCallback optional if (errorCallback && (typeof errorCallback != "function")) { console.log("Accelerometer Error: errorCallback is not a function"); return; } // Make sure accelerometer timeout > frequency + 10 sec PhoneGap.exec( function(timeout) { if (timeout < (frequency + 10000)) { PhoneGap.exec(null, null, "Accelerometer", "setTimeout", [frequency + 10000]); } }, function(e) { }, "Accelerometer", "getTimeout", []); // Start watch timer var id = PhoneGap.createUUID(); navigator.accelerometer.timers[id] = setInterval(function() { PhoneGap.exec(successCallback, errorCallback, "Accelerometer", "getAcceleration", []); }, (frequency ? frequency : 1)); return id; }; /** * Clears the specified accelerometer watch. * * @param {String} id The id of the watch returned from #watchAcceleration. */ Accelerometer.prototype.clearWatch = function(id) { // Stop javascript timer & remove from timer list if (id && navigator.accelerometer.timers[id] != undefined) { clearInterval(navigator.accelerometer.timers[id]); delete navigator.accelerometer.timers[id]; } }; PhoneGap.addConstructor(function() { if (typeof navigator.accelerometer == "undefined") navigator.accelerometer = new Accelerometer(); }); /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * Constructor */ function App() { } /** * Clear the resource cache. */ App.prototype.clearCache = function() { PhoneGap.exec(null, null, "App", "clearCache", []); }; /** * Load the url into the webview. * * @param url The URL to load * @param props Properties that can be passed in to the activity: * wait: int => wait msec before loading URL * loadingDialog: "Title,Message" => display a native loading dialog * hideLoadingDialogOnPage: boolean => hide loadingDialog when page loaded instead of when deviceready event occurs. * loadInWebView: boolean => cause all links on web page to be loaded into existing web view, instead of being loaded into new browser. * loadUrlTimeoutValue: int => time in msec to wait before triggering a timeout error * errorUrl: URL => URL to load if there's an error loading specified URL with loadUrl(). Should be a local URL such as file:///android_asset/www/error.html"); * keepRunning: boolean => enable app to keep running in background * * Example: * App app = new App(); * app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000}); */ App.prototype.loadUrl = function(url, props) { PhoneGap.exec(null, null, "App", "loadUrl", [url, props]); }; /** * Cancel loadUrl that is waiting to be loaded. */ App.prototype.cancelLoadUrl = function() { PhoneGap.exec(null, null, "App", "cancelLoadUrl", []); }; /** * Clear web history in this web view. * Instead of BACK button loading the previous web page, it will exit the app. */ App.prototype.clearHistory = function() { PhoneGap.exec(null, null, "App", "clearHistory", []); }; /** * Add a class that implements a service. * * @param serviceType * @param className */ App.prototype.addService = function(serviceType, className) { PhoneGap.exec(null, null, "App", "addService", [serviceType, className]); }; /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * This class provides access to the device camera. * * @constructor */ Camera = function() { this.successCallback = null; this.errorCallback = null; this.options = null; }; /** * Format of image that returned from getPicture. * * Example: navigator.camera.getPicture(success, fail, * { quality: 80, * destinationType: Camera.DestinationType.DATA_URL, * sourceType: Camera.PictureSourceType.PHOTOLIBRARY}) */ Camera.DestinationType = { DATA_URL: 0, // Return base64 encoded string FILE_URI: 1 // Return file uri (content://media/external/images/media/2 for Android) }; Camera.prototype.DestinationType = Camera.DestinationType; /** * Source to getPicture from. * * Example: navigator.camera.getPicture(success, fail, * { quality: 80, * destinationType: Camera.DestinationType.DATA_URL, * sourceType: Camera.PictureSourceType.PHOTOLIBRARY}) */ Camera.PictureSourceType = { PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android) CAMERA : 1, // Take picture from camera SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android) }; Camera.prototype.PictureSourceType = Camera.PictureSourceType; /** * Gets a picture from source defined by "options.sourceType", and returns the * image as defined by the "options.destinationType" option. * The defaults are sourceType=CAMERA and destinationType=DATA_URL. * * @param {Function} successCallback * @param {Function} errorCallback * @param {Object} options */ Camera.prototype.getPicture = function(successCallback, errorCallback, options) { // successCallback required if (typeof successCallback != "function") { console.log("Camera Error: successCallback is not a function"); return; } // errorCallback optional if (errorCallback && (typeof errorCallback != "function")) { console.log("Camera Error: errorCallback is not a function"); return; } this.options = options; var quality = 80; if (options.quality) { quality = this.options.quality; } var destinationType = Camera.DestinationType.DATA_URL; if (this.options.destinationType) { destinationType = this.options.destinationType; } var sourceType = Camera.PictureSourceType.CAMERA; if (typeof this.options.sourceType == "number") { sourceType = this.options.sourceType; } PhoneGap.exec(successCallback, errorCallback, "Camera", "takePicture", [quality, destinationType, sourceType]); }; PhoneGap.addConstructor(function() { if (typeof navigator.camera == "undefined") navigator.camera = new Camera(); }); /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * This class provides access to device Compass data. * @constructor */ function Compass() { /** * The last known Compass position. */ this.lastHeading = null; /** * List of compass watch timers */ this.timers = {}; }; Compass.ERROR_MSG = ["Not running", "Starting", "", "Failed to start"]; /** * Asynchronously aquires the current heading. * * @param {Function} successCallback The function to call when the heading data is available * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL) * @param {PositionOptions} options The options for getting the heading data such as timeout. (OPTIONAL) */ Compass.prototype.getCurrentHeading = function(successCallback, errorCallback, options) { // successCallback required if (typeof successCallback != "function") { console.log("Compass Error: successCallback is not a function"); return; } // errorCallback optional if (errorCallback && (typeof errorCallback != "function")) { console.log("Compass Error: errorCallback is not a function"); return; } // Get heading PhoneGap.exec(successCallback, errorCallback, "Compass", "getHeading", []); }; /** * Asynchronously aquires the heading repeatedly at a given interval. * * @param {Function} successCallback The function to call each time the heading data is available * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL) * @param {HeadingOptions} options The options for getting the heading data such as timeout and the frequency of the watch. (OPTIONAL) * @return String The watch id that must be passed to #clearWatch to stop watching. */ Compass.prototype.watchHeading= function(successCallback, errorCallback, options) { // Default interval (100 msec) var frequency = (options != undefined) ? options.frequency : 100; // successCallback required if (typeof successCallback != "function") { console.log("Compass Error: successCallback is not a function"); return; } // errorCallback optional if (errorCallback && (typeof errorCallback != "function")) { console.log("Compass Error: errorCallback is not a function"); return; } // Make sure compass timeout > frequency + 10 sec PhoneGap.exec( function(timeout) { if (timeout < (frequency + 10000)) { PhoneGap.exec(null, null, "Compass", "setTimeout", [frequency + 10000]); } }, function(e) { }, "Compass", "getTimeout", []); // Start watch timer to get headings var id = PhoneGap.createUUID(); navigator.compass.timers[id] = setInterval( function() { PhoneGap.exec(successCallback, errorCallback, "Compass", "getHeading", []); }, (frequency ? frequency : 1)); return id; }; /** * Clears the specified heading watch. * * @param {String} id The ID of the watch returned from #watchHeading. */ Compass.prototype.clearWatch = function(id) { // Stop javascript timer & remove from timer list if (id && navigator.compass.timers[id]) { clearInterval(navigator.compass.timers[id]); delete navigator.compass.timers[id]; } }; PhoneGap.addConstructor(function() { if (typeof navigator.compass == "undefined") navigator.compass = new Compass(); }); /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * Contains information about a single contact. * @param {DOMString} id unique identifier * @param {DOMString} displayName * @param {ContactName} name * @param {DOMString} nickname * @param {ContactField[]} phoneNumbers array of phone numbers * @param {ContactField[]} emails array of email addresses * @param {ContactAddress[]} addresses array of addresses * @param {ContactField[]} ims instant messaging user ids * @param {ContactOrganization[]} organizations * @param {DOMString} revision date contact was last updated * @param {DOMString} birthday contact's birthday * @param {DOMString} gender contact's gender * @param {DOMString} note user notes about contact * @param {ContactField[]} photos * @param {ContactField[]} categories * @param {ContactField[]} urls contact's web sites * @param {DOMString} timezone the contacts time zone */ var Contact = function(id, displayName, name, nickname, phoneNumbers, emails, addresses, ims, organizations, revision, birthday, gender, note, photos, categories, urls, timezone) { this.id = id || null; this.rawId = null; this.displayName = displayName || null; this.name = name || null; // ContactName this.nickname = nickname || null; this.phoneNumbers = phoneNumbers || null; // ContactField[] this.emails = emails || null; // ContactField[] this.addresses = addresses || null; // ContactAddress[] this.ims = ims || null; // ContactField[] this.organizations = organizations || null; // ContactOrganization[] this.revision = revision || null; this.birthday = birthday || null; this.gender = gender || null; this.note = note || null; this.photos = photos || null; // ContactField[] this.categories = categories || null; // ContactField[] this.urls = urls || null; // ContactField[] this.timezone = timezone || null; }; /** * Removes contact from device storage. * @param successCB success callback * @param errorCB error callback */ Contact.prototype.remove = function(successCB, errorCB) { if (this.id == null) { var errorObj = new ContactError(); errorObj.code = ContactError.NOT_FOUND_ERROR; errorCB(errorObj); } else { PhoneGap.exec(successCB, errorCB, "Contacts", "remove", [this.id]); } }; /** * Creates a deep copy of this Contact. * With the contact ID set to null. * @return copy of this Contact */ Contact.prototype.clone = function() { var clonedContact = PhoneGap.clone(this); clonedContact.id = null; clonedContact.rawId = null; // Loop through and clear out any id's in phones, emails, etc. if (clonedContact.phoneNumbers) { for (i=0; i<clonedContact.phoneNumbers.length; i++) { clonedContact.phoneNumbers[i].id = null; } } if (clonedContact.emails) { for (i=0; i<clonedContact.emails.length; i++) { clonedContact.emails[i].id = null; } } if (clonedContact.addresses) { for (i=0; i<clonedContact.addresses.length; i++) { clonedContact.addresses[i].id = null; } } if (clonedContact.ims) { for (i=0; i<clonedContact.ims.length; i++) { clonedContact.ims[i].id = null; } } if (clonedContact.organizations) { for (i=0; i<clonedContact.organizations.length; i++) { clonedContact.organizations[i].id = null; } } if (clonedContact.tags) { for (i=0; i<clonedContact.tags.length; i++) { clonedContact.tags[i].id = null; } } if (clonedContact.photos) { for (i=0; i<clonedContact.photos.length; i++) { clonedContact.photos[i].id = null; } } if (clonedContact.urls) { for (i=0; i<clonedContact.urls.length; i++) { clonedContact.urls[i].id = null; } } return clonedContact; }; /** * Persists contact to device storage. * @param successCB success callback * @param errorCB error callback */ Contact.prototype.save = function(successCB, errorCB) { PhoneGap.exec(successCB, errorCB, "Contacts", "save", [this]); }; /** * Contact name. * @param formatted * @param familyName * @param givenName * @param middle * @param prefix * @param suffix */ var ContactName = function(formatted, familyName, givenName, middle, prefix, suffix) { this.formatted = formatted || null; this.familyName = familyName || null; this.givenName = givenName || null; this.middleName = middle || null; this.honorificPrefix = prefix || null; this.honorificSuffix = suffix || null; }; /** * Generic contact field. * @param {DOMString} id unique identifier, should only be set by native code * @param type * @param value * @param pref */ var ContactField = function(type, value, pref) { this.id = null; this.type = type || null; this.value = value || null; this.pref = pref || null; }; /** * Contact address. * @param {DOMString} id unique identifier, should only be set by native code * @param formatted * @param streetAddress * @param locality * @param region * @param postalCode * @param country */ var ContactAddress = function(formatted, streetAddress, locality, region, postalCode, country) { this.id = null; this.formatted = formatted || null; this.streetAddress = streetAddress || null; this.locality = locality || null; this.region = region || null; this.postalCode = postalCode || null; this.country = country || null; }; /** * Contact organization. * @param {DOMString} id unique identifier, should only be set by native code * @param name * @param dept * @param title * @param startDate * @param endDate * @param location * @param desc */ var ContactOrganization = function(name, dept, title) { this.id = null; this.name = name || null; this.department = dept || null; this.title = title || null; }; /** * Represents a group of Contacts. */ var Contacts = function() { this.inProgress = false; this.records = new Array(); } /** * Returns an array of Contacts matching the search criteria. * @param fields that should be searched * @param successCB success callback * @param errorCB error callback * @param {ContactFindOptions} options that can be applied to contact searching * @return array of Contacts matching search criteria */ Contacts.prototype.find = function(fields, successCB, errorCB, options) { PhoneGap.exec(successCB, errorCB, "Contacts", "search", [fields, options]); }; /** * This function creates a new contact, but it does not persist the contact * to device storage. To persist the contact to device storage, invoke * contact.save(). * @param properties an object who's properties will be examined to create a new Contact * @returns new Contact object */ Contacts.prototype.create = function(properties) { var contact = new Contact(); for (i in properties) { if (contact[i]!='undefined') { contact[i]=properties[i]; } } return contact; }; /** * This function returns and array of contacts. It is required as we need to convert raw * JSON objects into concrete Contact objects. Currently this method is called after * navigator.service.contacts.find but before the find methods success call back. * * @param jsonArray an array of JSON Objects that need to be converted to Contact objects. * @returns an array of Contact objects */ Contacts.prototype.cast = function(pluginResult) { var contacts = new Array(); for (var i=0; i<pluginResult.message.length; i++) { contacts.push(navigator.service.contacts.create(pluginResult.message[i])); } pluginResult.message = contacts; return pluginResult; } /** * ContactFindOptions. * @param filter used to match contacts against * @param multiple boolean used to determine if more than one contact should be returned * @param updatedSince return only contact records that have been updated on or after the given time */ var ContactFindOptions = function(filter, multiple, updatedSince) { this.filter = filter || ''; this.multiple = multiple || true; this.updatedSince = updatedSince || ''; }; /** * ContactError. * An error code assigned by an implementation when an error has occurred */ var ContactError = function() { this.code=null; }; /** * Error codes */ ContactError.UNKNOWN_ERROR = 0; ContactError.INVALID_ARGUMENT_ERROR = 1; ContactError.NOT_FOUND_ERROR = 2; ContactError.TIMEOUT_ERROR = 3; ContactError.PENDING_OPERATION_ERROR = 4; ContactError.IO_ERROR = 5; ContactError.NOT_SUPPORTED_ERROR = 6; ContactError.PERMISSION_DENIED_ERROR = 20; /** * Add the contact interface into the browser. */ PhoneGap.addConstructor(function() { if(typeof navigator.service == "undefined") navigator.service = new Object(); if(typeof navigator.service.contacts == "undefined") navigator.service.contacts = new Contacts(); }); /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ // TODO: Needs to be commented var Crypto = function() { }; Crypto.prototype.encrypt = function(seed, string, callback) { this.encryptWin = callback; PhoneGap.exec(null, null, "Crypto", "encrypt", [seed, string]); }; Crypto.prototype.decrypt = function(seed, string, callback) { this.decryptWin = callback; PhoneGap.exec(null, null, "Crypto", "decrypt", [seed, string]); }; Crypto.prototype.gotCryptedString = function(string) { this.encryptWin(string); }; Crypto.prototype.getPlainString = function(string) { this.decryptWin(string); }; PhoneGap.addConstructor(function() { if (typeof navigator.Crypto == "undefined") navigator.Crypto = new Crypto(); }); /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * This represents the mobile device, and provides properties for inspecting the model, version, UUID of the * phone, etc. * @constructor */ function Device() { this.available = PhoneGap.available; this.platform = null; this.version = null; this.name = null; this.uuid = null; this.phonegap = null; var me = this; this.getInfo( function(info) { me.available = true; me.platform = info.platform; me.version = info.version; me.name = info.name; me.uuid = info.uuid; me.phonegap = info.phonegap; PhoneGap.onPhoneGapInfoReady.fire(); }, function(e) { me.available = false; console.log("Error initializing PhoneGap: " + e); alert("Error initializing PhoneGap: "+e); }); } /** * Get device info * * @param {Function} successCallback The function to call when the heading data is available * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL) */ Device.prototype.getInfo = function(successCallback, errorCallback) { // successCallback required if (typeof successCallback != "function") { console.log("Device Error: successCallback is not a function"); return; } // errorCallback optional if (errorCallback && (typeof errorCallback != "function")) { console.log("Device Error: errorCallback is not a function"); return; } // Get info PhoneGap.exec(successCallback, errorCallback, "Device", "getDeviceInfo", []); }; /* * This is only for Android. * * You must explicitly override the back button. */ Device.prototype.overrideBackButton = function() { BackButton.override(); } /* * This is only for Android. * * This resets the back button to the default behaviour */ Device.prototype.resetBackButton = function() { BackButton.reset(); } /* * This is only for Android. * * This terminates the activity! */ Device.prototype.exitApp = function() { BackButton.exitApp(); } PhoneGap.addConstructor(function() { navigator.device = window.device = new Device(); }); /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * This class provides generic read and write access to the mobile device file system. * They are not used to read files from a server. */ /** * This class provides some useful information about a file. * This is the fields returned when navigator.fileMgr.getFileProperties() * is called. */ function FileProperties(filePath) { this.filePath = filePath; this.size = 0; this.lastModifiedDate = null; }; /** * Create an event object since we can't set target on DOM event. * * @param type * @param target * */ File._createEvent = function(type, target) { // Can't create event object, since we can't set target (its readonly) //var evt = document.createEvent('Events'); //evt.initEvent("onload", false, false); var evt = {"type": type}; evt.target = target; return evt; }; function FileError() { this.code = null; }; // File error codes // Found in DOMException FileError.NOT_FOUND_ERR = 1; FileError.SECURITY_ERR = 2; FileError.ABORT_ERR = 3; // Added by this specification FileError.NOT_READABLE_ERR = 4; FileError.ENCODING_ERR = 5; FileError.NO_MODIFICATION_ALLOWED_ERR = 6; FileError.INVALID_STATE_ERR = 7; FileError.SYNTAX_ERR = 8; //----------------------------------------------------------------------------- // File manager //----------------------------------------------------------------------------- function FileMgr() { }; FileMgr.prototype.getFileProperties = function(filePath) { return PhoneGap.exec(null, null, "File", "getFile", [filePath]); }; FileMgr.prototype.getFileBasePaths = function() { }; FileMgr.prototype.getRootPaths = function() { return PhoneGap.exec(null, null, "File", "getRootPaths", []); }; FileMgr.prototype.testSaveLocationExists = function(successCallback, errorCallback) { return PhoneGap.exec(successCallback, errorCallback, "File", "testSaveLocationExists", []); }; FileMgr.prototype.testFileExists = function(fileName, successCallback, errorCallback) { return PhoneGap.exec(successCallback, errorCallback, "File", "testFileExists", [fileName]); }; FileMgr.prototype.testDirectoryExists = function(dirName, successCallback, errorCallback) { return PhoneGap.exec(successCallback, errorCallback, "File", "testDirectoryExists", [dirName]); }; FileMgr.prototype.createDirectory = function(dirName, successCallback, errorCallback) { return PhoneGap.exec(successCallback, errorCallback, "File", "createDirectory", [dirName]); }; FileMgr.prototype.deleteDirectory = function(dirName, successCallback, errorCallback) { return PhoneGap.exec(successCallback, errorCallback, "File", "deleteDirectory", [dirName]); }; FileMgr.prototype.deleteFile = function(fileName, successCallback, errorCallback) { return PhoneGap.exec(successCallback, errorCallback, "File", "deleteFile", [fileName]); }; FileMgr.prototype.getFreeDiskSpace = function(successCallback, errorCallback) { return PhoneGap.exec(successCallback, errorCallback, "File", "getFreeDiskSpace", []); }; FileMgr.prototype.writeAsText = function(fileName, data, append, successCallback, errorCallback) { PhoneGap.exec(successCallback, errorCallback, "File", "writeAsText", [fileName, data, append]); }; FileMgr.prototype.write = function(fileName, data, position, successCallback, errorCallback) { PhoneGap.exec(successCallback, errorCallback, "File", "write", [fileName, data, position]); }; FileMgr.prototype.truncate = function(fileName, size, successCallback, errorCallback) { PhoneGap.exec(successCallback, errorCallback, "File", "truncate", [fileName, size]); }; FileMgr.prototype.readAsText = function(fileName, encoding, successCallback, errorCallback) { PhoneGap.exec(successCallback, errorCallback, "File", "readAsText", [fileName, encoding]); }; FileMgr.prototype.readAsDataURL = function(fileName, successCallback, errorCallback) { PhoneGap.exec(successCallback, errorCallback, "File", "readAsDataURL", [fileName]); }; PhoneGap.addConstructor(function() { if (typeof navigator.fileMgr == "undefined") navigator.fileMgr = new FileMgr(); }); //----------------------------------------------------------------------------- // File Reader //----------------------------------------------------------------------------- // TODO: All other FileMgr function operate on the SD card as root. However, // for FileReader & FileWriter the root is not SD card. Should this be changed? /** * This class reads the mobile device file system. * * For Android: * The root directory is the root of the file system. * To read from the SD card, the file name is "sdcard/my_file.txt" */ function FileReader() { this.fileName = ""; this.readyState = 0; // File data this.result = null; // Error this.error = null; // Event handlers this.onloadstart = null; // When the read starts. this.onprogress = null; // While reading (and decoding) file or fileBlob data, and reporting partial file data (progess.loaded/progress.total) this.onload = null; // When the read has successfully completed. this.onerror = null; // When the read has failed (see errors). this.onloadend = null; // When the request has completed (either in success or failure). this.onabort = null; // When the read has been aborted. For instance, by invoking the abort() method. }; // States FileReader.EMPTY = 0; FileReader.LOADING = 1; FileReader.DONE = 2; /** * Abort reading file. */ FileReader.prototype.abort = function() { this.readyState = FileReader.DONE; this.result = null; // set error var error = new FileError(); error.code = error.ABORT_ERR; this.error = error; // If error callback if (typeof this.onerror == "function") { var evt = File._createEvent("error", this); this.onerror(evt); } // If abort callback if (typeof this.onabort == "function") { var evt = File._createEvent("abort", this); this.onabort(evt); } // If load end callback if (typeof this.onloadend == "function") { var evt = File._createEvent("loadend", this); this.onloadend(evt); } }; /** * Read text file. * * @param file The name of the file * @param encoding [Optional] (see http://www.iana.org/assignments/character-sets) */ FileReader.prototype.readAsText = function(file, encoding) { this.fileName = file; // LOADING state this.readyState = FileReader.LOADING; // If loadstart callback if (typeof this.onloadstart == "function") { var evt = File._createEvent("loadstart", this); this.onloadstart(evt); } // Default encoding is UTF-8 var enc = encoding ? encoding : "UTF-8"; var me = this; // Read file navigator.fileMgr.readAsText(file, enc, // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me.readyState == FileReader.DONE) { return; } // Save result me.result = r; // If onload callback if (typeof me.onload == "function") { var evt = File._createEvent("load", me); me.onload(evt); } // DONE state me.readyState = FileReader.DONE; // If onloadend callback if (typeof me.onloadend == "function") { var evt = File._createEvent("loadend", me); me.onloadend(evt); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me.readyState == FileReader.DONE) { return; } // Save error me.error = e; // If onerror callback if (typeof me.onerror == "function") { var evt = File._createEvent("error", me); me.onerror(evt); } // DONE state me.readyState = FileReader.DONE; // If onloadend callback if (typeof me.onloadend == "function") { var evt = File._createEvent("loadend", me); me.onloadend(evt); } } ); }; /** * Read file and return data as a base64 encoded data url. * A data url is of the form: * data:[<mediatype>][;base64],<data> * * @param file The name of the file */ FileReader.prototype.readAsDataURL = function(file) { this.fileName = file; // LOADING state this.readyState = FileReader.LOADING; // If loadstart callback if (typeof this.onloadstart == "function") { var evt = File._createEvent("loadstart", this); this.onloadstart(evt); } var me = this; // Read file navigator.fileMgr.readAsDataURL(file, // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me.readyState == FileReader.DONE) { return; } // Save result me.result = r; // If onload callback if (typeof me.onload == "function") { var evt = File._createEvent("load", me); me.onload(evt); } // DONE state me.readyState = FileReader.DONE; // If onloadend callback if (typeof me.onloadend == "function") { var evt = File._createEvent("loadend", me); me.onloadend(evt); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me.readyState == FileReader.DONE) { return; } // Save error me.error = e; // If onerror callback if (typeof me.onerror == "function") { var evt = File._createEvent("error", me); me.onerror(evt); } // DONE state me.readyState = FileReader.DONE; // If onloadend callback if (typeof me.onloadend == "function") { var evt = File._createEvent("loadend", me); me.onloadend(evt); } } ); }; /** * Read file and return data as a binary data. * * @param file The name of the file */ FileReader.prototype.readAsBinaryString = function(file) { // TODO - Can't return binary data to browser. this.fileName = file; }; /** * Read file and return data as a binary data. * * @param file The name of the file */ FileReader.prototype.readAsArrayBuffer = function(file) { // TODO - Can't return binary data to browser. this.fileName = file; }; //----------------------------------------------------------------------------- // File Writer //----------------------------------------------------------------------------- /** * This class writes to the mobile device file system. * * For Android: * The root directory is the root of the file system. * To write to the SD card, the file name is "sdcard/my_file.txt" * * @param filePath the file to write to * @param append if true write to the end of the file, otherwise overwrite the file */ function FileWriter(filePath, append) { this.fileName = ""; this.length = 0; if (filePath) { var f = navigator.fileMgr.getFileProperties(filePath); this.fileName = f.name; this.length = f.size; } // default is to write at the beginning of the file this.position = (append !== true) ? 0 : this.length; this.readyState = 0; // EMPTY this.result = null; // Error this.error = null; // Event handlers this.onwritestart = null; // When writing starts this.onprogress = null; // While writing the file, and reporting partial file data this.onwrite = null; // When the write has successfully completed. this.onwriteend = null; // When the request has completed (either in success or failure). this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method. this.onerror = null; // When the write has failed (see errors). }; // States FileWriter.INIT = 0; FileWriter.WRITING = 1; FileWriter.DONE = 2; /** * Abort writing file. */ FileWriter.prototype.abort = function() { // check for invalid state if (this.readyState === FileWriter.DONE || this.readyState === FileWriter.INIT) { throw FileError.INVALID_STATE_ERR; } // set error var error = new FileError(); error.code = error.ABORT_ERR; this.error = error; // If error callback if (typeof this.onerror == "function") { var evt = File._createEvent("error", this); this.onerror(evt); } // If abort callback if (typeof this.onabort == "function") { var evt = File._createEvent("abort", this); this.onabort(evt); } this.readyState = FileWriter.DONE; // If write end callback if (typeof this.onwriteend == "function") { var evt = File._createEvent("writeend", this); this.onwriteend(evt); } }; /** * @Deprecated: use write instead * * @param file to write the data to * @param text to be written * @param bAppend if true write to end of file, otherwise overwrite the file */ FileWriter.prototype.writeAsText = function(file, text, bAppend) { // Throw an exception if we are already writing a file if (this.readyState == FileWriter.WRITING) { throw FileError.INVALID_STATE_ERR; } if (bAppend != true) { bAppend = false; // for null values } this.fileName = file; // WRITING state this.readyState = FileWriter.WRITING; var me = this; // If onwritestart callback if (typeof me.onwritestart == "function") { var evt = File._createEvent("writestart", me); me.onwritestart(evt); } // Write file navigator.fileMgr.writeAsText(file, text, bAppend, // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me.readyState == FileWriter.DONE) { return; } // Save result me.result = r; // If onwrite callback if (typeof me.onwrite == "function") { var evt = File._createEvent("write", me); me.onwrite(evt); } // DONE state me.readyState = FileWriter.DONE; // If onwriteend callback if (typeof me.onwriteend == "function") { var evt = File._createEvent("writeend", me); me.onwriteend(evt); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me.readyState == FileWriter.DONE) { return; } // Save error me.error = e; // If onerror callback if (typeof me.onerror == "function") { var evt = File._createEvent("error", me); me.onerror(evt); } // DONE state me.readyState = FileWriter.DONE; // If onwriteend callback if (typeof me.onwriteend == "function") { var evt = File._createEvent("writeend", me); me.onwriteend(evt); } } ); }; /** * Writes data to the file * * @param text to be written */ FileWriter.prototype.write = function(text) { // Throw an exception if we are already writing a file if (this.readyState == FileWriter.WRITING) { throw FileError.INVALID_STATE_ERR; } // WRITING state this.readyState = FileWriter.WRITING; var me = this; // If onwritestart callback if (typeof me.onwritestart == "function") { var evt = File._createEvent("writestart", me); me.onwritestart(evt); } // Write file navigator.fileMgr.write(this.fileName, text, this.position, // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me.readyState == FileWriter.DONE) { return; } // So if the user wants to keep appending to the file me.length = Math.max(me.length, me.position + r); // position always increases by bytes written because file would be extended me.position += r; // If onwrite callback if (typeof me.onwrite == "function") { var evt = File._createEvent("write", me); me.onwrite(evt); } // DONE state me.readyState = FileWriter.DONE; // If onwriteend callback if (typeof me.onwriteend == "function") { var evt = File._createEvent("writeend", me); me.onwriteend(evt); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me.readyState == FileWriter.DONE) { return; } // Save error me.error = e; // If onerror callback if (typeof me.onerror == "function") { var evt = File._createEvent("error", me); me.onerror(evt); } // DONE state me.readyState = FileWriter.DONE; // If onwriteend callback if (typeof me.onwriteend == "function") { var evt = File._createEvent("writeend", me); me.onwriteend(evt); } } ); }; /** * Moves the file pointer to the location specified. * * If the offset is a negative number the position of the file * pointer is rewound. If the offset is greater than the file * size the position is set to the end of the file. * * @param offset is the location to move the file pointer to. */ FileWriter.prototype.seek = function(offset) { // Throw an exception if we are already writing a file if (this.readyState === FileWriter.WRITING) { throw FileError.INVALID_STATE_ERR; } if (!offset) { return; } // See back from end of file. if (offset < 0) { this.position = Math.max(offset + this.length, 0); } // Offset is bigger then file size so set position // to the end of the file. else if (offset > this.length) { this.position = this.length; } // Offset is between 0 and file size so set the position // to start writing. else { this.position = offset; } }; /** * Truncates the file to the size specified. * * @param size to chop the file at. */ FileWriter.prototype.truncate = function(size) { // Throw an exception if we are already writing a file if (this.readyState == FileWriter.WRITING) { throw FileError.INVALID_STATE_ERR; } // WRITING state this.readyState = FileWriter.WRITING; var me = this; // If onwritestart callback if (typeof me.onwritestart == "function") { var evt = File._createEvent("writestart", me); me.onwritestart(evt); } // Write file navigator.fileMgr.truncate(this.fileName, size, // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me.readyState == FileWriter.DONE) { return; } // Update the length of the file me.length = r; me.position = Math.min(me.position, r);; // If onwrite callback if (typeof me.onwrite == "function") { var evt = File._createEvent("write", me); me.onwrite(evt); } // DONE state me.readyState = FileWriter.DONE; // If onwriteend callback if (typeof me.onwriteend == "function") { var evt = File._createEvent("writeend", me); me.onwriteend(evt); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me.readyState == FileWriter.DONE) { return; } // Save error me.error = e; // If onerror callback if (typeof me.onerror == "function") { var evt = File._createEvent("error", me); me.onerror(evt); } // DONE state me.readyState = FileWriter.DONE; // If onwriteend callback if (typeof me.onwriteend == "function") { var evt = File._createEvent("writeend", me); me.onwriteend(evt); } } ); }; /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * FileTransfer uploads a file to a remote server. */ function FileTransfer() {}; /** * FileUploadResult */ function FileUploadResult() { this.bytesSent = 0; this.responseCode = null; this.response = null; }; /** * FileTransferError */ function FileTransferError() { this.code = null; }; FileTransferError.FILE_NOT_FOUND_ERR = 1; FileTransferError.INVALID_URL_ERR = 2; FileTransferError.CONNECTION_ERR = 3; /** * Given an absolute file path, uploads a file on the device to a remote server * using a multipart HTTP request. * @param filePath {String} Full path of the file on the device * @param server {String} URL of the server to receive the file * @param successCallback (Function} Callback to be invoked when upload has completed * @param errorCallback {Function} Callback to be invoked upon error * @param options {FileUploadOptions} Optional parameters such as file name and mimetype */ FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, debug) { // check for options var fileKey = null; var fileName = null; var mimeType = null; var params = null; if (options) { fileKey = options.fileKey; fileName = options.fileName; mimeType = options.mimeType; if (options.params) { params = options.params; } else { params = {}; } } PhoneGap.exec(successCallback, errorCallback, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, debug]); }; /** * Options to customize the HTTP request used to upload files. * @param fileKey {String} Name of file request parameter. * @param fileName {String} Filename to be used by the server. Defaults to image.jpg. * @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg. * @param params {Object} Object with key: value params to send to the server. */ function FileUploadOptions(fileKey, fileName, mimeType, params) { this.fileKey = fileKey || null; this.fileName = fileName || null; this.mimeType = mimeType || null; this.params = params || null; }; /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * This class provides access to device GPS data. * @constructor */ function Geolocation() { // The last known GPS position. this.lastPosition = null; // Geolocation listeners this.listeners = {}; }; /** * Position error object * * @param code * @param message */ function PositionError(code, message) { this.code = code; this.message = message; }; PositionError.PERMISSION_DENIED = 1; PositionError.POSITION_UNAVAILABLE = 2; PositionError.TIMEOUT = 3; /** * Asynchronously aquires the current position. * * @param {Function} successCallback The function to call when the position data is available * @param {Function} errorCallback The function to call when there is an error getting the heading position. (OPTIONAL) * @param {PositionOptions} options The options for getting the position data. (OPTIONAL) */ Geolocation.prototype.getCurrentPosition = function(successCallback, errorCallback, options) { if (navigator._geo.listeners["global"]) { console.log("Geolocation Error: Still waiting for previous getCurrentPosition() request."); try { errorCallback(new PositionError(PositionError.TIMEOUT, "Geolocation Error: Still waiting for previous getCurrentPosition() request.")); } catch (e) { } return; } var maximumAge = 10000; var enableHighAccuracy = false; var timeout = 10000; if (typeof options != "undefined") { if (typeof options.maximumAge != "undefined") { maximumAge = options.maximumAge; } if (typeof options.enableHighAccuracy != "undefined") { enableHighAccuracy = options.enableHighAccuracy; } if (typeof options.timeout != "undefined") { timeout = options.timeout; } } navigator._geo.listeners["global"] = {"success" : successCallback, "fail" : errorCallback }; PhoneGap.exec(null, null, "Geolocation", "getCurrentLocation", [enableHighAccuracy, timeout, maximumAge]); } /** * Asynchronously watches the geolocation for changes to geolocation. When a change occurs, * the successCallback is called with the new location. * * @param {Function} successCallback The function to call each time the location data is available * @param {Function} errorCallback The function to call when there is an error getting the location data. (OPTIONAL) * @param {PositionOptions} options The options for getting the location data such as frequency. (OPTIONAL) * @return String The watch id that must be passed to #clearWatch to stop watching. */ Geolocation.prototype.watchPosition = function(successCallback, errorCallback, options) { var maximumAge = 10000; var enableHighAccuracy = false; var timeout = 10000; if (typeof options != "undefined") { if (typeof options.frequency != "undefined") { maximumAge = options.frequency; } if (typeof options.maximumAge != "undefined") { maximumAge = options.maximumAge; } if (typeof options.enableHighAccuracy != "undefined") { enableHighAccuracy = options.enableHighAccuracy; } if (typeof options.timeout != "undefined") { timeout = options.timeout; } } var id = PhoneGap.createUUID(); navigator._geo.listeners[id] = {"success" : successCallback, "fail" : errorCallback }; PhoneGap.exec(null, null, "Geolocation", "start", [id, enableHighAccuracy, timeout, maximumAge]); return id; }; /* * Native callback when watch position has a new position. * PRIVATE METHOD * * @param {String} id * @param {Number} lat * @param {Number} lng * @param {Number} alt * @param {Number} altacc * @param {Number} head * @param {Number} vel * @param {Number} stamp */ Geolocation.prototype.success = function(id, lat, lng, alt, altacc, head, vel, stamp) { var coords = new Coordinates(lat, lng, alt, altacc, head, vel); var loc = new Position(coords, stamp); try { if (lat == "undefined" || lng == "undefined") { navigator._geo.listeners[id].fail(new PositionError(PositionError.POSITION_UNAVAILABLE, "Lat/Lng are undefined.")); } else { navigator._geo.lastPosition = loc; navigator._geo.listeners[id].success(loc); } } catch (e) { console.log("Geolocation Error: Error calling success callback function."); } if (id == "global") { delete navigator._geo.listeners["global"]; } }; /** * Native callback when watch position has an error. * PRIVATE METHOD * * @param {String} id The ID of the watch * @param {Number} code The error code * @param {String} msg The error message */ Geolocation.prototype.fail = function(id, code, msg) { try { navigator._geo.listeners[id].fail(new PositionError(code, msg)); } catch (e) { console.log("Geolocation Error: Error calling error callback function."); } }; /** * Clears the specified heading watch. * * @param {String} id The ID of the watch returned from #watchPosition */ Geolocation.prototype.clearWatch = function(id) { PhoneGap.exec(null, null, "Geolocation", "stop", [id]); delete navigator._geo.listeners[id]; }; /** * Force the PhoneGap geolocation to be used instead of built-in. */ Geolocation.usingPhoneGap = false; Geolocation.usePhoneGap = function() { if (Geolocation.usingPhoneGap) { return; } Geolocation.usingPhoneGap = true; // Set built-in geolocation methods to our own implementations // (Cannot replace entire geolocation, but can replace individual methods) navigator.geolocation.setLocation = navigator._geo.setLocation; navigator.geolocation.getCurrentPosition = navigator._geo.getCurrentPosition; navigator.geolocation.watchPosition = navigator._geo.watchPosition; navigator.geolocation.clearWatch = navigator._geo.clearWatch; navigator.geolocation.start = navigator._geo.start; navigator.geolocation.stop = navigator._geo.stop; }; PhoneGap.addConstructor(function() { navigator._geo = new Geolocation(); // No native geolocation object for Android 1.x, so use PhoneGap geolocation if (typeof navigator.geolocation == 'undefined') { navigator.geolocation = navigator._geo; Geolocation.usingPhoneGap = true; } }); /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ function KeyEvent() { } KeyEvent.prototype.backTrigger = function() { var e = document.createEvent('Events'); e.initEvent('backKeyDown'); document.dispatchEvent(e); }; KeyEvent.prototype.menuTrigger = function() { var e = document.createEvent('Events'); e.initEvent('menuKeyDown'); document.dispatchEvent(e); }; KeyEvent.prototype.searchTrigger = function() { var e = document.createEvent('Events'); e.initEvent('searchKeyDown'); document.dispatchEvent(e); }; if (document.keyEvent == null || typeof document.keyEvent == 'undefined') { window.keyEvent = document.keyEvent = new KeyEvent(); } /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * List of media objects. * PRIVATE */ PhoneGap.mediaObjects = {}; /** * Object that receives native callbacks. * PRIVATE */ PhoneGap.Media = function() {}; /** * Get the media object. * PRIVATE * * @param id The media object id (string) */ PhoneGap.Media.getMediaObject = function(id) { return PhoneGap.mediaObjects[id]; }; /** * Audio has status update. * PRIVATE * * @param id The media object id (string) * @param status The status code (int) * @param msg The status message (string) */ PhoneGap.Media.onStatus = function(id, msg, value) { var media = PhoneGap.mediaObjects[id]; // If state update if (msg == Media.MEDIA_STATE) { if (value == Media.MEDIA_STOPPED) { if (media.successCallback) { media.successCallback(); } } if (media.statusCallback) { media.statusCallback(value); } } else if (msg == Media.MEDIA_DURATION) { media._duration = value; } else if (msg == Media.MEDIA_ERROR) { if (media.errorCallback) { media.errorCallback(value); } } }; /** * This class provides access to the device media, interfaces to both sound and video * * @param src The file name or url to play * @param successCallback The callback to be called when the file is done playing or recording. * successCallback() - OPTIONAL * @param errorCallback The callback to be called if there is an error. * errorCallback(int errorCode) - OPTIONAL * @param statusCallback The callback to be called when media status has changed. * statusCallback(int statusCode) - OPTIONAL * @param positionCallback The callback to be called when media position has changed. * positionCallback(long position) - OPTIONAL */ Media = function(src, successCallback, errorCallback, statusCallback, positionCallback) { // successCallback optional if (successCallback && (typeof successCallback != "function")) { console.log("Media Error: successCallback is not a function"); return; } // errorCallback optional if (errorCallback && (typeof errorCallback != "function")) { console.log("Media Error: errorCallback is not a function"); return; } // statusCallback optional if (statusCallback && (typeof statusCallback != "function")) { console.log("Media Error: statusCallback is not a function"); return; } // statusCallback optional if (positionCallback && (typeof positionCallback != "function")) { console.log("Media Error: positionCallback is not a function"); return; } this.id = PhoneGap.createUUID(); PhoneGap.mediaObjects[this.id] = this; this.src = src; this.successCallback = successCallback; this.errorCallback = errorCallback; this.statusCallback = statusCallback; this.positionCallback = positionCallback; this._duration = -1; this._position = -1; }; // Media messages Media.MEDIA_STATE = 1; Media.MEDIA_DURATION = 2; Media.MEDIA_ERROR = 9; // Media states Media.MEDIA_NONE = 0; Media.MEDIA_STARTING = 1; Media.MEDIA_RUNNING = 2; Media.MEDIA_PAUSED = 3; Media.MEDIA_STOPPED = 4; Media.MEDIA_MSG = ["None", "Starting", "Running", "Paused", "Stopped"]; // TODO: Will MediaError be used? /** * This class contains information about any Media errors. * @constructor */ function MediaError() { this.code = null, this.message = ""; }; MediaError.MEDIA_ERR_ABORTED = 1; MediaError.MEDIA_ERR_NETWORK = 2; MediaError.MEDIA_ERR_DECODE = 3; MediaError.MEDIA_ERR_NONE_SUPPORTED = 4; /** * Start or resume playing audio file. */ Media.prototype.play = function() { PhoneGap.exec(null, null, "Media", "startPlayingAudio", [this.id, this.src]); }; /** * Stop playing audio file. */ Media.prototype.stop = function() { return PhoneGap.exec(null, null, "Media", "stopPlayingAudio", [this.id]); }; /** * Pause playing audio file. */ Media.prototype.pause = function() { PhoneGap.exec(null, null, "Media", "pausePlayingAudio", [this.id]); }; /** * Get duration of an audio file. * The duration is only set for audio that is playing, paused or stopped. * * @return duration or -1 if not known. */ Media.prototype.getDuration = function() { return this._duration; }; /** * Get position of audio. * * @return */ Media.prototype.getCurrentPosition = function(success, fail) { PhoneGap.exec(success, fail, "Media", "getCurrentPositionAudio", [this.id]); }; /** * Start recording audio file. */ Media.prototype.startRecord = function() { PhoneGap.exec(null, null, "Media", "startRecordingAudio", [this.id, this.src]); }; /** * Stop recording audio file. */ Media.prototype.stopRecord = function() { PhoneGap.exec(null, null, "Media", "stopRecordingAudio", [this.id]); }; /** * Release the resources. */ Media.prototype.release = function() { PhoneGap.exec(null, null, "Media", "release", [this.id]); }; /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * This class contains information about any NetworkStatus. * @constructor */ function NetworkStatus() { //this.code = null; //this.message = ""; }; NetworkStatus.NOT_REACHABLE = 0; NetworkStatus.REACHABLE_VIA_CARRIER_DATA_NETWORK = 1; NetworkStatus.REACHABLE_VIA_WIFI_NETWORK = 2; /** * This class provides access to device Network data (reachability). * @constructor */ function Network() { /** * The last known Network status. * { hostName: string, ipAddress: string, remoteHostStatus: int(0/1/2), internetConnectionStatus: int(0/1/2), localWiFiConnectionStatus: int (0/2) } */ this.lastReachability = null; }; /** * Called by the geolocation framework when the reachability status has changed. * @param {Reachibility} reachability The current reachability status. */ // TODO: Callback from native code not implemented for Android Network.prototype.updateReachability = function(reachability) { this.lastReachability = reachability; }; /** * Determine if a URI is reachable over the network. * @param {Object} uri * @param {Function} callback * @param {Object} options (isIpAddress:boolean) */ Network.prototype.isReachable = function(uri, callback, options) { var isIpAddress = false; if (options && options.isIpAddress) { isIpAddress = options.isIpAddress; } PhoneGap.exec(callback, null, "Network Status", "isReachable", [uri, isIpAddress]); }; PhoneGap.addConstructor(function() { if (typeof navigator.network == "undefined") navigator.network = new Network(); }); /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * This class provides access to notifications on the device. */ function Notification() { } /** * Open a native alert dialog, with a customizable title and button text. * * @param {String} message Message to print in the body of the alert * @param {Function} completeCallback The callback that is called when user clicks on a button. * @param {String} title Title of the alert dialog (default: Alert) * @param {String} buttonLabel Label of the close button (default: OK) */ Notification.prototype.alert = function(message, completeCallback, title, buttonLabel) { var _title = (title || "Alert"); var _buttonLabel = (buttonLabel || "OK"); PhoneGap.exec(completeCallback, null, "Notification", "alert", [message,_title,_buttonLabel]); }; /** * Open a native confirm dialog, with a customizable title and button text. * The result that the user selects is returned to the result callback. * * @param {String} message Message to print in the body of the alert * @param {Function} resultCallback The callback that is called when user clicks on a button. * @param {String} title Title of the alert dialog (default: Confirm) * @param {String} buttonLabels Comma separated list of the labels of the buttons (default: 'OK,Cancel') */ Notification.prototype.confirm = function(message, resultCallback, title, buttonLabels) { var _title = (title || "Confirm"); var _buttonLabels = (buttonLabels || "OK,Cancel"); PhoneGap.exec(resultCallback, null, "Notification", "confirm", [message,_title,_buttonLabels]); }; /** * Start spinning the activity indicator on the statusbar */ Notification.prototype.activityStart = function() { PhoneGap.exec(null, null, "Notification", "activityStart", ["Busy","Please wait..."]); }; /** * Stop spinning the activity indicator on the statusbar, if it's currently spinning */ Notification.prototype.activityStop = function() { PhoneGap.exec(null, null, "Notification", "activityStop", []); }; /** * Display a progress dialog with progress bar that goes from 0 to 100. * * @param {String} title Title of the progress dialog. * @param {String} message Message to display in the dialog. */ Notification.prototype.progressStart = function(title, message) { PhoneGap.exec(null, null, "Notification", "progressStart", [title, message]); }; /** * Set the progress dialog value. * * @param {Number} value 0-100 */ Notification.prototype.progressValue = function(value) { PhoneGap.exec(null, null, "Notification", "progressValue", [value]); }; /** * Close the progress dialog. */ Notification.prototype.progressStop = function() { PhoneGap.exec(null, null, "Notification", "progressStop", []); }; /** * Causes the device to blink a status LED. * * @param {Integer} count The number of blinks. * @param {String} colour The colour of the light. */ Notification.prototype.blink = function(count, colour) { // NOT IMPLEMENTED }; /** * Causes the device to vibrate. * * @param {Integer} mills The number of milliseconds to vibrate for. */ Notification.prototype.vibrate = function(mills) { PhoneGap.exec(null, null, "Notification", "vibrate", [mills]); }; /** * Causes the device to beep. * On Android, the default notification ringtone is played "count" times. * * @param {Integer} count The number of beeps. */ Notification.prototype.beep = function(count) { PhoneGap.exec(null, null, "Notification", "beep", [count]); }; PhoneGap.addConstructor(function() { if (typeof navigator.notification == "undefined") navigator.notification = new Notification(); }); /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /** * This class contains position information. * @param {Object} lat * @param {Object} lng * @param {Object} acc * @param {Object} alt * @param {Object} altacc * @param {Object} head * @param {Object} vel * @constructor */ function Position(coords, timestamp) { this.coords = coords; this.timestamp = (timestamp != 'undefined') ? timestamp : new Date().getTime(); } function Coordinates(lat, lng, alt, acc, head, vel, altacc) { /** * The latitude of the position. */ this.latitude = lat; /** * The longitude of the position, */ this.longitude = lng; /** * The accuracy of the position. */ this.accuracy = acc; /** * The altitude of the position. */ this.altitude = alt; /** * The direction the device is moving at the position. */ this.heading = head; /** * The velocity with which the device is moving at the position. */ this.speed = vel; /** * The altitude accuracy of the position. */ this.altitudeAccuracy = (altacc != 'undefined') ? altacc : null; } /** * This class specifies the options for requesting position data. * @constructor */ function PositionOptions() { /** * Specifies the desired position accuracy. */ this.enableHighAccuracy = true; /** * The timeout after which if position data cannot be obtained the errorCallback * is called. */ this.timeout = 10000; } /** * This class contains information about any GSP errors. * @constructor */ function PositionError() { this.code = null; this.message = ""; } PositionError.UNKNOWN_ERROR = 0; PositionError.PERMISSION_DENIED = 1; PositionError.POSITION_UNAVAILABLE = 2; PositionError.TIMEOUT = 3; /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ /* * This is purely for the Android 1.5/1.6 HTML 5 Storage * I was hoping that Android 2.0 would deprecate this, but given the fact that * most manufacturers ship with Android 1.5 and do not do OTA Updates, this is required */ /** * Storage object that is called by native code when performing queries. * PRIVATE METHOD */ var DroidDB = function() { this.queryQueue = {}; }; /** * Callback from native code when query is complete. * PRIVATE METHOD * * @param id Query id */ DroidDB.prototype.completeQuery = function(id, data) { var query = this.queryQueue[id]; if (query) { try { delete this.queryQueue[id]; // Get transaction var tx = query.tx; // If transaction hasn't failed // Note: We ignore all query results if previous query // in the same transaction failed. if (tx && tx.queryList[id]) { // Save query results var r = new DroidDB_Result(); r.rows.resultSet = data; r.rows.length = data.length; try { if (typeof query.successCallback == 'function') { query.successCallback(query.tx, r); } } catch (ex) { console.log("executeSql error calling user success callback: "+ex); } tx.queryComplete(id); } } catch (e) { console.log("executeSql error: "+e); } } }; /** * Callback from native code when query fails * PRIVATE METHOD * * @param reason Error message * @param id Query id */ DroidDB.prototype.fail = function(reason, id) { var query = this.queryQueue[id]; if (query) { try { delete this.queryQueue[id]; // Get transaction var tx = query.tx; // If transaction hasn't failed // Note: We ignore all query results if previous query // in the same transaction failed. if (tx && tx.queryList[id]) { tx.queryList = {}; try { if (typeof query.errorCallback == 'function') { query.errorCallback(query.tx, reason); } } catch (ex) { console.log("executeSql error calling user error callback: "+ex); } tx.queryFailed(id, reason); } } catch (e) { console.log("executeSql error: "+e); } } }; var DatabaseShell = function() { }; /** * Start a transaction. * Does not support rollback in event of failure. * * @param process {Function} The transaction function * @param successCallback {Function} * @param errorCallback {Function} */ DatabaseShell.prototype.transaction = function(process, errorCallback, successCallback) { var tx = new DroidDB_Tx(); tx.successCallback = successCallback; tx.errorCallback = errorCallback; try { process(tx); } catch (e) { console.log("Transaction error: "+e); if (tx.errorCallback) { try { tx.errorCallback(e); } catch (ex) { console.log("Transaction error calling user error callback: "+e); } } } }; /** * Transaction object * PRIVATE METHOD */ var DroidDB_Tx = function() { // Set the id of the transaction this.id = PhoneGap.createUUID(); // Callbacks this.successCallback = null; this.errorCallback = null; // Query list this.queryList = {}; }; /** * Mark query in transaction as complete. * If all queries are complete, call the user's transaction success callback. * * @param id Query id */ DroidDB_Tx.prototype.queryComplete = function(id) { delete this.queryList[id]; // If no more outstanding queries, then fire transaction success if (this.successCallback) { var count = 0; for (var i in this.queryList) { count++; } if (count == 0) { try { this.successCallback(); } catch(e) { console.log("Transaction error calling user success callback: " + e); } } } }; /** * Mark query in transaction as failed. * * @param id Query id * @param reason Error message */ DroidDB_Tx.prototype.queryFailed = function(id, reason) { // The sql queries in this transaction have already been run, since // we really don't have a real transaction implemented in native code. // However, the user callbacks for the remaining sql queries in transaction // will not be called. this.queryList = {}; if (this.errorCallback) { try { this.errorCallback(reason); } catch(e) { console.log("Transaction error calling user error callback: " + e); } } }; /** * SQL query object * PRIVATE METHOD * * @param tx The transaction object that this query belongs to */ var DroidDB_Query = function(tx) { // Set the id of the query this.id = PhoneGap.createUUID(); // Add this query to the queue droiddb.queryQueue[this.id] = this; // Init result this.resultSet = []; // Set transaction that this query belongs to this.tx = tx; // Add this query to transaction list this.tx.queryList[this.id] = this; // Callbacks this.successCallback = null; this.errorCallback = null; } /** * Execute SQL statement * * @param sql SQL statement to execute * @param params Statement parameters * @param successCallback Success callback * @param errorCallback Error callback */ DroidDB_Tx.prototype.executeSql = function(sql, params, successCallback, errorCallback) { // Init params array if (typeof params == 'undefined') { params = []; } // Create query and add to queue var query = new DroidDB_Query(this); droiddb.queryQueue[query.id] = query; // Save callbacks query.successCallback = successCallback; query.errorCallback = errorCallback; // Call native code PhoneGap.exec(null, null, "Storage", "executeSql", [sql, params, query.id]); }; /** * SQL result set that is returned to user. * PRIVATE METHOD */ DroidDB_Result = function() { this.rows = new DroidDB_Rows(); }; /** * SQL result set object * PRIVATE METHOD */ DroidDB_Rows = function() { this.resultSet = []; // results array this.length = 0; // number of rows }; /** * Get item from SQL result set * * @param row The row number to return * @return The row object */ DroidDB_Rows.prototype.item = function(row) { return this.resultSet[row]; }; /** * Open database * * @param name Database name * @param version Database version * @param display_name Database display name * @param size Database size in bytes * @return Database object */ DroidDB_openDatabase = function(name, version, display_name, size) { PhoneGap.exec(null, null, "Storage", "openDatabase", [name, version, display_name, size]); var db = new DatabaseShell(); return db; }; /** * For browsers with no localStorage we emulate it with SQLite. Follows the w3c api. * TODO: Do similar for sessionStorage. */ var CupcakeLocalStorage = function() { try { this.db = openDatabase('localStorage', '1.0', 'localStorage', 2621440); var storage = {}; this.db.transaction( function (transaction) { transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))'); transaction.executeSql('SELECT * FROM storage', [], function(tx, result) { for(var i = 0; i < result.rows.length; i++) { storage[result.rows.item(i)['id']] = result.rows.item(i)['body']; } PhoneGap.initializationComplete("cupcakeStorage"); }); }, function (err) { alert(err.message); } ); this.setItem = function(key, val) { console.log('set'); storage[key] = val; this.db.transaction( function (transaction) { transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))'); transaction.executeSql('REPLACE INTO storage (id, body) values(?,?)', [key,val]); } ); } this.getItem = function(key) { return storage[key]; } this.removeItem = function(key) { delete storage[key]; this.db.transaction( function (transaction) { transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))'); transaction.executeSql('DELETE FROM storage where id=?', [key]); } ); } } catch(e) { alert("Database error "+e+"."); return; } }; PhoneGap.addConstructor(function() { if (typeof window.openDatabase == "undefined") { navigator.openDatabase = window.openDatabase = DroidDB_openDatabase; window.droiddb = new DroidDB(); } if (typeof window.localStorage == "undefined") { navigator.localStorage = window.localStorage = new CupcakeLocalStorage(); PhoneGap.waitForInitialization("cupcakeStorage"); } });
JavaScript
/* "URL-safe" Base64 Codec, by Jacob Rus This library happily strips off as many trailing '=' as are included in the input to 'decode', and doesn't worry whether its length is an even multiple of 4. It does not include trailing '=' in its own output. It uses the 'URL safe' base64 alphabet, where the last two characters are '-' and '_'. -------------------- Copyright (c) 2009 Jacob Rus 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. */ var sys = require('sys'); var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; var pad = '='; var padChar = alphabet.charAt(alphabet.length - 1); var shorten = function (array, number) { // remove 'number' characters from the end of 'array', in place (no return) for (var i = number; i > 0; i--){ array.pop(); }; }; var decode_map = {}; for (var i=0, n=alphabet.length; i < n; i++) { decode_map[alphabet.charAt(i)] = i; }; // use this regexp in the decode function to sniff out invalid characters. var alphabet_inverse = new RegExp('[^' + alphabet.replace('-', '\\-') + ']'); var Base64CodecError = exports.Base64CodecError = function (message) { this.message = message; }; Base64CodecError.prototype.toString = function () { return 'Base64CodecError' + (this.message ? ': ' + this.message : ''); }; var assertOrBadInput = function (exp, message) { if (!exp) { throw new Base64CodecError(message) }; }; exports.encode = function (bytes) { assertOrBadInput(!(/[^\x00-\xFF]/.test(bytes)), // disallow two-byte chars 'Input contains out-of-range characters.'); var padding = '\x00\x00\x00'.slice((bytes.length % 3) || 3); bytes += padding; // pad with null bytes var out_array = []; for (var i=0, n=bytes.length; i < n; i+=3) { var newchars = ( (bytes.charCodeAt(i) << 020) + (bytes.charCodeAt(i+1) << 010) + (bytes.charCodeAt(i+2))); out_array.push( alphabet.charAt((newchars >> 18) & 077), alphabet.charAt((newchars >> 12) & 077), alphabet.charAt((newchars >> 6) & 077), alphabet.charAt((newchars) & 077)); }; shorten(out_array, padding.length); return out_array.join(''); }; exports.decode = function (b64text) { sys.puts('decode', b64text); b64text = b64text.replace(/\s/g, '') // kill whitespace // strip trailing pad characters from input; // XXX maybe some better way? var i = b64text.length; while (b64text.charAt(--i) === pad) {}; b64text = b64text.slice(0, i + 1); assertOrBadInput(!alphabet_inverse.test(b64text), 'Input contains out-of-range characters.'); var padding = Array(5 - ((b64text.length % 4) || 4)).join(padChar); b64text += padding; // pad with last letter of alphabet var out_array = []; for (var i=0, n=b64text.length; i < n; i+=4) { newchars = ( (decode_map[b64text.charAt(i)] << 18) + (decode_map[b64text.charAt(i+1)] << 12) + (decode_map[b64text.charAt(i+2)] << 6) + (decode_map[b64text.charAt(i+3)])); out_array.push( (newchars >> 020) & 0xFF, (newchars >> 010) & 0xFF, (newchars) & 0xFF); }; shorten(out_array, padding.length); var result = String.fromCharCode.apply(String, out_array); sys.puts('decoded', result); return result; };
JavaScript
var sys = require('sys'); var fs = require('fs'); var http = require('http'); var url_parse = require("url").parse; var NOT_FOUND = "Not Found\n"; var routes = []; function notFound(req, res, message) { sys.debug("notFound!"); message = message || NOT_FOUND; res.sendHeader(404, [ ["Content-Type", "text/plain"], ["Content-Length", message.length] ]); res.write(message); res.close(); } function addRoute(method, pattern, handler, format) { var route = { method: method, pattern: pattern, handler: handler }; if (format !== undefined) { route.format = format; } routes.push(route); } exports.get = function (pattern, handler) { return addRoute("GET", pattern, handler); }; exports.post = function (pattern, handler, format) { return addRoute("POST", pattern, handler, format); }; exports.put = function (pattern, handler, format) { return addRoute("PUT", pattern, handler, format); }; exports.del = function (pattern, handler) { return addRoute("DELETE", pattern, handler); }; exports.resource = function (name, controller, format) { exports.get(new RegExp('^/' + name + '$'), controller.index); exports.get(new RegExp('^/' + name + '/([^/]+)$'), controller.show); exports.post(new RegExp('^/' + name + '$'), controller.create, format); exports.put(new RegExp('^/' + name + '/([^/]+)$'), controller.update, format); exports.del(new RegExp('^/' + name + '/([^/]+)$'), controller.destroy); }; exports.resourceController = function (name, data, on_change) { data = data || []; on_change = on_change || function () {}; return { index: function (req, res) { res.simpleJson(200, {content: data, self: '/' + name}); }, show: function (req, res, id) { var item = data[id]; if (item) { res.simpleJson(200, {content: item, self: '/' + name + '/' + id}); } else { res.notFound(); } }, create: function (req, res) { req.jsonBody(function (json) { var item, id, url; item = json && json.content; if (!item) { res.notFound(); } else { data.push(item); id = data.length - 1; on_change(id); url = "/" + name + "/" + id; res.simpleJson(201, {content: item, self: url}, [["Location", url]]); } }); }, update: function (req, res, id) { req.jsonBody(function (json) { var item = json && json.content; if (!item) { res.notFound(); } else { data[id] = item; on_change(id); res.simpleJson(200, {content: item, self: "/" + name + "/" + id}); } }); }, destroy: function (req, res, id) { delete(data[id]); on_change(id); res.simpleJson(200, "200 Destroyed"); } }; }; var server = http.createServer(function (req, res) { var uri = url_parse(req.url); var path = uri.pathname; sys.puts(req.method + " " + path); res.simpleText = function (code, body, extra_headers) { res.sendHeader(code, (extra_headers || []).concat( [ ["Content-Type", "text/plain"], ["Content-Length", body.length] ])); res.write(body); res.close(); }; res.simpleHtml = function (code, body, extra_headers) { res.sendHeader(code, (extra_headers || []).concat( [ ["Content-Type", "text/html"], ["Content-Length", body.length] ])); res.write(body); res.close(); }; res.simpleJson = function (code, json, extra_headers) { var body = JSON.stringify(json); res.sendHeader(code, (extra_headers || []).concat( [ ["Content-Type", "application/json"], ["Content-Length", body.length] ])); res.write(body); res.close(); }; res.notFound = function (message) { notFound(req, res, message); }; for (var i = 0, l = routes.length; i < l; i += 1) { var route = routes[i]; if (req.method === route.method) { var match = path.match(route.pattern); if (match && match[0].length > 0) { match.shift(); match = match.map(unescape); match.unshift(res); match.unshift(req); if (route.format !== 'undefined') { var body = ""; req.setBodyEncoding('utf8'); req.addListener('data', function (chunk) { body += chunk; }); req.addListener('end', function () { if (route.format === 'json') { body = JSON.parse(body); } match.push(body); route.handler.apply(null, match); }); return; } route.handler.apply(null, match); return; } } } notFound(req, res); }); exports.listen = function (port, host) { server.listen(port, host); sys.puts("Server at http://" + (host || "127.0.0.1") + ":" + port.toString() + "/"); }; exports.close = function () { server.close(); }; function extname (path) { var index = path.lastIndexOf("."); return index < 0 ? "" : path.substring(index); } exports.staticHandler = function (req, res, filename) { var body, headers; var content_type = exports.mime.lookupExtension(extname(filename)); var encoding = (content_type.slice(0,4) === "text" ? "utf8" : "binary"); function loadResponseData(callback) { if (body && headers) { callback(); return; } fs.readFile(filename, encoding,function(err,data) { if(err)notFound(req, res, "Cannot find file: " + filename); else { body = data; headers = [ [ "Content-Type" , content_type ], [ "Content-Length" , body.length ] ]; headers.push(["Cache-Control", "public"]); callback(); }}); } loadResponseData(function () { res.sendHeader(200, headers); res.write(body, encoding); res.close(); }); }; // stolen from jack- thanks exports.mime = { // returns MIME type for extension, or fallback, or octet-steam lookupExtension : function(ext, fallback) { return exports.mime.TYPES[ext.toLowerCase()] || fallback || 'application/octet-stream'; }, // List of most common mime-types, stolen from Rack. TYPES : { ".3gp" : "video/3gpp", ".a" : "application/octet-stream", ".ai" : "application/postscript", ".aif" : "audio/x-aiff", ".aiff" : "audio/x-aiff", ".asc" : "application/pgp-signature", ".asf" : "video/x-ms-asf", ".asm" : "text/x-asm", ".asx" : "video/x-ms-asf", ".atom" : "application/atom+xml", ".au" : "audio/basic", ".avi" : "video/x-msvideo", ".bat" : "application/x-msdownload", ".bin" : "application/octet-stream", ".bmp" : "image/bmp", ".bz2" : "application/x-bzip2", ".c" : "text/x-c", ".cab" : "application/vnd.ms-cab-compressed", ".cc" : "text/x-c", ".chm" : "application/vnd.ms-htmlhelp", ".class" : "application/octet-stream", ".com" : "application/x-msdownload", ".conf" : "text/plain", ".cpp" : "text/x-c", ".crt" : "application/x-x509-ca-cert", ".css" : "text/css", ".csv" : "text/csv", ".cxx" : "text/x-c", ".deb" : "application/x-debian-package", ".der" : "application/x-x509-ca-cert", ".diff" : "text/x-diff", ".djv" : "image/vnd.djvu", ".djvu" : "image/vnd.djvu", ".dll" : "application/x-msdownload", ".dmg" : "application/octet-stream", ".doc" : "application/msword", ".dot" : "application/msword", ".dtd" : "application/xml-dtd", ".dvi" : "application/x-dvi", ".ear" : "application/java-archive", ".eml" : "message/rfc822", ".eps" : "application/postscript", ".exe" : "application/x-msdownload", ".f" : "text/x-fortran", ".f77" : "text/x-fortran", ".f90" : "text/x-fortran", ".flv" : "video/x-flv", ".for" : "text/x-fortran", ".gem" : "application/octet-stream", ".gemspec" : "text/x-script.ruby", ".gif" : "image/gif", ".gz" : "application/x-gzip", ".h" : "text/x-c", ".hh" : "text/x-c", ".htm" : "text/html", ".html" : "text/html", ".ico" : "image/vnd.microsoft.icon", ".ics" : "text/calendar", ".ifb" : "text/calendar", ".iso" : "application/octet-stream", ".jar" : "application/java-archive", ".java" : "text/x-java-source", ".jnlp" : "application/x-java-jnlp-file", ".jpeg" : "image/jpeg", ".jpg" : "image/jpeg", ".js" : "application/javascript", ".json" : "application/json", ".log" : "text/plain", ".m3u" : "audio/x-mpegurl", ".m4v" : "video/mp4", ".man" : "text/troff", ".mathml" : "application/mathml+xml", ".mbox" : "application/mbox", ".mdoc" : "text/troff", ".me" : "text/troff", ".mid" : "audio/midi", ".midi" : "audio/midi", ".mime" : "message/rfc822", ".mml" : "application/mathml+xml", ".mng" : "video/x-mng", ".mov" : "video/quicktime", ".mp3" : "audio/mpeg", ".mp4" : "video/mp4", ".mp4v" : "video/mp4", ".mpeg" : "video/mpeg", ".mpg" : "video/mpeg", ".ms" : "text/troff", ".msi" : "application/x-msdownload", ".odp" : "application/vnd.oasis.opendocument.presentation", ".ods" : "application/vnd.oasis.opendocument.spreadsheet", ".odt" : "application/vnd.oasis.opendocument.text", ".ogg" : "application/ogg", ".p" : "text/x-pascal", ".pas" : "text/x-pascal", ".pbm" : "image/x-portable-bitmap", ".pdf" : "application/pdf", ".pem" : "application/x-x509-ca-cert", ".pgm" : "image/x-portable-graymap", ".pgp" : "application/pgp-encrypted", ".pkg" : "application/octet-stream", ".pl" : "text/x-script.perl", ".pm" : "text/x-script.perl-module", ".png" : "image/png", ".pnm" : "image/x-portable-anymap", ".ppm" : "image/x-portable-pixmap", ".pps" : "application/vnd.ms-powerpoint", ".ppt" : "application/vnd.ms-powerpoint", ".ps" : "application/postscript", ".psd" : "image/vnd.adobe.photoshop", ".py" : "text/x-script.python", ".qt" : "video/quicktime", ".ra" : "audio/x-pn-realaudio", ".rake" : "text/x-script.ruby", ".ram" : "audio/x-pn-realaudio", ".rar" : "application/x-rar-compressed", ".rb" : "text/x-script.ruby", ".rdf" : "application/rdf+xml", ".roff" : "text/troff", ".rpm" : "application/x-redhat-package-manager", ".rss" : "application/rss+xml", ".rtf" : "application/rtf", ".ru" : "text/x-script.ruby", ".s" : "text/x-asm", ".sgm" : "text/sgml", ".sgml" : "text/sgml", ".sh" : "application/x-sh", ".sig" : "application/pgp-signature", ".snd" : "audio/basic", ".so" : "application/octet-stream", ".svg" : "image/svg+xml", ".svgz" : "image/svg+xml", ".swf" : "application/x-shockwave-flash", ".t" : "text/troff", ".tar" : "application/x-tar", ".tbz" : "application/x-bzip-compressed-tar", ".tci" : "application/x-topcloud", ".tcl" : "application/x-tcl", ".tex" : "application/x-tex", ".texi" : "application/x-texinfo", ".texinfo" : "application/x-texinfo", ".text" : "text/plain", ".tif" : "image/tiff", ".tiff" : "image/tiff", ".torrent" : "application/x-bittorrent", ".tr" : "text/troff", ".txt" : "text/plain", ".vcf" : "text/x-vcard", ".vcs" : "text/x-vcalendar", ".vrml" : "model/vrml", ".war" : "application/java-archive", ".wav" : "audio/x-wav", ".wma" : "audio/x-ms-wma", ".wmv" : "video/x-ms-wmv", ".wmx" : "video/x-ms-wmx", ".wrl" : "model/vrml", ".wsdl" : "application/wsdl+xml", ".xbm" : "image/x-xbitmap", ".xhtml" : "application/xhtml+xml", ".xls" : "application/vnd.ms-excel", ".xml" : "application/xml", ".xpm" : "image/x-xpixmap", ".xsl" : "application/xml", ".xslt" : "application/xslt+xml", ".yaml" : "text/yaml", ".yml" : "text/yaml", ".zip" : "application/zip" } };
JavaScript
// Redis client for Node.js // Author: Brian Hammond <brian at fictorial dot com> // Copyright (C) 2009 Fictorial LLC // License: MIT var sys = require("sys"), tcp = require("tcp"); var crlf = "\r\n", crlf_len = 2; var inline_commands = { auth:1, bgsave:1, dbsize:1, decr:1, decrby:1, del:1, exists:1, expire:1, flushall:1, flushdb:1, get:1, incr:1, incrby:1, info:1, keys:1, lastsave:1, lindex:1, llen:1, lpop:1, lrange:1, ltrim:1, mget:1, move:1, randomkey:1, rename:1, renamenx:1, rpop:1, save:1, scard:1, sdiff:1, sdiffstore:1, select:1, shutdown:1, sinter:1, sinterstore:1, smembers:1, spop:1, srandmember:1, sunion:1, sunionstore:1, ttl:1, type:1, zrange:1, zrevrange:1, zcard:1, zrangebyscore:1, rpoplpush:1 }; var bulk_commands = { getset:1, lpush:1, lrem:1, lset:1, rpush:1, sadd:1, set:1, setnx:1, sismember:1, smove:1, srem:1, zadd:1, zrem:1, zscore:1, }; var multi_bulk_commands = { mset:1, msetnx:1 }; var Client = exports.Client = function (port, host) { process.EventEmitter.call(this); this.host = host || '127.0.0.1'; this.port = port || 6379; this.callbacks = []; this.conn = null; }; // The client emits "connect" when a connection is established, and emits // "close" when a connection is closed (passing boolean true if failed in // error). // // Note that calling a Redis client method when the connection is closed will // automatically attempt to reconnect to Redis first. sys.inherits(Client, process.EventEmitter); // Callback a function after we've ensured we're connected to Redis. Client.prototype.connect = function (callback) { if (!this.conn) { this.conn = new process.tcp.Connection(); } if (this.conn.readyState === "open" && typeof(callback) === 'function') { callback(); } else { var self = this; this.conn.addListener("connect", function () { this.setEncoding("binary"); this.setTimeout(0); // try to stay connected. this.setNoDelay(); self.emit("connect"); if (typeof(callback) === 'function') callback(); }); this.conn.addListener("data", function (data) { if (!self.buffer) self.buffer = ""; self.buffer += data; self.handle_replies(); }); this.conn.addListener("end", function () { if (self.conn && self.conn.readyState) { self.conn.close(); self.conn = null; } }); this.conn.addListener("close", function (encountered_error) { self.conn = null; self.emit("close", encountered_error); }); this.conn.connect(this.port, this.host); } }; Client.prototype.close = function () { if (this.conn && this.conn.readyState === "open") { this.conn.close(); this.conn = null; } }; // Reply handlers read replies from the current reply buffer. At the time of // the call the buffer will start with at least the prefix associated with the // relevant reply type which is at this time always of length 1. // // Note the buffer may not contain a full reply in which case these reply // handlers return null. In this case the buffer is left intact for future // "receive" events to append onto, and the read-replies process repeats. // Repeat ad infinitum. // // Each handler returns [ value, next_command_index ] on success, null on // underflow. var prefix_len = 1; // Bulk replies resemble: // $6\r\nFOOBAR\r\n Client.prototype.handle_bulk_reply = function (start_at, buf) { var buffer = buf || this.buffer; start_at = (start_at || 0) + prefix_len; var crlf_at = buffer.indexOf(crlf, start_at); if (crlf_at === -1) return null; var value_len_str = buffer.substring(start_at, crlf_at); var value_len = parseInt(value_len_str, 10); if (value_len === NaN) throw new Error("invalid bulk value len: " + value_len_str); if (value_len === -1) // value doesn't exist return [ null, crlf_at + crlf_len ]; var value_at = crlf_at + crlf_len; var next_reply_at = value_at + value_len + crlf_len; if (next_reply_at > buffer.length) return null; var value = buffer.substr(value_at, value_len); return [ value, next_reply_at ]; } // Mult-bulk replies resemble: // *4\r\n$3\r\nFOO\r\n$3\r\nBAR\r\n$5\r\nHELLO\r\n$5\r\nWORLD\r\n // *4 is the number of bulk replies to follow. Client.prototype.handle_multi_bulk_reply = function (buf) { var buffer = buf || this.buffer; var crlf_at = buffer.indexOf(crlf, prefix_len); if (crlf_at === -1) return null; var count_str = buffer.substring(prefix_len, crlf_at); var count = parseInt(count_str, 10); if (count === NaN) throw new Error("invalid multi-bulk count: " + count_str); var next_reply_at = crlf_at + crlf_len; if (count === -1) // value doesn't exist return [ null, next_reply_at ]; if (count === 0) return [ [], next_reply_at ]; if (next_reply_at >= buffer.length) return null; var results = []; for (var i = 0; i < count; ++i) { var bulk_reply = this.handle_bulk_reply(next_reply_at, buffer); if (bulk_reply === null) // no full multi-bulk cmd return null; var bulk_reply_value = bulk_reply[0]; results.push(bulk_reply_value); next_reply_at = bulk_reply[1]; } return [ results, next_reply_at ]; }; // Single line replies resemble: // +OK\r\n Client.prototype.handle_single_line_reply = function (buf) { var buffer = buf || this.buffer; var crlf_at = buffer.indexOf(crlf, prefix_len); if (crlf_at === -1) return null; var value = buffer.substring(prefix_len, crlf_at); if (value === 'OK') value = true; var next_reply_at = crlf_at + crlf_len; return [ value, next_reply_at ]; }; // Integer replies resemble: // :1000\r\n Client.prototype.handle_integer_reply = function (buf) { var buffer = buf || this.buffer; var crlf_at = buffer.indexOf(crlf, prefix_len); if (crlf_at === -1) return null; var value_str = buffer.substring(prefix_len, crlf_at); var value = parseInt(value_str, 10); if (value === NaN) throw new Error("invalid integer reply: " + value_str); var next_reply_at = crlf_at + crlf_len; return [ value, next_reply_at ]; }; // Error replies resemble: // -ERR you suck at tennis\r\n Client.prototype.handle_error_reply = function (buf) { var buffer = buf || this.buffer; var crlf_at = buffer.indexOf(crlf, prefix_len); if (crlf_at === -1) return null; var value = buffer.substring(prefix_len, crlf_at); var next_reply_at = crlf_at + crlf_len; if (value.indexOf("ERR ") === 0) value = value.substr("ERR ".length); return [ value, next_reply_at ]; } // Try to read as many replies from the current buffer as we can. Leave // partial replies in the buffer, else eat 'em. Dispatch any promises waiting // for these replies. Error replies emit error on the promise, else success is // emitted. Client.prototype.handle_replies = function () { while (this.buffer.length > 0) { if (GLOBAL.DEBUG) { write_debug('---'); write_debug('buffer: ' + this.buffer); } var prefix = this.buffer.charAt(0); var result, is_error = false; switch (prefix) { case '$': result = this.handle_bulk_reply(); break; case '*': result = this.handle_multi_bulk_reply(); break; case '+': result = this.handle_single_line_reply(); break; case ':': result = this.handle_integer_reply(); break; case '-': result = this.handle_error_reply(); is_error = true; break; } // The handlers return null when there's not enough data // in the buffer to read a full reply. Leave the buffer alone until // we receive more data. if (result === null) break; if (GLOBAL.DEBUG) { write_debug('prefix: ' + prefix); write_debug('result: ' + JSON.stringify(result)); } var next_reply_at = result[1]; this.buffer = this.buffer.substring(next_reply_at); var callback = this.callbacks.shift(); var result_value = result[0]; if( callback.func ) { if (is_error) callback.func(true, result_value); else { result_value = post_process_results(callback.command, result_value); callback.func(false, result_value); } } } }; function write_debug(data) { if (!GLOBAL.DEBUG || !data) return; sys.puts(data.replace(/\r\n/g, '<CRLF>')); } function try_convert_to_number(str) { var value = parseInt(str, 10); if (value === NaN) value = parseFloat(str); if (value === NaN) return str; return value; } function format_inline(name, args) { var command = name; for (var arg in args) command += ' ' + args[arg].toString(); return command + crlf; } function format_bulk_command(name, args) { var output = name; for (var i = 0; i < args.length - 1; ++i) output += ' ' + args[i].toString(); var last_arg = args[args.length - 1].toString(); return output + ' ' + last_arg.length + crlf + last_arg + crlf; } function format_multi_bulk_command(name, args) { var output = '*' + (args.length + 1) + crlf + '$' + name.length + crlf + name + crlf; for (var i = 0; i < args.length; ++i) { var arg_as_str = args[i].toString(); output += '$' + arg_as_str.length + crlf + arg_as_str + crlf; } return output; } function make_command_sender(name) { Client.prototype[name] = function () { if (GLOBAL.DEBUG) { var description = "client." + name + "( "; for (var a in arguments) description += "'" + arguments[a] + "',"; description = description.substr(0, description.length - 1) + " )"; } var actual_callback = null; var args = arguments; if( typeof( arguments[arguments.length-1] ) === "function" ) { actual_callback = arguments[arguments.length-1]; [].pop.call(args); } var self = this; this.connect(function () { var command; if (inline_commands[name]) command = format_inline(name, args); else if (bulk_commands[name]) command = format_bulk_command(name, args); else if (multi_bulk_commands[name]) command = format_multi_bulk_command(name, args); else throw new Error('unknown command type for "' + name + '"'); if (GLOBAL.DEBUG) { write_debug("---"); write_debug("call: " + description); write_debug("command:" + command); } self.callbacks.push({ command:name.toLowerCase(), func: actual_callback }); self.conn.write(command); }); }; } for (var name in inline_commands) make_command_sender(name); for (var name in bulk_commands) make_command_sender(name); for (var name in multi_bulk_commands) make_command_sender(name); function post_process_results(command, result) { var new_result = result; switch (command) { case 'info': var info = {}; result.split(/\r\n/g).forEach(function (line) { var parts = line.split(':'); if (parts.length === 2) info[parts[0]] = try_convert_to_number(parts[1]); }); new_result = info; break; case 'keys': new_result = result.split(' '); break; case 'lastsave': case 'scard': case 'zcard': case 'zscore': new_result = try_convert_to_number(result); break; default: break; } return new_result; } // Read this: http://code.google.com/p/redis/wiki/SortCommand // 'key' is what to sort, 'options' is how to sort. // 'options' is an object with optional properties: // 'by_pattern': 'pattern' // 'limit': [start, end] // 'get_patterns': [ 'pattern', 'pattern', ... ] // 'ascending': true|false // 'lexicographically': true|false // 'store_key': 'a_key_name' Client.prototype.sort = function (key, options, func) { var self = this; this.connect(function () { var opts = []; if (typeof(options) == 'object') { if (options.by_pattern) opts.push('by ' + options.by_pattern); if (options.get_patterns) { options.get_patterns.forEach(function (pat) { opts.push('get ' + pat); }); } if (!options.ascending) opts.push('desc'); if (options.lexicographically) opts.push('alpha'); if (options.store_key) opts.push('store ' + options.store_key); if (options.limit) opts.push('limit ' + options.limit[0] + ' ' + options.limit[1]); } var command = 'sort ' + key + ' ' + opts.join(' ') + crlf; write_debug("call: client.sort(...)\ncommand: " + command); self.callbacks.push({ command:'sort', func: func }); self.conn.write(command); }); } Client.prototype.quit = function () { if (this.conn.readyState != "open") { this.conn.close(); } else { this.conn.write('quit' + crlf); this.conn.close(); } }; Client.prototype.make_master = function (func) { var self = this; this.connect(function () { self.callbacks.push({ command:'slaveof', func: func}); self.conn.write('slaveof no one'); }); }; Client.prototype.make_slave_of = function (host, port, func) { var self = this; this.connect(function () { port = port || 6379; var command = 'slaveof ' + host + ' ' + port; self.callbacks.push({ command:'slaveof', func: func }); self.conn.write(command); }); };
JavaScript
var http = require('http'); var multipart = require('multipart'); var redis = require("./redisclient"); var sys = require('sys'); var url = require('url'); var server = require('./node-router'); var base64 = require('./base64'); var fs = require("fs"); function logon(req, res, match) { var image=""; req.setBodyEncoding('binary'); req.addListener('data', function(chunk) { sys.print("Uploading "+chunk); image+=chunk; }); req.addListener('end', function() { var redis_client1 = new redis.Client(); redis_client1.incr('user_counter',function(err,value){ redis_client1.close(); if(err) show_404(req,res,err);else{ show_result(req,res,value); sys.puts(value); } var redis_client2 = new redis.Client(); redis_client2.sadd('user_presences',value,function(err,v){ if(!err) sys.puts("saved presence for user "+value+":"+v); redis_client2.close(); }); }); }); } function logon_img_static(req, res, match) { var file=null; var temp_file='x'+(new Date())+'.jpeg'; req.setBodyEncoding('binary'); req.addListener('data', function(chunk) { sys.puts("Uploading "+chunk); var write=function(err,fileDescriptor){if(!err){req.pause();fs.write(fileDescriptor,chunk);req.resume();}}; if(file == null){sys.puts("Opening file");file = fs.open(temp_file, process.O_CREAT | process.O_WRONLY, 0600,write);} else write(null,file); }); req.addListener('end', function() { var redis_client1 = new redis.Client(); if(file)fs.close(file); redis_client1.incr('user_counter',function(err,value){ redis_client1.close(); if(err)show_404(req,res,err);else { show_result(req,res,value); var redis_client2 = new redis.Client(); redis_client2.sadd('user_presences',value,function(err,v){ if(!err)sys.puts("saved presence for user "+value+":"+v); redis_client2.close(); }); }; fs.rename(temp_file,''+value+'.jpeg'); }); }); } function logon_img(req, res, match) { var image=""; req.setBodyEncoding('binary'); req.addListener('data', function(chunk) { sys.print("Uploading "+chunk); image+=chunk; }); req.addListener('end', function() { var redis_client1 = new redis.Client(); redis_client1.incr('user_counter',function(err,value){ redis_client1.close(); if(err) show_404(req,res); else { show_result(req,res,value); var redis_client2 = new redis.Client(); redis_client2.sadd('user_presences',value,function(err,v){ if(!err)sys.puts("saved presence for user "+value+":"+v); redis_client2.close(); }); }; //save image if(""!=image){ redis_client3 = new redis.Client(); var image_str=base64.encode(image); redis_client3.set('user_image_'+value,image_str,function(err,r){ if(!err)sys.puts("saved image for user "+value+":"+r); redis_client3.close(); }); } }); }); } function logoff(req, res, match) { var q=url.parse(req.url,true).query; if(q&&q.myID){ var redis_client = new redis.Client(); redis_client.srem('user_presences',q.myID,function(err,value){ redis_client.close(); if(err) show_404(req,res,err); else show_result(req,res,value); }); } } function next(req, res, match) { var redis_client1 = new redis.Client(); redis_client1.srandmember('user_presences',function(err,value){ redis_client1.close(); if(err)show_404(req,res,err); else { show_result(req,res,value); sys.puts('next:'+value); } }); } function next_img_static(req, res, match) { var redis_client1 = new redis.Client(); redis_client1.srandmember('user_presences',function(err,value){ redis_client1.close(); if(err) show_404(req,res); else { sys.puts('next:'+value); server.staticHandler(req,res,''+value+'.jpeg'); }; }); } function next_img(req, res, match) { var redis_client1 = new redis.Client(); redis_client1.srandmember('user_presences',function(err,value){ redis_client1.close(); if(err)show_404(req,res,err); else { sys.puts('next:'+value); var redis_client2 = new redis.Client(); redis_client2.get('user_image_'+random,function(err,value){ redis_client2.close(); if(err)show_404(req,res,err); else{ var image_bin=base64.decode(value); show_image(req,res,image_bin); } }); } }); } function message(req, res, match) { var txt=''; req.addListener('data', function(chunk) { sys.puts('message-chunk:'+chunk); txt+=chunk; }); req.addListener('end', function() { var q=url.parse(req.url,true).query; if(txt==''&&q.txt)txt=q.txt; sys.puts('try to send '+q.fromID+'->'+q.toID+':'+txt); var redis_client = new redis.Client(); redis_client.set('user_message_'+q.toID,q.fromID+':'+txt,function(err,value){ redis_client.close(); if(err)show_404(req,res,err); else { show_result(req,res,'OK'); sys.puts('done:'+q.fromID+'->'+q.toID+':'+txt); } }); }); } function poll(req, res, match) { var q=url.parse(req.url,true).query; var redis_client = new redis.Client(); redis_client.get('user_message_'+q.myID,function(err,value){ redis_client.close(); if(err)show_404(req,res,err); else { if(value)show_result(req,res,value);else show_204(req,res,''); sys.puts('poll:'+q.myID+':'+(value?value:'204')); } }); } function image(req, res, match){ var q=url.parse(req.url,true).query; server.staticHandler(req,res,''+q.myID+'.jpeg'); } server.get(new RegExp("^/logon$"), logon); server.post(new RegExp("^/logon$"), logon); server.get(new RegExp("^/logoff$"), logoff); server.post(new RegExp("^/logoff$"), logoff); server.get(new RegExp("^/logon-img$"), logon_img); server.post(new RegExp("^/logon-img$"), logon_img); server.get(new RegExp("^/logon-img-static$"),logon_img_static); server.post(new RegExp("^/logon-img-static$"),logon_img_static); server.get(new RegExp("^/next$"), next); server.post(new RegExp("^/next$"), next); server.get(new RegExp("^/next-img$"), next_img); server.post(new RegExp("^/next-img$"), next_img); server.get(new RegExp("^/next-img-static$"),next_img_static); server.post(new RegExp("^/next-img-static$"),next_img_static); server.get(new RegExp("^/message$"), message); server.post(new RegExp("^/message$"), message); server.get(new RegExp("^/poll$"), poll); server.post(new RegExp("^/poll$"), poll); server.get(new RegExp("^/image"), image); server.post(new RegExp("^/image"), image); server.listen(8000); function show_result(req, res, txt) {txt=""+(txt||""); res.sendHeader(200, {'Content-Type': 'text/plain','Content-Length': txt.length}); res.write(""+txt); res.close(); sys.puts('response,closed:'+txt); } function show_image(req, res, img) {img=""+(img||""); res.sendHeader(200, {'Content-Type': 'image/jpeg','Content-Length': img.length}); res.write(""+img); res.close(); sys.puts('response,closed:'+img); } function show_404(req, res, error) {error=""+(error||"ERROR"); res.sendHeader(404, {'Content-Type': 'text/plain','Content-Length': error.length}); res.write(error); res.close(); sys.puts('response,closed:'+error); } function show_204(req, res, error) {error=""+(error||""); res.sendHeader(204, {'Content-Type': 'text/plain','Content-Length': error.length}); res.write(error); res.close(); sys.puts('response,closed:'+error); }
JavaScript
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ var swfobject = function() { var UNDEF = "undefined", OBJECT = "object", SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", EXPRESS_INSTALL_ID = "SWFObjectExprInst", ON_READY_STATE_CHANGE = "onreadystatechange", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], regObjArr = [], objIdArr = [], listenersArr = [], storedAltContent, storedAltContentId, storedCallbackFn, storedCallbackObj, isDomLoaded = false, isExpressInstallActive = false, dynamicStylesheet, dynamicStylesheetMedia, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(), /* Cross-browser onDomLoad - Will fire an event as soon as the DOM of a web page is loaded - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/ - Regular onload serves as fallback */ onDomLoad = function() { if (!ua.w3) { return; } if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically callDomLoadFunctions(); } if (!isDomLoaded) { if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false); } if (ua.ie && ua.win) { doc.attachEvent(ON_READY_STATE_CHANGE, function() { if (doc.readyState == "complete") { doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee); callDomLoadFunctions(); } }); if (win == top) { // if not inside an iframe (function(){ if (isDomLoaded) { return; } try { doc.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } } if (ua.wk) { (function(){ if (isDomLoaded) { return; } if (!/loaded|complete/.test(doc.readyState)) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } addLoadEvent(callDomLoadFunctions); } }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span")); t.parentNode.removeChild(t); } catch (e) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Cross-browser onload - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/ - Will fire an event as soon as a web page including all of its assets are loaded */ function addLoadEvent(fn) { if (typeof win.addEventListener != UNDEF) { win.addEventListener("load", fn, false); } else if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("load", fn, false); } else if (typeof win.attachEvent != UNDEF) { addListener(win, "onload", fn); } else if (typeof win.onload == "function") { var fnOld = win.onload; win.onload = function() { fnOld(); fn(); }; } else { win.onload = fn; } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } else { matchVersions(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; matchVersions(); })(); } else { matchVersions(); } } /* Perform Flash Player and SWF version matching; static publishing only */ function matchVersions() { var rl = regObjArr.length; if (rl > 0) { for (var i = 0; i < rl; i++) { // for each registered object element var id = regObjArr[i].id; var cb = regObjArr[i].callbackFn; var cbObj = {success:false, id:id}; if (ua.pv[0] > 0) { var obj = getElementById(id); if (obj) { if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match! setVisibility(id, true); if (cb) { cbObj.success = true; cbObj.ref = getObjectById(id); cb(cbObj); } } else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported var att = {}; att.data = regObjArr[i].expressInstall; att.width = obj.getAttribute("width") || "0"; att.height = obj.getAttribute("height") || "0"; if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); } if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); } // parse HTML object param element's name-value pairs var par = {}; var p = obj.getElementsByTagName("param"); var pl = p.length; for (var j = 0; j < pl; j++) { if (p[j].getAttribute("name").toLowerCase() != "movie") { par[p[j].getAttribute("name")] = p[j].getAttribute("value"); } } showExpressInstall(att, par, id, cb); } else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF displayAltContent(obj); if (cb) { cb(cbObj); } } } } else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content) setVisibility(id, true); if (cb) { var o = getObjectById(id); // test whether there is an HTML object element or not if (o && typeof o.SetVariable != UNDEF) { cbObj.success = true; cbObj.ref = o; } cb(cbObj); } } } } } function getObjectById(objectIdStr) { var r = null; var o = getElementById(objectIdStr); if (o && o.nodeName == "OBJECT") { if (typeof o.SetVariable != UNDEF) { r = o; } else { var n = o.getElementsByTagName(OBJECT)[0]; if (n) { r = n; } } } return r; } /* Requirements for Adobe Express Install - only one instance can be active at a time - fp 6.0.65 or higher - Win/Mac OS only - no Webkit engines older than version 312 */ function canExpressInstall() { return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312); } /* Show the Adobe Express Install dialog - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75 */ function showExpressInstall(att, par, replaceElemIdStr, callbackFn) { isExpressInstallActive = true; storedCallbackFn = callbackFn || null; storedCallbackObj = {success:false, id:replaceElemIdStr}; var obj = getElementById(replaceElemIdStr); if (obj) { if (obj.nodeName == "OBJECT") { // static publishing storedAltContent = abstractAltContent(obj); storedAltContentId = null; } else { // dynamic publishing storedAltContent = obj; storedAltContentId = replaceElemIdStr; } att.id = EXPRESS_INSTALL_ID; if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; } if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; } doc.title = doc.title.slice(0, 47) + " - Flash Player Installation"; var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn", fv = "MMredirectURL=" + encodeURI(window.location).toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title; if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + fv; } else { par.flashvars = fv; } // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work if (ua.ie && ua.win && obj.readyState != 4) { var newObj = createElement("div"); replaceElemIdStr += "SWFObjectNew"; newObj.setAttribute("id", replaceElemIdStr); obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } createSWF(att, par, replaceElemIdStr); } } /* Functions to abstract and display alternative content */ function displayAltContent(obj) { if (ua.ie && ua.win && obj.readyState != 4) { // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work var el = createElement("div"); obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content el.parentNode.replaceChild(abstractAltContent(obj), el); obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.replaceChild(abstractAltContent(obj), obj); } } function abstractAltContent(obj) { var ac = createElement("div"); if (ua.win && ua.ie) { ac.innerHTML = obj.innerHTML; } else { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var i = 0; i < cl; i++) { if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) { ac.appendChild(c[i].cloneNode(true)); } } } } } return ac; } /* Cross-browser dynamic SWF creation */ function createSWF(attObj, parObj, id) { var r, el = getElementById(id); if (ua.wk && ua.wk < 312) { return r; } if (el) { if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content attObj.id = id; } if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML var att = ""; for (var i in attObj) { if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries if (i.toLowerCase() == "data") { parObj.movie = attObj[i]; } else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword att += ' class="' + attObj[i] + '"'; } else if (i.toLowerCase() != "classid") { att += ' ' + i + '="' + attObj[i] + '"'; } } } var par = ""; for (var j in parObj) { if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries par += '<param name="' + j + '" value="' + parObj[j] + '" />'; } } el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>'; objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only) r = getElementById(attObj.id); } else { // well-behaving browsers var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); for (var m in attObj) { if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword o.setAttribute("class", attObj[m]); } else if (m.toLowerCase() != "classid") { // filter out IE specific attribute o.setAttribute(m, attObj[m]); } } } for (var n in parObj) { if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element createObjParam(o, n, parObj[n]); } } el.parentNode.replaceChild(o, el); r = o; } } return r; } function createObjParam(el, pName, pValue) { var p = createElement("param"); p.setAttribute("name", pName); p.setAttribute("value", pValue); el.appendChild(p); } /* Cross-browser SWF removal - Especially needed to safely and completely remove a SWF in Internet Explorer */ function removeSWF(id) { var obj = getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (ua.ie && ua.win) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } } function removeObjectInIE(id) { var obj = getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } /* Functions to optimize JavaScript compression */ function getElementById(id) { var el = null; try { el = doc.getElementById(id); } catch (e) {} return el; } function createElement(el) { return doc.createElement(el); } /* Updated attachEvent function for Internet Explorer - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks */ function addListener(target, eventType, fn) { target.attachEvent(eventType, fn); listenersArr[listenersArr.length] = [target, eventType, fn]; } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } /* Cross-browser dynamic CSS creation - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php */ function createCSS(sel, decl, media, newStyle) { if (ua.ie && ua.mac) { return; } var h = doc.getElementsByTagName("head")[0]; if (!h) { return; } // to also support badly authored HTML pages that lack a head element var m = (media && typeof media == "string") ? media : "screen"; if (newStyle) { dynamicStylesheet = null; dynamicStylesheetMedia = null; } if (!dynamicStylesheet || dynamicStylesheetMedia != m) { // create dynamic stylesheet + get a global reference to it var s = createElement("style"); s.setAttribute("type", "text/css"); s.setAttribute("media", m); dynamicStylesheet = h.appendChild(s); if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) { dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1]; } dynamicStylesheetMedia = m; } // add style rule if (ua.ie && ua.win) { if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) { dynamicStylesheet.addRule(sel, decl); } } else { if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) { dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}")); } } } function setVisibility(id, isVisible) { if (!autoHideShow) { return; } var v = isVisible ? "visible" : "hidden"; if (isDomLoaded && getElementById(id)) { getElementById(id).style.visibility = v; } else { createCSS("#" + id, "visibility:" + v); } } /* Filter to avoid XSS attacks */ function urlEncodeIfNecessary(s) { var regex = /[\\\"<>\.;]/; var hasBadChars = regex.exec(s) != null; return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s; } /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only) */ var cleanup = function() { if (ua.ie && ua.win) { window.attachEvent("onunload", function() { // remove listeners to avoid memory leaks var ll = listenersArr.length; for (var i = 0; i < ll; i++) { listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]); } // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect var il = objIdArr.length; for (var j = 0; j < il; j++) { removeSWF(objIdArr[j]); } // cleanup library's main closures to avoid memory leaks for (var k in ua) { ua[k] = null; } ua = null; for (var l in swfobject) { swfobject[l] = null; } swfobject = null; }); } }(); return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) { if (ua.w3 && objectIdStr && swfVersionStr) { var regObj = {}; regObj.id = objectIdStr; regObj.swfVersion = swfVersionStr; regObj.expressInstall = xiSwfUrlStr; regObj.callbackFn = callbackFn; regObjArr[regObjArr.length] = regObj; setVisibility(objectIdStr, false); } else if (callbackFn) { callbackFn({success:false, id:objectIdStr}); } }, getObjectById: function(objectIdStr) { if (ua.w3) { return getObjectById(objectIdStr); } }, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var callbackObj = {success:false, id:replaceElemIdStr}; if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) { setVisibility(replaceElemIdStr, false); addDomLoadEvent(function() { widthStr += ""; // auto-convert to string heightStr += ""; var att = {}; if (attObj && typeof attObj === OBJECT) { for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs att[i] = attObj[i]; } } att.data = swfUrlStr; att.width = widthStr; att.height = heightStr; var par = {}; if (parObj && typeof parObj === OBJECT) { for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs par[j] = parObj[j]; } } if (flashvarsObj && typeof flashvarsObj === OBJECT) { for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + k + "=" + flashvarsObj[k]; } else { par.flashvars = k + "=" + flashvarsObj[k]; } } } if (hasPlayerVersion(swfVersionStr)) { // create SWF var obj = createSWF(att, par, replaceElemIdStr); if (att.id == replaceElemIdStr) { setVisibility(replaceElemIdStr, true); } callbackObj.success = true; callbackObj.ref = obj; } else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install att.data = xiSwfUrlStr; showExpressInstall(att, par, replaceElemIdStr, callbackFn); return; } else { // show alternative content setVisibility(replaceElemIdStr, true); } if (callbackFn) { callbackFn(callbackObj); } }); } else if (callbackFn) { callbackFn(callbackObj); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) { if (ua.w3 && canExpressInstall()) { showExpressInstall(att, par, replaceElemIdStr, callbackFn); } }, removeSWF: function(objElemIdStr) { if (ua.w3) { removeSWF(objElemIdStr); } }, createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) { if (ua.w3) { createCSS(selStr, declStr, mediaStr, newStyleBoolean); } }, addDomLoadEvent: addDomLoadEvent, addLoadEvent: addLoadEvent, getQueryParamValue: function(param) { var q = doc.location.search || doc.location.hash; if (q) { if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark if (param == null) { return urlEncodeIfNecessary(q); } var pairs = q.split("&"); for (var i = 0; i < pairs.length; i++) { if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) { return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1))); } } } return ""; }, // For internal usage only expressInstallCallback: function() { if (isExpressInstallActive) { var obj = getElementById(EXPRESS_INSTALL_ID); if (obj && storedAltContent) { obj.parentNode.replaceChild(storedAltContent, obj); if (storedAltContentId) { setVisibility(storedAltContentId, true); if (ua.ie && ua.win) { storedAltContent.style.display = "block"; } } if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); } } isExpressInstallActive = false; } } }; }();
JavaScript
var total;//定义flash影片总桢数 var frame_number;//定义flash影片当前桢数 //以下是滚动条图片拖动程序 var dragapproved=false; var z,x,y var movie = document.getElementById('movie'); //动态显示播放影片的当前桢/总桢数(进度条显示) function showcount(){ //已测可用CallJava.consoleFlashProgress(5); total = movie.TotalFrames; frame_number=movie.CurrentFrame(); frame_number++; var progressSize = 100*(frame_number/movie.TotalFrames()); CallJava.consoleFlashProgress(progressSize); } //播放影片 function Play(){ movie.Play(); } //暂停播放 function Pause(){ movie.StopPlay(); } //开始载入flash影片 function loadSWF(fsrc,fwidth,fheight){ movie.LoadMovie(0, fsrc); movie.width=fwidth; movie.height=fheight; frame_number=movie.CurrentFrame(); }
JavaScript
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ var swfobject = function() { var UNDEF = "undefined", OBJECT = "object", SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", EXPRESS_INSTALL_ID = "SWFObjectExprInst", ON_READY_STATE_CHANGE = "onreadystatechange", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], regObjArr = [], objIdArr = [], listenersArr = [], storedAltContent, storedAltContentId, storedCallbackFn, storedCallbackObj, isDomLoaded = false, isExpressInstallActive = false, dynamicStylesheet, dynamicStylesheetMedia, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(), /* Cross-browser onDomLoad - Will fire an event as soon as the DOM of a web page is loaded - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/ - Regular onload serves as fallback */ onDomLoad = function() { if (!ua.w3) { return; } if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically callDomLoadFunctions(); } if (!isDomLoaded) { if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false); } if (ua.ie && ua.win) { doc.attachEvent(ON_READY_STATE_CHANGE, function() { if (doc.readyState == "complete") { doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee); callDomLoadFunctions(); } }); if (win == top) { // if not inside an iframe (function(){ if (isDomLoaded) { return; } try { doc.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } } if (ua.wk) { (function(){ if (isDomLoaded) { return; } if (!/loaded|complete/.test(doc.readyState)) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } addLoadEvent(callDomLoadFunctions); } }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span")); t.parentNode.removeChild(t); } catch (e) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Cross-browser onload - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/ - Will fire an event as soon as a web page including all of its assets are loaded */ function addLoadEvent(fn) { if (typeof win.addEventListener != UNDEF) { win.addEventListener("load", fn, false); } else if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("load", fn, false); } else if (typeof win.attachEvent != UNDEF) { addListener(win, "onload", fn); } else if (typeof win.onload == "function") { var fnOld = win.onload; win.onload = function() { fnOld(); fn(); }; } else { win.onload = fn; } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } else { matchVersions(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; matchVersions(); })(); } else { matchVersions(); } } /* Perform Flash Player and SWF version matching; static publishing only */ function matchVersions() { var rl = regObjArr.length; if (rl > 0) { for (var i = 0; i < rl; i++) { // for each registered object element var id = regObjArr[i].id; var cb = regObjArr[i].callbackFn; var cbObj = {success:false, id:id}; if (ua.pv[0] > 0) { var obj = getElementById(id); if (obj) { if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match! setVisibility(id, true); if (cb) { cbObj.success = true; cbObj.ref = getObjectById(id); cb(cbObj); } } else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported var att = {}; att.data = regObjArr[i].expressInstall; att.width = obj.getAttribute("width") || "0"; att.height = obj.getAttribute("height") || "0"; if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); } if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); } // parse HTML object param element's name-value pairs var par = {}; var p = obj.getElementsByTagName("param"); var pl = p.length; for (var j = 0; j < pl; j++) { if (p[j].getAttribute("name").toLowerCase() != "movie") { par[p[j].getAttribute("name")] = p[j].getAttribute("value"); } } showExpressInstall(att, par, id, cb); } else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF displayAltContent(obj); if (cb) { cb(cbObj); } } } } else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content) setVisibility(id, true); if (cb) { var o = getObjectById(id); // test whether there is an HTML object element or not if (o && typeof o.SetVariable != UNDEF) { cbObj.success = true; cbObj.ref = o; } cb(cbObj); } } } } } function getObjectById(objectIdStr) { var r = null; var o = getElementById(objectIdStr); if (o && o.nodeName == "OBJECT") { if (typeof o.SetVariable != UNDEF) { r = o; } else { var n = o.getElementsByTagName(OBJECT)[0]; if (n) { r = n; } } } return r; } /* Requirements for Adobe Express Install - only one instance can be active at a time - fp 6.0.65 or higher - Win/Mac OS only - no Webkit engines older than version 312 */ function canExpressInstall() { return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312); } /* Show the Adobe Express Install dialog - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75 */ function showExpressInstall(att, par, replaceElemIdStr, callbackFn) { isExpressInstallActive = true; storedCallbackFn = callbackFn || null; storedCallbackObj = {success:false, id:replaceElemIdStr}; var obj = getElementById(replaceElemIdStr); if (obj) { if (obj.nodeName == "OBJECT") { // static publishing storedAltContent = abstractAltContent(obj); storedAltContentId = null; } else { // dynamic publishing storedAltContent = obj; storedAltContentId = replaceElemIdStr; } att.id = EXPRESS_INSTALL_ID; if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; } if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; } doc.title = doc.title.slice(0, 47) + " - Flash Player Installation"; var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn", fv = "MMredirectURL=" + encodeURI(window.location).toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title; if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + fv; } else { par.flashvars = fv; } // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work if (ua.ie && ua.win && obj.readyState != 4) { var newObj = createElement("div"); replaceElemIdStr += "SWFObjectNew"; newObj.setAttribute("id", replaceElemIdStr); obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } createSWF(att, par, replaceElemIdStr); } } /* Functions to abstract and display alternative content */ function displayAltContent(obj) { if (ua.ie && ua.win && obj.readyState != 4) { // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work var el = createElement("div"); obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content el.parentNode.replaceChild(abstractAltContent(obj), el); obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.replaceChild(abstractAltContent(obj), obj); } } function abstractAltContent(obj) { var ac = createElement("div"); if (ua.win && ua.ie) { ac.innerHTML = obj.innerHTML; } else { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var i = 0; i < cl; i++) { if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) { ac.appendChild(c[i].cloneNode(true)); } } } } } return ac; } /* Cross-browser dynamic SWF creation */ function createSWF(attObj, parObj, id) { var r, el = getElementById(id); if (ua.wk && ua.wk < 312) { return r; } if (el) { if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content attObj.id = id; } if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML var att = ""; for (var i in attObj) { if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries if (i.toLowerCase() == "data") { parObj.movie = attObj[i]; } else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword att += ' class="' + attObj[i] + '"'; } else if (i.toLowerCase() != "classid") { att += ' ' + i + '="' + attObj[i] + '"'; } } } var par = ""; for (var j in parObj) { if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries par += '<param name="' + j + '" value="' + parObj[j] + '" />'; } } el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>'; objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only) r = getElementById(attObj.id); } else { // well-behaving browsers var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); for (var m in attObj) { if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword o.setAttribute("class", attObj[m]); } else if (m.toLowerCase() != "classid") { // filter out IE specific attribute o.setAttribute(m, attObj[m]); } } } for (var n in parObj) { if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element createObjParam(o, n, parObj[n]); } } el.parentNode.replaceChild(o, el); r = o; } } return r; } function createObjParam(el, pName, pValue) { var p = createElement("param"); p.setAttribute("name", pName); p.setAttribute("value", pValue); el.appendChild(p); } /* Cross-browser SWF removal - Especially needed to safely and completely remove a SWF in Internet Explorer */ function removeSWF(id) { var obj = getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (ua.ie && ua.win) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } } function removeObjectInIE(id) { var obj = getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } /* Functions to optimize JavaScript compression */ function getElementById(id) { var el = null; try { el = doc.getElementById(id); } catch (e) {} return el; } function createElement(el) { return doc.createElement(el); } /* Updated attachEvent function for Internet Explorer - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks */ function addListener(target, eventType, fn) { target.attachEvent(eventType, fn); listenersArr[listenersArr.length] = [target, eventType, fn]; } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } /* Cross-browser dynamic CSS creation - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php */ function createCSS(sel, decl, media, newStyle) { if (ua.ie && ua.mac) { return; } var h = doc.getElementsByTagName("head")[0]; if (!h) { return; } // to also support badly authored HTML pages that lack a head element var m = (media && typeof media == "string") ? media : "screen"; if (newStyle) { dynamicStylesheet = null; dynamicStylesheetMedia = null; } if (!dynamicStylesheet || dynamicStylesheetMedia != m) { // create dynamic stylesheet + get a global reference to it var s = createElement("style"); s.setAttribute("type", "text/css"); s.setAttribute("media", m); dynamicStylesheet = h.appendChild(s); if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) { dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1]; } dynamicStylesheetMedia = m; } // add style rule if (ua.ie && ua.win) { if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) { dynamicStylesheet.addRule(sel, decl); } } else { if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) { dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}")); } } } function setVisibility(id, isVisible) { if (!autoHideShow) { return; } var v = isVisible ? "visible" : "hidden"; if (isDomLoaded && getElementById(id)) { getElementById(id).style.visibility = v; } else { createCSS("#" + id, "visibility:" + v); } } /* Filter to avoid XSS attacks */ function urlEncodeIfNecessary(s) { var regex = /[\\\"<>\.;]/; var hasBadChars = regex.exec(s) != null; return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s; } /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only) */ var cleanup = function() { if (ua.ie && ua.win) { window.attachEvent("onunload", function() { // remove listeners to avoid memory leaks var ll = listenersArr.length; for (var i = 0; i < ll; i++) { listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]); } // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect var il = objIdArr.length; for (var j = 0; j < il; j++) { removeSWF(objIdArr[j]); } // cleanup library's main closures to avoid memory leaks for (var k in ua) { ua[k] = null; } ua = null; for (var l in swfobject) { swfobject[l] = null; } swfobject = null; }); } }(); return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) { if (ua.w3 && objectIdStr && swfVersionStr) { var regObj = {}; regObj.id = objectIdStr; regObj.swfVersion = swfVersionStr; regObj.expressInstall = xiSwfUrlStr; regObj.callbackFn = callbackFn; regObjArr[regObjArr.length] = regObj; setVisibility(objectIdStr, false); } else if (callbackFn) { callbackFn({success:false, id:objectIdStr}); } }, getObjectById: function(objectIdStr) { if (ua.w3) { return getObjectById(objectIdStr); } }, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var callbackObj = {success:false, id:replaceElemIdStr}; if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) { setVisibility(replaceElemIdStr, false); addDomLoadEvent(function() { widthStr += ""; // auto-convert to string heightStr += ""; var att = {}; if (attObj && typeof attObj === OBJECT) { for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs att[i] = attObj[i]; } } att.data = swfUrlStr; att.width = widthStr; att.height = heightStr; var par = {}; if (parObj && typeof parObj === OBJECT) { for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs par[j] = parObj[j]; } } if (flashvarsObj && typeof flashvarsObj === OBJECT) { for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + k + "=" + flashvarsObj[k]; } else { par.flashvars = k + "=" + flashvarsObj[k]; } } } if (hasPlayerVersion(swfVersionStr)) { // create SWF var obj = createSWF(att, par, replaceElemIdStr); if (att.id == replaceElemIdStr) { setVisibility(replaceElemIdStr, true); } callbackObj.success = true; callbackObj.ref = obj; } else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install att.data = xiSwfUrlStr; showExpressInstall(att, par, replaceElemIdStr, callbackFn); return; } else { // show alternative content setVisibility(replaceElemIdStr, true); } if (callbackFn) { callbackFn(callbackObj); } }); } else if (callbackFn) { callbackFn(callbackObj); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) { if (ua.w3 && canExpressInstall()) { showExpressInstall(att, par, replaceElemIdStr, callbackFn); } }, removeSWF: function(objElemIdStr) { if (ua.w3) { removeSWF(objElemIdStr); } }, createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) { if (ua.w3) { createCSS(selStr, declStr, mediaStr, newStyleBoolean); } }, addDomLoadEvent: addDomLoadEvent, addLoadEvent: addLoadEvent, getQueryParamValue: function(param) { var q = doc.location.search || doc.location.hash; if (q) { if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark if (param == null) { return urlEncodeIfNecessary(q); } var pairs = q.split("&"); for (var i = 0; i < pairs.length; i++) { if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) { return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1))); } } } return ""; }, // For internal usage only expressInstallCallback: function() { if (isExpressInstallActive) { var obj = getElementById(EXPRESS_INSTALL_ID); if (obj && storedAltContent) { obj.parentNode.replaceChild(storedAltContent, obj); if (storedAltContentId) { setVisibility(storedAltContentId, true); if (ua.ie && ua.win) { storedAltContent.style.display = "block"; } } if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); } } isExpressInstallActive = false; } } }; }();
JavaScript
$("#page1").live("pageinit",function() { $("#btn_next1").bind("click", function() { Helper.hideHelper(); }); });
JavaScript
(function() { // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ function isEventSupported(eventName) { var el = document.createElement('div'); eventName = 'on' + eventName; var isSupported = (eventName in el); if (!isSupported) { el.setAttribute(eventName, 'return;'); isSupported = typeof el[eventName] == 'function'; } el = null; return isSupported; } function isForm(element) { return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM' } function isInput(element) { if (Object.isElement(element)) { var name = element.nodeName.toUpperCase() return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA' } else return false } var submitBubbles = isEventSupported('submit'), changeBubbles = isEventSupported('change') if (!submitBubbles || !changeBubbles) { // augment the Event.Handler class to observe custom events when needed Event.Handler.prototype.initialize = Event.Handler.prototype.initialize.wrap( function(init, element, eventName, selector, callback) { init(element, eventName, selector, callback) // is the handler being attached to an element that doesn't support this event? if ( (!submitBubbles && this.eventName == 'submit' && !isForm(this.element)) || (!changeBubbles && this.eventName == 'change' && !isInput(this.element)) ) { // "submit" => "emulated:submit" this.eventName = 'emulated:' + this.eventName } } ) } if (!submitBubbles) { // discover forms on the page by observing focus events which always bubble document.on('focusin', 'form', function(focusEvent, form) { // special handler for the real "submit" event (one-time operation) if (!form.retrieve('emulated:submit')) { form.on('submit', function(submitEvent) { var emulated = form.fire('emulated:submit', submitEvent, true) // if custom event received preventDefault, cancel the real one too if (emulated.returnValue === false) submitEvent.preventDefault() }) form.store('emulated:submit', true) } }) } if (!changeBubbles) { // discover form inputs on the page document.on('focusin', 'input, select, texarea', function(focusEvent, input) { // special handler for real "change" events if (!input.retrieve('emulated:change')) { input.on('change', function(changeEvent) { input.fire('emulated:change', changeEvent, true) }) input.store('emulated:change', true) } }) } function handleRemote(element) { var method, url, params; var event = element.fire("ajax:before"); if (event.stopped) return false; if (element.tagName.toLowerCase() === 'form') { method = element.readAttribute('method') || 'post'; url = element.readAttribute('action'); params = element.serialize(); } else { method = element.readAttribute('data-method') || 'get'; url = element.readAttribute('href'); params = {}; } new Ajax.Request(url, { method: method, parameters: params, evalScripts: true, onComplete: function(request) { element.fire("ajax:complete", request); }, onSuccess: function(request) { element.fire("ajax:success", request); }, onFailure: function(request) { element.fire("ajax:failure", request); } }); element.fire("ajax:after"); } function handleMethod(element) { var method = element.readAttribute('data-method'), url = element.readAttribute('href'), csrf_param = $$('meta[name=csrf-param]')[0], csrf_token = $$('meta[name=csrf-token]')[0]; var form = new Element('form', { method: "POST", action: url, style: "display: none;" }); element.parentNode.insert(form); if (method !== 'post') { var field = new Element('input', { type: 'hidden', name: '_method', value: method }); form.insert(field); } if (csrf_param) { var param = csrf_param.readAttribute('content'), token = csrf_token.readAttribute('content'), field = new Element('input', { type: 'hidden', name: param, value: token }); form.insert(field); } form.submit(); } document.on("click", "*[data-confirm]", function(event, element) { var message = element.readAttribute('data-confirm'); if (!confirm(message)) event.stop(); }); document.on("click", "a[data-remote]", function(event, element) { if (event.stopped) return; handleRemote(element); event.stop(); }); document.on("click", "a[data-method]", function(event, element) { if (event.stopped) return; handleMethod(element); event.stop(); }); document.on("submit", function(event) { var element = event.findElement(), message = element.readAttribute('data-confirm'); if (message && !confirm(message)) { event.stop(); return false; } var inputs = element.select("input[type=submit][data-disable-with]"); inputs.each(function(input) { input.disabled = true; input.writeAttribute('data-original-value', input.value); input.value = input.readAttribute('data-disable-with'); }); var element = event.findElement("form[data-remote]"); if (element) { handleRemote(element); event.stop(); } }); document.on("ajax:after", "form", function(event, element) { var inputs = element.select("input[type=submit][disabled=true][data-disable-with]"); inputs.each(function(input) { input.value = input.readAttribute('data-original-value'); input.removeAttribute('data-original-value'); input.disabled = false; }); }); })();
JavaScript
// Place your application-specific JavaScript functions and classes here // This file is automatically included by javascript_include_tag :defaults
JavaScript
function double_list_move(srcId, destId) { var src=document.getElementById(srcId); var dest=document.getElementById(destId); for (var i = 0; i < src.options.length; i++) { if (src.options[i].selected) { dest.options[dest.length] = new Option(src.options[i].text, src.options[i].value); src.options[i] = null; --i; } } } function double_list_submit() { var form = document.getElementById('sf_admin_edit_form'); var element; // find multiple selects with name beginning 'associated_' and select all their options for (var i = 0; i < form.elements.length; i++) { element = form.elements[i]; if (element.type == 'select-multiple') { if (element.className == 'sf_admin_multiple-selected') { for (var j = 0; j < element.options.length; j++) { element.options[j].selected = true; } } } } }
JavaScript
// django javascript file // Finds all fieldsets with class="collapse", collapses them, and gives each // one a "show" link that uncollapses it. The "show" link becomes a "hide" // link when the fieldset is visible. function findForm(node) { // returns the node of the form containing the given node if (node.tagName.toLowerCase() != 'form') { return findForm(node.parentNode); } return node; } var CollapsedFieldsets = { collapse_re: /\bcollapse\b/, // Class of fieldsets that should be dealt with. collapsed_re: /\bcollapsed\b/, // Class that fieldsets get when they're hidden. collapsed_class: 'collapsed', init: function() { var fieldsets = document.getElementsByTagName('fieldset'); var collapsed_seen = false; for (var i = 0, fs; fs = fieldsets[i]; i++) { // Collapse this fieldset if it has the correct class, and if it // doesn't have any errors. (Collapsing shouldn't apply in the case // of error messages.) if (fs.className.match(CollapsedFieldsets.collapse_re) && !CollapsedFieldsets.fieldset_has_errors(fs)) { collapsed_seen = true; // Give it an additional class, used by CSS to hide it. fs.className += ' ' + CollapsedFieldsets.collapsed_class; // (<a id="fieldsetcollapser3" class="collapse-toggle" href="#">show</a>) var collapse_link = document.createElement('a'); collapse_link.className = 'collapse-toggle'; collapse_link.id = 'fieldsetcollapser' + i; collapse_link.onclick = new Function('CollapsedFieldsets.show('+i+'); return false;'); collapse_link.href = '#'; collapse_link.innerHTML = 'show'; var h2 = fs.getElementsByTagName('h2')[0]; h2.appendChild(document.createTextNode(' [')); h2.appendChild(collapse_link); h2.appendChild(document.createTextNode(']')); } } if (collapsed_seen) { // Expand all collapsed fieldsets when form is submitted. Event.observe(findForm(document.getElementsByTagName('fieldset')[0]), 'submit', function() { CollapsedFieldsets.uncollapse_all(); }, false); } }, fieldset_has_errors: function(fs) { // Returns true if any fields in the fieldset have validation errors. var divs = fs.getElementsByTagName('div'); for (var i=0; i<divs.length; i++) { if (divs[i].className.match(/\bform-error\b/)) { return true; } } return false; }, show: function(fieldset_index) { var fs = document.getElementsByTagName('fieldset')[fieldset_index]; // Remove the class name that causes the "display: none". fs.className = fs.className.replace(CollapsedFieldsets.collapsed_re, ''); // Toggle the "show" link to a "hide" link var collapse_link = document.getElementById('fieldsetcollapser' + fieldset_index); collapse_link.onclick = new Function('CollapsedFieldsets.hide('+fieldset_index+'); return false;'); collapse_link.innerHTML = 'hide'; }, hide: function(fieldset_index) { var fs = document.getElementsByTagName('fieldset')[fieldset_index]; // Add the class name that causes the "display: none". fs.className += ' ' + CollapsedFieldsets.collapsed_class; // Toggle the "hide" link to a "show" link var collapse_link = document.getElementById('fieldsetcollapser' + fieldset_index); collapse_link.onclick = new Function('CollapsedFieldsets.show('+fieldset_index+'); return false;'); collapse_link.innerHTML = 'show'; }, uncollapse_all: function() { var fieldsets = document.getElementsByTagName('fieldset'); for (var i=0; i<fieldsets.length; i++) { if (fieldsets[i].className.match(CollapsedFieldsets.collapsed_re)) { CollapsedFieldsets.show(i); } } } } Event.observe(window, 'load', CollapsedFieldsets.init, false);
JavaScript
// script.aculo.us unittest.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // (c) 2005-2008 Jon Tirsen (http://www.tirsen.com) // (c) 2005-2008 Michael Schuerig (http://www.schuerig.de/michael/) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ // experimental, Firefox-only Event.simulateMouse = function(element, eventName) { var options = Object.extend({ pointerX: 0, pointerY: 0, buttons: 0, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false }, arguments[2] || {}); var oEvent = document.createEvent("MouseEvents"); oEvent.initMouseEvent(eventName, true, true, document.defaultView, options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element)); if(this.mark) Element.remove(this.mark); this.mark = document.createElement('div'); this.mark.appendChild(document.createTextNode(" ")); document.body.appendChild(this.mark); this.mark.style.position = 'absolute'; this.mark.style.top = options.pointerY + "px"; this.mark.style.left = options.pointerX + "px"; this.mark.style.width = "5px"; this.mark.style.height = "5px;"; this.mark.style.borderTop = "1px solid red;"; this.mark.style.borderLeft = "1px solid red;"; if(this.step) alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options)); $(element).dispatchEvent(oEvent); }; // Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2. // You need to downgrade to 1.0.4 for now to get this working // See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much Event.simulateKey = function(element, eventName) { var options = Object.extend({ ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, keyCode: 0, charCode: 0 }, arguments[2] || {}); var oEvent = document.createEvent("KeyEvents"); oEvent.initKeyEvent(eventName, true, true, window, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.keyCode, options.charCode ); $(element).dispatchEvent(oEvent); }; Event.simulateKeys = function(element, command) { for(var i=0; i<command.length; i++) { Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)}); } }; var Test = {}; Test.Unit = {}; // security exception workaround Test.Unit.inspect = Object.inspect; Test.Unit.Logger = Class.create(); Test.Unit.Logger.prototype = { initialize: function(log) { this.log = $(log); if (this.log) { this._createLogTable(); } }, start: function(testName) { if (!this.log) return; this.testName = testName; this.lastLogLine = document.createElement('tr'); this.statusCell = document.createElement('td'); this.nameCell = document.createElement('td'); this.nameCell.className = "nameCell"; this.nameCell.appendChild(document.createTextNode(testName)); this.messageCell = document.createElement('td'); this.lastLogLine.appendChild(this.statusCell); this.lastLogLine.appendChild(this.nameCell); this.lastLogLine.appendChild(this.messageCell); this.loglines.appendChild(this.lastLogLine); }, finish: function(status, summary) { if (!this.log) return; this.lastLogLine.className = status; this.statusCell.innerHTML = status; this.messageCell.innerHTML = this._toHTML(summary); this.addLinksToResults(); }, message: function(message) { if (!this.log) return; this.messageCell.innerHTML = this._toHTML(message); }, summary: function(summary) { if (!this.log) return; this.logsummary.innerHTML = this._toHTML(summary); }, _createLogTable: function() { this.log.innerHTML = '<div id="logsummary"></div>' + '<table id="logtable">' + '<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' + '<tbody id="loglines"></tbody>' + '</table>'; this.logsummary = $('logsummary'); this.loglines = $('loglines'); }, _toHTML: function(txt) { return txt.escapeHTML().replace(/\n/g,"<br/>"); }, addLinksToResults: function(){ $$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log td.title = "Run only this test"; Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;}); }); $$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log td.title = "Run all tests"; Event.observe(td, 'click', function(){ window.location.search = "";}); }); } }; Test.Unit.Runner = Class.create(); Test.Unit.Runner.prototype = { initialize: function(testcases) { this.options = Object.extend({ testLog: 'testlog' }, arguments[1] || {}); this.options.resultsURL = this.parseResultsURLQueryParameter(); this.options.tests = this.parseTestsQueryParameter(); if (this.options.testLog) { this.options.testLog = $(this.options.testLog) || null; } if(this.options.tests) { this.tests = []; for(var i = 0; i < this.options.tests.length; i++) { if(/^test/.test(this.options.tests[i])) { this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"])); } } } else { if (this.options.test) { this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])]; } else { this.tests = []; for(var testcase in testcases) { if(/^test/.test(testcase)) { this.tests.push( new Test.Unit.Testcase( this.options.context ? ' -> ' + this.options.titles[testcase] : testcase, testcases[testcase], testcases["setup"], testcases["teardown"] )); } } } } this.currentTest = 0; this.logger = new Test.Unit.Logger(this.options.testLog); setTimeout(this.runTests.bind(this), 1000); }, parseResultsURLQueryParameter: function() { return window.location.search.parseQuery()["resultsURL"]; }, parseTestsQueryParameter: function(){ if (window.location.search.parseQuery()["tests"]){ return window.location.search.parseQuery()["tests"].split(','); }; }, // Returns: // "ERROR" if there was an error, // "FAILURE" if there was a failure, or // "SUCCESS" if there was neither getResult: function() { var hasFailure = false; for(var i=0;i<this.tests.length;i++) { if (this.tests[i].errors > 0) { return "ERROR"; } if (this.tests[i].failures > 0) { hasFailure = true; } } if (hasFailure) { return "FAILURE"; } else { return "SUCCESS"; } }, postResults: function() { if (this.options.resultsURL) { new Ajax.Request(this.options.resultsURL, { method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false }); } }, runTests: function() { var test = this.tests[this.currentTest]; if (!test) { // finished! this.postResults(); this.logger.summary(this.summary()); return; } if(!test.isWaiting) { this.logger.start(test.name); } test.run(); if(test.isWaiting) { this.logger.message("Waiting for " + test.timeToWait + "ms"); setTimeout(this.runTests.bind(this), test.timeToWait || 1000); } else { this.logger.finish(test.status(), test.summary()); this.currentTest++; // tail recursive, hopefully the browser will skip the stackframe this.runTests(); } }, summary: function() { var assertions = 0; var failures = 0; var errors = 0; var messages = []; for(var i=0;i<this.tests.length;i++) { assertions += this.tests[i].assertions; failures += this.tests[i].failures; errors += this.tests[i].errors; } return ( (this.options.context ? this.options.context + ': ': '') + this.tests.length + " tests, " + assertions + " assertions, " + failures + " failures, " + errors + " errors"); } }; Test.Unit.Assertions = Class.create(); Test.Unit.Assertions.prototype = { initialize: function() { this.assertions = 0; this.failures = 0; this.errors = 0; this.messages = []; }, summary: function() { return ( this.assertions + " assertions, " + this.failures + " failures, " + this.errors + " errors" + "\n" + this.messages.join("\n")); }, pass: function() { this.assertions++; }, fail: function(message) { this.failures++; this.messages.push("Failure: " + message); }, info: function(message) { this.messages.push("Info: " + message); }, error: function(error) { this.errors++; this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")"); }, status: function() { if (this.failures > 0) return 'failed'; if (this.errors > 0) return 'error'; return 'passed'; }, assert: function(expression) { var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"'; try { expression ? this.pass() : this.fail(message); } catch(e) { this.error(e); } }, assertEqual: function(expected, actual) { var message = arguments[2] || "assertEqual"; try { (expected == actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertInspect: function(expected, actual) { var message = arguments[2] || "assertInspect"; try { (expected == actual.inspect()) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertEnumEqual: function(expected, actual) { var message = arguments[2] || "assertEnumEqual"; try { $A(expected).length == $A(actual).length && expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ? this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) + ', actual ' + Test.Unit.inspect(actual)); } catch(e) { this.error(e); } }, assertNotEqual: function(expected, actual) { var message = arguments[2] || "assertNotEqual"; try { (expected != actual) ? this.pass() : this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertIdentical: function(expected, actual) { var message = arguments[2] || "assertIdentical"; try { (expected === actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertNotIdentical: function(expected, actual) { var message = arguments[2] || "assertNotIdentical"; try { !(expected === actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertNull: function(obj) { var message = arguments[1] || 'assertNull'; try { (obj==null) ? this.pass() : this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); } catch(e) { this.error(e); } }, assertMatch: function(expected, actual) { var message = arguments[2] || 'assertMatch'; var regex = new RegExp(expected); try { (regex.exec(actual)) ? this.pass() : this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertHidden: function(element) { var message = arguments[1] || 'assertHidden'; this.assertEqual("none", element.style.display, message); }, assertNotNull: function(object) { var message = arguments[1] || 'assertNotNull'; this.assert(object != null, message); }, assertType: function(expected, actual) { var message = arguments[2] || 'assertType'; try { (actual.constructor == expected) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + (actual.constructor) + '"'); } catch(e) { this.error(e); } }, assertNotOfType: function(expected, actual) { var message = arguments[2] || 'assertNotOfType'; try { (actual.constructor != expected) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + (actual.constructor) + '"'); } catch(e) { this.error(e); } }, assertInstanceOf: function(expected, actual) { var message = arguments[2] || 'assertInstanceOf'; try { (actual instanceof expected) ? this.pass() : this.fail(message + ": object was not an instance of the expected type"); } catch(e) { this.error(e); } }, assertNotInstanceOf: function(expected, actual) { var message = arguments[2] || 'assertNotInstanceOf'; try { !(actual instanceof expected) ? this.pass() : this.fail(message + ": object was an instance of the not expected type"); } catch(e) { this.error(e); } }, assertRespondsTo: function(method, obj) { var message = arguments[2] || 'assertRespondsTo'; try { (obj[method] && typeof obj[method] == 'function') ? this.pass() : this.fail(message + ": object doesn't respond to [" + method + "]"); } catch(e) { this.error(e); } }, assertReturnsTrue: function(method, obj) { var message = arguments[2] || 'assertReturnsTrue'; try { var m = obj[method]; if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)]; m() ? this.pass() : this.fail(message + ": method returned false"); } catch(e) { this.error(e); } }, assertReturnsFalse: function(method, obj) { var message = arguments[2] || 'assertReturnsFalse'; try { var m = obj[method]; if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)]; !m() ? this.pass() : this.fail(message + ": method returned true"); } catch(e) { this.error(e); } }, assertRaise: function(exceptionName, method) { var message = arguments[2] || 'assertRaise'; try { method(); this.fail(message + ": exception expected but none was raised"); } catch(e) { ((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e); } }, assertElementsMatch: function() { var expressions = $A(arguments), elements = $A(expressions.shift()); if (elements.length != expressions.length) { this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions'); return false; } elements.zip(expressions).all(function(pair, index) { var element = $(pair.first()), expression = pair.last(); if (element.match(expression)) return true; this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect()); }.bind(this)) && this.pass(); }, assertElementMatches: function(element, expression) { this.assertElementsMatch([element], expression); }, benchmark: function(operation, iterations) { var startAt = new Date(); (iterations || 1).times(operation); var timeTaken = ((new Date())-startAt); this.info((arguments[2] || 'Operation') + ' finished ' + iterations + ' iterations in ' + (timeTaken/1000)+'s' ); return timeTaken; }, _isVisible: function(element) { element = $(element); if(!element.parentNode) return true; this.assertNotNull(element); if(element.style && Element.getStyle(element, 'display') == 'none') return false; return this._isVisible(element.parentNode); }, assertNotVisible: function(element) { this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1])); }, assertVisible: function(element) { this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1])); }, benchmark: function(operation, iterations) { var startAt = new Date(); (iterations || 1).times(operation); var timeTaken = ((new Date())-startAt); this.info((arguments[2] || 'Operation') + ' finished ' + iterations + ' iterations in ' + (timeTaken/1000)+'s' ); return timeTaken; } }; Test.Unit.Testcase = Class.create(); Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), { initialize: function(name, test, setup, teardown) { Test.Unit.Assertions.prototype.initialize.bind(this)(); this.name = name; if(typeof test == 'string') { test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,'); test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)'); this.test = function() { eval('with(this){'+test+'}'); } } else { this.test = test || function() {}; } this.setup = setup || function() {}; this.teardown = teardown || function() {}; this.isWaiting = false; this.timeToWait = 1000; }, wait: function(time, nextPart) { this.isWaiting = true; this.test = nextPart; this.timeToWait = time; }, run: function() { try { try { if (!this.isWaiting) this.setup.bind(this)(); this.isWaiting = false; this.test.bind(this)(); } finally { if(!this.isWaiting) { this.teardown.bind(this)(); } } } catch(e) { this.error(e); } } }); // *EXPERIMENTAL* BDD-style testing to please non-technical folk // This draws many ideas from RSpec http://rspec.rubyforge.org/ Test.setupBDDExtensionMethods = function(){ var METHODMAP = { shouldEqual: 'assertEqual', shouldNotEqual: 'assertNotEqual', shouldEqualEnum: 'assertEnumEqual', shouldBeA: 'assertType', shouldNotBeA: 'assertNotOfType', shouldBeAn: 'assertType', shouldNotBeAn: 'assertNotOfType', shouldBeNull: 'assertNull', shouldNotBeNull: 'assertNotNull', shouldBe: 'assertReturnsTrue', shouldNotBe: 'assertReturnsFalse', shouldRespondTo: 'assertRespondsTo' }; var makeAssertion = function(assertion, args, object) { this[assertion].apply(this,(args || []).concat([object])); }; Test.BDDMethods = {}; $H(METHODMAP).each(function(pair) { Test.BDDMethods[pair.key] = function() { var args = $A(arguments); var scope = args.shift(); makeAssertion.apply(scope, [pair.value, args, this]); }; }); [Array.prototype, String.prototype, Number.prototype, Boolean.prototype].each( function(p){ Object.extend(p, Test.BDDMethods) } ); }; Test.context = function(name, spec, log){ Test.setupBDDExtensionMethods(); var compiledSpec = {}; var titles = {}; for(specName in spec) { switch(specName){ case "setup": case "teardown": compiledSpec[specName] = spec[specName]; break; default: var testName = 'test'+specName.gsub(/\s+/,'-').camelize(); var body = spec[specName].toString().split('\n').slice(1); if(/^\{/.test(body[0])) body = body.slice(1); body.pop(); body = body.map(function(statement){ return statement.strip() }); compiledSpec[testName] = body.join('\n'); titles[testName] = specName; } } new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name }); };
JavaScript
// script.aculo.us slider.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008 // Copyright (c) 2005-2008 Marty Haught, Thomas Fuchs // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ if (!Control) var Control = { }; // options: // axis: 'vertical', or 'horizontal' (default) // // callbacks: // onChange(value) // onSlide(value) Control.Slider = Class.create({ initialize: function(handle, track, options) { var slider = this; if (Object.isArray(handle)) { this.handles = handle.collect( function(e) { return $(e) }); } else { this.handles = [$(handle)]; } this.track = $(track); this.options = options || { }; this.axis = this.options.axis || 'horizontal'; this.increment = this.options.increment || 1; this.step = parseInt(this.options.step || '1'); this.range = this.options.range || $R(0,1); this.value = 0; // assure backwards compat this.values = this.handles.map( function() { return 0 }); this.spans = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false; this.options.startSpan = $(this.options.startSpan || null); this.options.endSpan = $(this.options.endSpan || null); this.restricted = this.options.restricted || false; this.maximum = this.options.maximum || this.range.end; this.minimum = this.options.minimum || this.range.start; // Will be used to align the handle onto the track, if necessary this.alignX = parseInt(this.options.alignX || '0'); this.alignY = parseInt(this.options.alignY || '0'); this.trackLength = this.maximumOffset() - this.minimumOffset(); this.handleLength = this.isVertical() ? (this.handles[0].offsetHeight != 0 ? this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) : (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth : this.handles[0].style.width.replace(/px$/,"")); this.active = false; this.dragging = false; this.disabled = false; if (this.options.disabled) this.setDisabled(); // Allowed values array this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false; if (this.allowedValues) { this.minimum = this.allowedValues.min(); this.maximum = this.allowedValues.max(); } this.eventMouseDown = this.startDrag.bindAsEventListener(this); this.eventMouseUp = this.endDrag.bindAsEventListener(this); this.eventMouseMove = this.update.bindAsEventListener(this); // Initialize handles in reverse (make sure first handle is active) this.handles.each( function(h,i) { i = slider.handles.length-1-i; slider.setValue(parseFloat( (Object.isArray(slider.options.sliderValue) ? slider.options.sliderValue[i] : slider.options.sliderValue) || slider.range.start), i); h.makePositioned().observe("mousedown", slider.eventMouseDown); }); this.track.observe("mousedown", this.eventMouseDown); document.observe("mouseup", this.eventMouseUp); document.observe("mousemove", this.eventMouseMove); this.initialized = true; }, dispose: function() { var slider = this; Event.stopObserving(this.track, "mousedown", this.eventMouseDown); Event.stopObserving(document, "mouseup", this.eventMouseUp); Event.stopObserving(document, "mousemove", this.eventMouseMove); this.handles.each( function(h) { Event.stopObserving(h, "mousedown", slider.eventMouseDown); }); }, setDisabled: function(){ this.disabled = true; }, setEnabled: function(){ this.disabled = false; }, getNearestValue: function(value){ if (this.allowedValues){ if (value >= this.allowedValues.max()) return(this.allowedValues.max()); if (value <= this.allowedValues.min()) return(this.allowedValues.min()); var offset = Math.abs(this.allowedValues[0] - value); var newValue = this.allowedValues[0]; this.allowedValues.each( function(v) { var currentOffset = Math.abs(v - value); if (currentOffset <= offset){ newValue = v; offset = currentOffset; } }); return newValue; } if (value > this.range.end) return this.range.end; if (value < this.range.start) return this.range.start; return value; }, setValue: function(sliderValue, handleIdx){ if (!this.active) { this.activeHandleIdx = handleIdx || 0; this.activeHandle = this.handles[this.activeHandleIdx]; this.updateStyles(); } handleIdx = handleIdx || this.activeHandleIdx || 0; if (this.initialized && this.restricted) { if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1])) sliderValue = this.values[handleIdx-1]; if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1])) sliderValue = this.values[handleIdx+1]; } sliderValue = this.getNearestValue(sliderValue); this.values[handleIdx] = sliderValue; this.value = this.values[0]; // assure backwards compat this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = this.translateToPx(sliderValue); this.drawSpans(); if (!this.dragging || !this.event) this.updateFinished(); }, setValueBy: function(delta, handleIdx) { this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, handleIdx || this.activeHandleIdx || 0); }, translateToPx: function(value) { return Math.round( ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) * (value - this.range.start)) + "px"; }, translateToValue: function(offset) { return ((offset/(this.trackLength-this.handleLength) * (this.range.end-this.range.start)) + this.range.start); }, getRange: function(range) { var v = this.values.sortBy(Prototype.K); range = range || 0; return $R(v[range],v[range+1]); }, minimumOffset: function(){ return(this.isVertical() ? this.alignY : this.alignX); }, maximumOffset: function(){ return(this.isVertical() ? (this.track.offsetHeight != 0 ? this.track.offsetHeight : this.track.style.height.replace(/px$/,"")) - this.alignY : (this.track.offsetWidth != 0 ? this.track.offsetWidth : this.track.style.width.replace(/px$/,"")) - this.alignX); }, isVertical: function(){ return (this.axis == 'vertical'); }, drawSpans: function() { var slider = this; if (this.spans) $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) }); if (this.options.startSpan) this.setSpan(this.options.startSpan, $R(0, this.values.length>1 ? this.getRange(0).min() : this.value )); if (this.options.endSpan) this.setSpan(this.options.endSpan, $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum)); }, setSpan: function(span, range) { if (this.isVertical()) { span.style.top = this.translateToPx(range.start); span.style.height = this.translateToPx(range.end - range.start + this.range.start); } else { span.style.left = this.translateToPx(range.start); span.style.width = this.translateToPx(range.end - range.start + this.range.start); } }, updateStyles: function() { this.handles.each( function(h){ Element.removeClassName(h, 'selected') }); Element.addClassName(this.activeHandle, 'selected'); }, startDrag: function(event) { if (Event.isLeftClick(event)) { if (!this.disabled){ this.active = true; var handle = Event.element(event); var pointer = [Event.pointerX(event), Event.pointerY(event)]; var track = handle; if (track==this.track) { var offsets = Position.cumulativeOffset(this.track); this.event = event; this.setValue(this.translateToValue( (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2) )); var offsets = Position.cumulativeOffset(this.activeHandle); this.offsetX = (pointer[0] - offsets[0]); this.offsetY = (pointer[1] - offsets[1]); } else { // find the handle (prevents issues with Safari) while((this.handles.indexOf(handle) == -1) && handle.parentNode) handle = handle.parentNode; if (this.handles.indexOf(handle)!=-1) { this.activeHandle = handle; this.activeHandleIdx = this.handles.indexOf(this.activeHandle); this.updateStyles(); var offsets = Position.cumulativeOffset(this.activeHandle); this.offsetX = (pointer[0] - offsets[0]); this.offsetY = (pointer[1] - offsets[1]); } } } Event.stop(event); } }, update: function(event) { if (this.active) { if (!this.dragging) this.dragging = true; this.draw(event); if (Prototype.Browser.WebKit) window.scrollBy(0,0); Event.stop(event); } }, draw: function(event) { var pointer = [Event.pointerX(event), Event.pointerY(event)]; var offsets = Position.cumulativeOffset(this.track); pointer[0] -= this.offsetX + offsets[0]; pointer[1] -= this.offsetY + offsets[1]; this.event = event; this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] )); if (this.initialized && this.options.onSlide) this.options.onSlide(this.values.length>1 ? this.values : this.value, this); }, endDrag: function(event) { if (this.active && this.dragging) { this.finishDrag(event, true); Event.stop(event); } this.active = false; this.dragging = false; }, finishDrag: function(event, success) { this.active = false; this.dragging = false; this.updateFinished(); }, updateFinished: function() { if (this.initialized && this.options.onChange) this.options.onChange(this.values.length>1 ? this.values : this.value, this); this.event = null; } });
JavaScript
// script.aculo.us sound.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // Based on code created by Jules Gravinese (http://www.webveteran.com/) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ Sound = { tracks: {}, _enabled: true, template: new Template('<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'), enable: function(){ Sound._enabled = true; }, disable: function(){ Sound._enabled = false; }, play: function(url){ if(!Sound._enabled) return; var options = Object.extend({ track: 'global', url: url, replace: false }, arguments[1] || {}); if(options.replace && this.tracks[options.track]) { $R(0, this.tracks[options.track].id).each(function(id){ var sound = $('sound_'+options.track+'_'+id); sound.Stop && sound.Stop(); sound.remove(); }); this.tracks[options.track] = null; } if(!this.tracks[options.track]) this.tracks[options.track] = { id: 0 }; else this.tracks[options.track].id++; options.id = this.tracks[options.track].id; $$('body')[0].insert( Prototype.Browser.IE ? new Element('bgsound',{ id: 'sound_'+options.track+'_'+options.id, src: options.url, loop: 1, autostart: true }) : Sound.template.evaluate(options)); } }; if(Prototype.Browser.Gecko && navigator.userAgent.indexOf("Win") > 0){ if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('QuickTime') != -1 })) Sound.template = new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>'); else Sound.play = function(){}; }
JavaScript
// script.aculo.us scriptaculous.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // 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. // // For details, see the script.aculo.us web site: http://script.aculo.us/ var Scriptaculous = { Version: '1.8.2', require: function(libraryName) { // inserting via DOM fails in Safari 2.0, so brute force approach document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>'); }, REQUIRED_PROTOTYPE: '1.6.0.3', load: function() { function convertVersionString(versionString) { var v = versionString.replace(/_.*|\./g, ''); v = parseInt(v + '0'.times(4-v.length)); return versionString.indexOf('_') > -1 ? v-1 : v; } if((typeof Prototype=='undefined') || (typeof Element == 'undefined') || (typeof Element.Methods=='undefined') || (convertVersionString(Prototype.Version) < convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))) throw("script.aculo.us requires the Prototype JavaScript framework >= " + Scriptaculous.REQUIRED_PROTOTYPE); var js = /scriptaculous\.js(\?.*)?$/; $$('head script[src]').findAll(function(s) { return s.src.match(js); }).each(function(s) { var path = s.src.replace(js, ''), includes = s.src.match(/\?.*load=([a-z,]*)/); (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each( function(include) { Scriptaculous.require(path+include+'.js') }); }); } }; Scriptaculous.load();
JavaScript
// script.aculo.us builder.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ var Builder = { NODEMAP: { AREA: 'map', CAPTION: 'table', COL: 'table', COLGROUP: 'table', LEGEND: 'fieldset', OPTGROUP: 'select', OPTION: 'select', PARAM: 'object', TBODY: 'table', TD: 'table', TFOOT: 'table', TH: 'table', THEAD: 'table', TR: 'table' }, // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken, // due to a Firefox bug node: function(elementName) { elementName = elementName.toUpperCase(); // try innerHTML approach var parentTag = this.NODEMAP[elementName] || 'div'; var parentElement = document.createElement(parentTag); try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" + elementName + "></" + elementName + ">"; } catch(e) {} var element = parentElement.firstChild || null; // see if browser added wrapping tags if(element && (element.tagName.toUpperCase() != elementName)) element = element.getElementsByTagName(elementName)[0]; // fallback to createElement approach if(!element) element = document.createElement(elementName); // abort if nothing could be created if(!element) return; // attributes (or text) if(arguments[1]) if(this._isStringOrNumber(arguments[1]) || (arguments[1] instanceof Array) || arguments[1].tagName) { this._children(element, arguments[1]); } else { var attrs = this._attributes(arguments[1]); if(attrs.length) { try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" +elementName + " " + attrs + "></" + elementName + ">"; } catch(e) {} element = parentElement.firstChild || null; // workaround firefox 1.0.X bug if(!element) { element = document.createElement(elementName); for(attr in arguments[1]) element[attr == 'class' ? 'className' : attr] = arguments[1][attr]; } if(element.tagName.toUpperCase() != elementName) element = parentElement.getElementsByTagName(elementName)[0]; } } // text, or array of children if(arguments[2]) this._children(element, arguments[2]); return $(element); }, _text: function(text) { return document.createTextNode(text); }, ATTR_MAP: { 'className': 'class', 'htmlFor': 'for' }, _attributes: function(attributes) { var attrs = []; for(attribute in attributes) attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) + '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"'); return attrs.join(" "); }, _children: function(element, children) { if(children.tagName) { element.appendChild(children); return; } if(typeof children=='object') { // array can hold nodes and text children.flatten().each( function(e) { if(typeof e=='object') element.appendChild(e); else if(Builder._isStringOrNumber(e)) element.appendChild(Builder._text(e)); }); } else if(Builder._isStringOrNumber(children)) element.appendChild(Builder._text(children)); }, _isStringOrNumber: function(param) { return(typeof param=='string' || typeof param=='number'); }, build: function(html) { var element = this.node('div'); $(element).update(html.strip()); return element.down(); }, dump: function(scope) { if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " + "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " + "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+ "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+ "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+ "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/); tags.each( function(tag){ scope[tag] = function() { return Builder.node.apply(Builder, [tag].concat($A(arguments))); }; }); } };
JavaScript
// script.aculo.us unittest.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // (c) 2005-2008 Jon Tirsen (http://www.tirsen.com) // (c) 2005-2008 Michael Schuerig (http://www.schuerig.de/michael/) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ // experimental, Firefox-only Event.simulateMouse = function(element, eventName) { var options = Object.extend({ pointerX: 0, pointerY: 0, buttons: 0, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false }, arguments[2] || {}); var oEvent = document.createEvent("MouseEvents"); oEvent.initMouseEvent(eventName, true, true, document.defaultView, options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element)); if(this.mark) Element.remove(this.mark); this.mark = document.createElement('div'); this.mark.appendChild(document.createTextNode(" ")); document.body.appendChild(this.mark); this.mark.style.position = 'absolute'; this.mark.style.top = options.pointerY + "px"; this.mark.style.left = options.pointerX + "px"; this.mark.style.width = "5px"; this.mark.style.height = "5px;"; this.mark.style.borderTop = "1px solid red;"; this.mark.style.borderLeft = "1px solid red;"; if(this.step) alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options)); $(element).dispatchEvent(oEvent); }; // Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2. // You need to downgrade to 1.0.4 for now to get this working // See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much Event.simulateKey = function(element, eventName) { var options = Object.extend({ ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, keyCode: 0, charCode: 0 }, arguments[2] || {}); var oEvent = document.createEvent("KeyEvents"); oEvent.initKeyEvent(eventName, true, true, window, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.keyCode, options.charCode ); $(element).dispatchEvent(oEvent); }; Event.simulateKeys = function(element, command) { for(var i=0; i<command.length; i++) { Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)}); } }; var Test = {}; Test.Unit = {}; // security exception workaround Test.Unit.inspect = Object.inspect; Test.Unit.Logger = Class.create(); Test.Unit.Logger.prototype = { initialize: function(log) { this.log = $(log); if (this.log) { this._createLogTable(); } }, start: function(testName) { if (!this.log) return; this.testName = testName; this.lastLogLine = document.createElement('tr'); this.statusCell = document.createElement('td'); this.nameCell = document.createElement('td'); this.nameCell.className = "nameCell"; this.nameCell.appendChild(document.createTextNode(testName)); this.messageCell = document.createElement('td'); this.lastLogLine.appendChild(this.statusCell); this.lastLogLine.appendChild(this.nameCell); this.lastLogLine.appendChild(this.messageCell); this.loglines.appendChild(this.lastLogLine); }, finish: function(status, summary) { if (!this.log) return; this.lastLogLine.className = status; this.statusCell.innerHTML = status; this.messageCell.innerHTML = this._toHTML(summary); this.addLinksToResults(); }, message: function(message) { if (!this.log) return; this.messageCell.innerHTML = this._toHTML(message); }, summary: function(summary) { if (!this.log) return; this.logsummary.innerHTML = this._toHTML(summary); }, _createLogTable: function() { this.log.innerHTML = '<div id="logsummary"></div>' + '<table id="logtable">' + '<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' + '<tbody id="loglines"></tbody>' + '</table>'; this.logsummary = $('logsummary'); this.loglines = $('loglines'); }, _toHTML: function(txt) { return txt.escapeHTML().replace(/\n/g,"<br/>"); }, addLinksToResults: function(){ $$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log td.title = "Run only this test"; Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;}); }); $$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log td.title = "Run all tests"; Event.observe(td, 'click', function(){ window.location.search = "";}); }); } }; Test.Unit.Runner = Class.create(); Test.Unit.Runner.prototype = { initialize: function(testcases) { this.options = Object.extend({ testLog: 'testlog' }, arguments[1] || {}); this.options.resultsURL = this.parseResultsURLQueryParameter(); this.options.tests = this.parseTestsQueryParameter(); if (this.options.testLog) { this.options.testLog = $(this.options.testLog) || null; } if(this.options.tests) { this.tests = []; for(var i = 0; i < this.options.tests.length; i++) { if(/^test/.test(this.options.tests[i])) { this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"])); } } } else { if (this.options.test) { this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])]; } else { this.tests = []; for(var testcase in testcases) { if(/^test/.test(testcase)) { this.tests.push( new Test.Unit.Testcase( this.options.context ? ' -> ' + this.options.titles[testcase] : testcase, testcases[testcase], testcases["setup"], testcases["teardown"] )); } } } } this.currentTest = 0; this.logger = new Test.Unit.Logger(this.options.testLog); setTimeout(this.runTests.bind(this), 1000); }, parseResultsURLQueryParameter: function() { return window.location.search.parseQuery()["resultsURL"]; }, parseTestsQueryParameter: function(){ if (window.location.search.parseQuery()["tests"]){ return window.location.search.parseQuery()["tests"].split(','); }; }, // Returns: // "ERROR" if there was an error, // "FAILURE" if there was a failure, or // "SUCCESS" if there was neither getResult: function() { var hasFailure = false; for(var i=0;i<this.tests.length;i++) { if (this.tests[i].errors > 0) { return "ERROR"; } if (this.tests[i].failures > 0) { hasFailure = true; } } if (hasFailure) { return "FAILURE"; } else { return "SUCCESS"; } }, postResults: function() { if (this.options.resultsURL) { new Ajax.Request(this.options.resultsURL, { method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false }); } }, runTests: function() { var test = this.tests[this.currentTest]; if (!test) { // finished! this.postResults(); this.logger.summary(this.summary()); return; } if(!test.isWaiting) { this.logger.start(test.name); } test.run(); if(test.isWaiting) { this.logger.message("Waiting for " + test.timeToWait + "ms"); setTimeout(this.runTests.bind(this), test.timeToWait || 1000); } else { this.logger.finish(test.status(), test.summary()); this.currentTest++; // tail recursive, hopefully the browser will skip the stackframe this.runTests(); } }, summary: function() { var assertions = 0; var failures = 0; var errors = 0; var messages = []; for(var i=0;i<this.tests.length;i++) { assertions += this.tests[i].assertions; failures += this.tests[i].failures; errors += this.tests[i].errors; } return ( (this.options.context ? this.options.context + ': ': '') + this.tests.length + " tests, " + assertions + " assertions, " + failures + " failures, " + errors + " errors"); } }; Test.Unit.Assertions = Class.create(); Test.Unit.Assertions.prototype = { initialize: function() { this.assertions = 0; this.failures = 0; this.errors = 0; this.messages = []; }, summary: function() { return ( this.assertions + " assertions, " + this.failures + " failures, " + this.errors + " errors" + "\n" + this.messages.join("\n")); }, pass: function() { this.assertions++; }, fail: function(message) { this.failures++; this.messages.push("Failure: " + message); }, info: function(message) { this.messages.push("Info: " + message); }, error: function(error) { this.errors++; this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")"); }, status: function() { if (this.failures > 0) return 'failed'; if (this.errors > 0) return 'error'; return 'passed'; }, assert: function(expression) { var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"'; try { expression ? this.pass() : this.fail(message); } catch(e) { this.error(e); } }, assertEqual: function(expected, actual) { var message = arguments[2] || "assertEqual"; try { (expected == actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertInspect: function(expected, actual) { var message = arguments[2] || "assertInspect"; try { (expected == actual.inspect()) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertEnumEqual: function(expected, actual) { var message = arguments[2] || "assertEnumEqual"; try { $A(expected).length == $A(actual).length && expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ? this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) + ', actual ' + Test.Unit.inspect(actual)); } catch(e) { this.error(e); } }, assertNotEqual: function(expected, actual) { var message = arguments[2] || "assertNotEqual"; try { (expected != actual) ? this.pass() : this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertIdentical: function(expected, actual) { var message = arguments[2] || "assertIdentical"; try { (expected === actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertNotIdentical: function(expected, actual) { var message = arguments[2] || "assertNotIdentical"; try { !(expected === actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertNull: function(obj) { var message = arguments[1] || 'assertNull'; try { (obj==null) ? this.pass() : this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); } catch(e) { this.error(e); } }, assertMatch: function(expected, actual) { var message = arguments[2] || 'assertMatch'; var regex = new RegExp(expected); try { (regex.exec(actual)) ? this.pass() : this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertHidden: function(element) { var message = arguments[1] || 'assertHidden'; this.assertEqual("none", element.style.display, message); }, assertNotNull: function(object) { var message = arguments[1] || 'assertNotNull'; this.assert(object != null, message); }, assertType: function(expected, actual) { var message = arguments[2] || 'assertType'; try { (actual.constructor == expected) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + (actual.constructor) + '"'); } catch(e) { this.error(e); } }, assertNotOfType: function(expected, actual) { var message = arguments[2] || 'assertNotOfType'; try { (actual.constructor != expected) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + (actual.constructor) + '"'); } catch(e) { this.error(e); } }, assertInstanceOf: function(expected, actual) { var message = arguments[2] || 'assertInstanceOf'; try { (actual instanceof expected) ? this.pass() : this.fail(message + ": object was not an instance of the expected type"); } catch(e) { this.error(e); } }, assertNotInstanceOf: function(expected, actual) { var message = arguments[2] || 'assertNotInstanceOf'; try { !(actual instanceof expected) ? this.pass() : this.fail(message + ": object was an instance of the not expected type"); } catch(e) { this.error(e); } }, assertRespondsTo: function(method, obj) { var message = arguments[2] || 'assertRespondsTo'; try { (obj[method] && typeof obj[method] == 'function') ? this.pass() : this.fail(message + ": object doesn't respond to [" + method + "]"); } catch(e) { this.error(e); } }, assertReturnsTrue: function(method, obj) { var message = arguments[2] || 'assertReturnsTrue'; try { var m = obj[method]; if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)]; m() ? this.pass() : this.fail(message + ": method returned false"); } catch(e) { this.error(e); } }, assertReturnsFalse: function(method, obj) { var message = arguments[2] || 'assertReturnsFalse'; try { var m = obj[method]; if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)]; !m() ? this.pass() : this.fail(message + ": method returned true"); } catch(e) { this.error(e); } }, assertRaise: function(exceptionName, method) { var message = arguments[2] || 'assertRaise'; try { method(); this.fail(message + ": exception expected but none was raised"); } catch(e) { ((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e); } }, assertElementsMatch: function() { var expressions = $A(arguments), elements = $A(expressions.shift()); if (elements.length != expressions.length) { this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions'); return false; } elements.zip(expressions).all(function(pair, index) { var element = $(pair.first()), expression = pair.last(); if (element.match(expression)) return true; this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect()); }.bind(this)) && this.pass(); }, assertElementMatches: function(element, expression) { this.assertElementsMatch([element], expression); }, benchmark: function(operation, iterations) { var startAt = new Date(); (iterations || 1).times(operation); var timeTaken = ((new Date())-startAt); this.info((arguments[2] || 'Operation') + ' finished ' + iterations + ' iterations in ' + (timeTaken/1000)+'s' ); return timeTaken; }, _isVisible: function(element) { element = $(element); if(!element.parentNode) return true; this.assertNotNull(element); if(element.style && Element.getStyle(element, 'display') == 'none') return false; return this._isVisible(element.parentNode); }, assertNotVisible: function(element) { this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1])); }, assertVisible: function(element) { this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1])); }, benchmark: function(operation, iterations) { var startAt = new Date(); (iterations || 1).times(operation); var timeTaken = ((new Date())-startAt); this.info((arguments[2] || 'Operation') + ' finished ' + iterations + ' iterations in ' + (timeTaken/1000)+'s' ); return timeTaken; } }; Test.Unit.Testcase = Class.create(); Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), { initialize: function(name, test, setup, teardown) { Test.Unit.Assertions.prototype.initialize.bind(this)(); this.name = name; if(typeof test == 'string') { test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,'); test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)'); this.test = function() { eval('with(this){'+test+'}'); } } else { this.test = test || function() {}; } this.setup = setup || function() {}; this.teardown = teardown || function() {}; this.isWaiting = false; this.timeToWait = 1000; }, wait: function(time, nextPart) { this.isWaiting = true; this.test = nextPart; this.timeToWait = time; }, run: function() { try { try { if (!this.isWaiting) this.setup.bind(this)(); this.isWaiting = false; this.test.bind(this)(); } finally { if(!this.isWaiting) { this.teardown.bind(this)(); } } } catch(e) { this.error(e); } } }); // *EXPERIMENTAL* BDD-style testing to please non-technical folk // This draws many ideas from RSpec http://rspec.rubyforge.org/ Test.setupBDDExtensionMethods = function(){ var METHODMAP = { shouldEqual: 'assertEqual', shouldNotEqual: 'assertNotEqual', shouldEqualEnum: 'assertEnumEqual', shouldBeA: 'assertType', shouldNotBeA: 'assertNotOfType', shouldBeAn: 'assertType', shouldNotBeAn: 'assertNotOfType', shouldBeNull: 'assertNull', shouldNotBeNull: 'assertNotNull', shouldBe: 'assertReturnsTrue', shouldNotBe: 'assertReturnsFalse', shouldRespondTo: 'assertRespondsTo' }; var makeAssertion = function(assertion, args, object) { this[assertion].apply(this,(args || []).concat([object])); }; Test.BDDMethods = {}; $H(METHODMAP).each(function(pair) { Test.BDDMethods[pair.key] = function() { var args = $A(arguments); var scope = args.shift(); makeAssertion.apply(scope, [pair.value, args, this]); }; }); [Array.prototype, String.prototype, Number.prototype, Boolean.prototype].each( function(p){ Object.extend(p, Test.BDDMethods) } ); }; Test.context = function(name, spec, log){ Test.setupBDDExtensionMethods(); var compiledSpec = {}; var titles = {}; for(specName in spec) { switch(specName){ case "setup": case "teardown": compiledSpec[specName] = spec[specName]; break; default: var testName = 'test'+specName.gsub(/\s+/,'-').camelize(); var body = spec[specName].toString().split('\n').slice(1); if(/^\{/.test(body[0])) body = body.slice(1); body.pop(); body = body.map(function(statement){ return statement.strip() }); compiledSpec[testName] = body.join('\n'); titles[testName] = specName; } } new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name }); };
JavaScript
// script.aculo.us slider.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008 // Copyright (c) 2005-2008 Marty Haught, Thomas Fuchs // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ if (!Control) var Control = { }; // options: // axis: 'vertical', or 'horizontal' (default) // // callbacks: // onChange(value) // onSlide(value) Control.Slider = Class.create({ initialize: function(handle, track, options) { var slider = this; if (Object.isArray(handle)) { this.handles = handle.collect( function(e) { return $(e) }); } else { this.handles = [$(handle)]; } this.track = $(track); this.options = options || { }; this.axis = this.options.axis || 'horizontal'; this.increment = this.options.increment || 1; this.step = parseInt(this.options.step || '1'); this.range = this.options.range || $R(0,1); this.value = 0; // assure backwards compat this.values = this.handles.map( function() { return 0 }); this.spans = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false; this.options.startSpan = $(this.options.startSpan || null); this.options.endSpan = $(this.options.endSpan || null); this.restricted = this.options.restricted || false; this.maximum = this.options.maximum || this.range.end; this.minimum = this.options.minimum || this.range.start; // Will be used to align the handle onto the track, if necessary this.alignX = parseInt(this.options.alignX || '0'); this.alignY = parseInt(this.options.alignY || '0'); this.trackLength = this.maximumOffset() - this.minimumOffset(); this.handleLength = this.isVertical() ? (this.handles[0].offsetHeight != 0 ? this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) : (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth : this.handles[0].style.width.replace(/px$/,"")); this.active = false; this.dragging = false; this.disabled = false; if (this.options.disabled) this.setDisabled(); // Allowed values array this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false; if (this.allowedValues) { this.minimum = this.allowedValues.min(); this.maximum = this.allowedValues.max(); } this.eventMouseDown = this.startDrag.bindAsEventListener(this); this.eventMouseUp = this.endDrag.bindAsEventListener(this); this.eventMouseMove = this.update.bindAsEventListener(this); // Initialize handles in reverse (make sure first handle is active) this.handles.each( function(h,i) { i = slider.handles.length-1-i; slider.setValue(parseFloat( (Object.isArray(slider.options.sliderValue) ? slider.options.sliderValue[i] : slider.options.sliderValue) || slider.range.start), i); h.makePositioned().observe("mousedown", slider.eventMouseDown); }); this.track.observe("mousedown", this.eventMouseDown); document.observe("mouseup", this.eventMouseUp); document.observe("mousemove", this.eventMouseMove); this.initialized = true; }, dispose: function() { var slider = this; Event.stopObserving(this.track, "mousedown", this.eventMouseDown); Event.stopObserving(document, "mouseup", this.eventMouseUp); Event.stopObserving(document, "mousemove", this.eventMouseMove); this.handles.each( function(h) { Event.stopObserving(h, "mousedown", slider.eventMouseDown); }); }, setDisabled: function(){ this.disabled = true; }, setEnabled: function(){ this.disabled = false; }, getNearestValue: function(value){ if (this.allowedValues){ if (value >= this.allowedValues.max()) return(this.allowedValues.max()); if (value <= this.allowedValues.min()) return(this.allowedValues.min()); var offset = Math.abs(this.allowedValues[0] - value); var newValue = this.allowedValues[0]; this.allowedValues.each( function(v) { var currentOffset = Math.abs(v - value); if (currentOffset <= offset){ newValue = v; offset = currentOffset; } }); return newValue; } if (value > this.range.end) return this.range.end; if (value < this.range.start) return this.range.start; return value; }, setValue: function(sliderValue, handleIdx){ if (!this.active) { this.activeHandleIdx = handleIdx || 0; this.activeHandle = this.handles[this.activeHandleIdx]; this.updateStyles(); } handleIdx = handleIdx || this.activeHandleIdx || 0; if (this.initialized && this.restricted) { if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1])) sliderValue = this.values[handleIdx-1]; if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1])) sliderValue = this.values[handleIdx+1]; } sliderValue = this.getNearestValue(sliderValue); this.values[handleIdx] = sliderValue; this.value = this.values[0]; // assure backwards compat this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = this.translateToPx(sliderValue); this.drawSpans(); if (!this.dragging || !this.event) this.updateFinished(); }, setValueBy: function(delta, handleIdx) { this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, handleIdx || this.activeHandleIdx || 0); }, translateToPx: function(value) { return Math.round( ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) * (value - this.range.start)) + "px"; }, translateToValue: function(offset) { return ((offset/(this.trackLength-this.handleLength) * (this.range.end-this.range.start)) + this.range.start); }, getRange: function(range) { var v = this.values.sortBy(Prototype.K); range = range || 0; return $R(v[range],v[range+1]); }, minimumOffset: function(){ return(this.isVertical() ? this.alignY : this.alignX); }, maximumOffset: function(){ return(this.isVertical() ? (this.track.offsetHeight != 0 ? this.track.offsetHeight : this.track.style.height.replace(/px$/,"")) - this.alignY : (this.track.offsetWidth != 0 ? this.track.offsetWidth : this.track.style.width.replace(/px$/,"")) - this.alignX); }, isVertical: function(){ return (this.axis == 'vertical'); }, drawSpans: function() { var slider = this; if (this.spans) $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) }); if (this.options.startSpan) this.setSpan(this.options.startSpan, $R(0, this.values.length>1 ? this.getRange(0).min() : this.value )); if (this.options.endSpan) this.setSpan(this.options.endSpan, $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum)); }, setSpan: function(span, range) { if (this.isVertical()) { span.style.top = this.translateToPx(range.start); span.style.height = this.translateToPx(range.end - range.start + this.range.start); } else { span.style.left = this.translateToPx(range.start); span.style.width = this.translateToPx(range.end - range.start + this.range.start); } }, updateStyles: function() { this.handles.each( function(h){ Element.removeClassName(h, 'selected') }); Element.addClassName(this.activeHandle, 'selected'); }, startDrag: function(event) { if (Event.isLeftClick(event)) { if (!this.disabled){ this.active = true; var handle = Event.element(event); var pointer = [Event.pointerX(event), Event.pointerY(event)]; var track = handle; if (track==this.track) { var offsets = Position.cumulativeOffset(this.track); this.event = event; this.setValue(this.translateToValue( (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2) )); var offsets = Position.cumulativeOffset(this.activeHandle); this.offsetX = (pointer[0] - offsets[0]); this.offsetY = (pointer[1] - offsets[1]); } else { // find the handle (prevents issues with Safari) while((this.handles.indexOf(handle) == -1) && handle.parentNode) handle = handle.parentNode; if (this.handles.indexOf(handle)!=-1) { this.activeHandle = handle; this.activeHandleIdx = this.handles.indexOf(this.activeHandle); this.updateStyles(); var offsets = Position.cumulativeOffset(this.activeHandle); this.offsetX = (pointer[0] - offsets[0]); this.offsetY = (pointer[1] - offsets[1]); } } } Event.stop(event); } }, update: function(event) { if (this.active) { if (!this.dragging) this.dragging = true; this.draw(event); if (Prototype.Browser.WebKit) window.scrollBy(0,0); Event.stop(event); } }, draw: function(event) { var pointer = [Event.pointerX(event), Event.pointerY(event)]; var offsets = Position.cumulativeOffset(this.track); pointer[0] -= this.offsetX + offsets[0]; pointer[1] -= this.offsetY + offsets[1]; this.event = event; this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] )); if (this.initialized && this.options.onSlide) this.options.onSlide(this.values.length>1 ? this.values : this.value, this); }, endDrag: function(event) { if (this.active && this.dragging) { this.finishDrag(event, true); Event.stop(event); } this.active = false; this.dragging = false; }, finishDrag: function(event, success) { this.active = false; this.dragging = false; this.updateFinished(); }, updateFinished: function() { if (this.initialized && this.options.onChange) this.options.onChange(this.values.length>1 ? this.values : this.value, this); this.event = null; } });
JavaScript
// script.aculo.us sound.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // Based on code created by Jules Gravinese (http://www.webveteran.com/) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ Sound = { tracks: {}, _enabled: true, template: new Template('<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'), enable: function(){ Sound._enabled = true; }, disable: function(){ Sound._enabled = false; }, play: function(url){ if(!Sound._enabled) return; var options = Object.extend({ track: 'global', url: url, replace: false }, arguments[1] || {}); if(options.replace && this.tracks[options.track]) { $R(0, this.tracks[options.track].id).each(function(id){ var sound = $('sound_'+options.track+'_'+id); sound.Stop && sound.Stop(); sound.remove(); }); this.tracks[options.track] = null; } if(!this.tracks[options.track]) this.tracks[options.track] = { id: 0 }; else this.tracks[options.track].id++; options.id = this.tracks[options.track].id; $$('body')[0].insert( Prototype.Browser.IE ? new Element('bgsound',{ id: 'sound_'+options.track+'_'+options.id, src: options.url, loop: 1, autostart: true }) : Sound.template.evaluate(options)); } }; if(Prototype.Browser.Gecko && navigator.userAgent.indexOf("Win") > 0){ if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('QuickTime') != -1 })) Sound.template = new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>'); else Sound.play = function(){}; }
JavaScript
// script.aculo.us scriptaculous.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // 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. // // For details, see the script.aculo.us web site: http://script.aculo.us/ var Scriptaculous = { Version: '1.8.2', require: function(libraryName) { // inserting via DOM fails in Safari 2.0, so brute force approach document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>'); }, REQUIRED_PROTOTYPE: '1.6.0.3', load: function() { function convertVersionString(versionString) { var v = versionString.replace(/_.*|\./g, ''); v = parseInt(v + '0'.times(4-v.length)); return versionString.indexOf('_') > -1 ? v-1 : v; } if((typeof Prototype=='undefined') || (typeof Element == 'undefined') || (typeof Element.Methods=='undefined') || (convertVersionString(Prototype.Version) < convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))) throw("script.aculo.us requires the Prototype JavaScript framework >= " + Scriptaculous.REQUIRED_PROTOTYPE); var js = /scriptaculous\.js(\?.*)?$/; $$('head script[src]').findAll(function(s) { return s.src.match(js); }).each(function(s) { var path = s.src.replace(js, ''), includes = s.src.match(/\?.*load=([a-z,]*)/); (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each( function(include) { Scriptaculous.require(path+include+'.js') }); }); } }; Scriptaculous.load();
JavaScript
// script.aculo.us builder.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ var Builder = { NODEMAP: { AREA: 'map', CAPTION: 'table', COL: 'table', COLGROUP: 'table', LEGEND: 'fieldset', OPTGROUP: 'select', OPTION: 'select', PARAM: 'object', TBODY: 'table', TD: 'table', TFOOT: 'table', TH: 'table', THEAD: 'table', TR: 'table' }, // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken, // due to a Firefox bug node: function(elementName) { elementName = elementName.toUpperCase(); // try innerHTML approach var parentTag = this.NODEMAP[elementName] || 'div'; var parentElement = document.createElement(parentTag); try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" + elementName + "></" + elementName + ">"; } catch(e) {} var element = parentElement.firstChild || null; // see if browser added wrapping tags if(element && (element.tagName.toUpperCase() != elementName)) element = element.getElementsByTagName(elementName)[0]; // fallback to createElement approach if(!element) element = document.createElement(elementName); // abort if nothing could be created if(!element) return; // attributes (or text) if(arguments[1]) if(this._isStringOrNumber(arguments[1]) || (arguments[1] instanceof Array) || arguments[1].tagName) { this._children(element, arguments[1]); } else { var attrs = this._attributes(arguments[1]); if(attrs.length) { try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" +elementName + " " + attrs + "></" + elementName + ">"; } catch(e) {} element = parentElement.firstChild || null; // workaround firefox 1.0.X bug if(!element) { element = document.createElement(elementName); for(attr in arguments[1]) element[attr == 'class' ? 'className' : attr] = arguments[1][attr]; } if(element.tagName.toUpperCase() != elementName) element = parentElement.getElementsByTagName(elementName)[0]; } } // text, or array of children if(arguments[2]) this._children(element, arguments[2]); return $(element); }, _text: function(text) { return document.createTextNode(text); }, ATTR_MAP: { 'className': 'class', 'htmlFor': 'for' }, _attributes: function(attributes) { var attrs = []; for(attribute in attributes) attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) + '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"'); return attrs.join(" "); }, _children: function(element, children) { if(children.tagName) { element.appendChild(children); return; } if(typeof children=='object') { // array can hold nodes and text children.flatten().each( function(e) { if(typeof e=='object') element.appendChild(e); else if(Builder._isStringOrNumber(e)) element.appendChild(Builder._text(e)); }); } else if(Builder._isStringOrNumber(children)) element.appendChild(Builder._text(children)); }, _isStringOrNumber: function(param) { return(typeof param=='string' || typeof param=='number'); }, build: function(html) { var element = this.node('div'); $(element).update(html.strip()); return element.down(); }, dump: function(scope) { if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " + "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " + "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+ "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+ "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+ "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/); tags.each( function(tag){ scope[tag] = function() { return Builder.node.apply(Builder, [tag].concat($A(arguments))); }; }); } };
JavaScript
// JavaScript Document //jquery timers /** * jQuery.timers - Timer abstractions for jQuery * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com) * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/). * Date: 2009/10/16 * * @author Blair Mitchelmore * @version 1.2 * **/ jQuery.fn.extend({ everyTime: function(interval, label, fn, times) { return this.each(function() { jQuery.timer.add(this, interval, label, fn, times); }); }, oneTime: function(interval, label, fn) { return this.each(function() { jQuery.timer.add(this, interval, label, fn, 1); }); }, stopTime: function(label, fn) { return this.each(function() { jQuery.timer.remove(this, label, fn); }); } }); jQuery.extend({ timer: { global: [], guid: 1, dataKey: "jQuery.timer", regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/, powers: { // Yeah this is major overkill... 'ms': 1, 'cs': 10, 'ds': 100, 's': 1000, 'das': 10000, 'hs': 100000, 'ks': 1000000 }, timeParse: function(value) { if (value == undefined || value == null) return null; var result = this.regex.exec(jQuery.trim(value.toString())); if (result[2]) { var num = parseFloat(result[1]); var mult = this.powers[result[2]] || 1; return num * mult; } else { return value; } }, add: function(element, interval, label, fn, times) { var counter = 0; if (jQuery.isFunction(label)) { if (!times) times = fn; fn = label; label = interval; } interval = jQuery.timer.timeParse(interval); if (typeof interval != 'number' || isNaN(interval) || interval < 0) return; if (typeof times != 'number' || isNaN(times) || times < 0) times = 0; times = times || 0; var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {}); if (!timers[label]) timers[label] = {}; fn.timerID = fn.timerID || this.guid++; var handler = function() { if ((++counter > times && times !== 0) || fn.call(element, counter) === false) jQuery.timer.remove(element, label, fn); }; handler.timerID = fn.timerID; if (!timers[label][fn.timerID]) timers[label][fn.timerID] = window.setInterval(handler,interval); this.global.push( element ); }, remove: function(element, label, fn) { var timers = jQuery.data(element, this.dataKey), ret; if ( timers ) { if (!label) { for ( label in timers ) this.remove(element, label, fn); } else if ( timers[label] ) { if ( fn ) { if ( fn.timerID ) { window.clearInterval(timers[label][fn.timerID]); delete timers[label][fn.timerID]; } } else { for ( var fn in timers[label] ) { window.clearInterval(timers[label][fn]); delete timers[label][fn]; } } for ( ret in timers[label] ) break; if ( !ret ) { ret = null; delete timers[label]; } } for ( ret in timers ) break; if ( !ret ) jQuery.removeData(element, this.dataKey); } } } }); jQuery(window).bind("unload", function() { jQuery.each(jQuery.timer.global, function(index, item) { jQuery.timer.remove(item); }); });
JavaScript
/** * @name GeoClusterer * @version 1.0 * @author Huan Erdao * @copyright (c) 2009 Huan Erdao * @fileoverview * This javascript library comes from markerclusterer by Xiaoxi Wu * which partially ported to work with google maps v3 apis. */ /* * 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. */ /** * Projection overlay helper class * came from : http://snippets.aktagon.com/snippets/377-How-to-find-a-Google-Map-marker-s-exact-position * @constructor * @param {google.maps.Map} map The map that the markers should be added to. */ function ProjectionHelperOverlay(map) { this.setMap(map); } ProjectionHelperOverlay.prototype = new google.maps.OverlayView(); ProjectionHelperOverlay.prototype.draw = function() { if (!this.ready){ this.ready = true; google.maps.event.trigger(this, 'ready'); } }; /** * GeoCluster class * @constructor * @param {google.maps.Map} map The map that the markers should be added to. */ function GeoClusterer(map) { // private members var clusters_ = []; var map_ = map; var maxZoom_ = null; var me_ = this; var gridSize_ = 90; var leftItems_ = []; var mcfn_ = null; var projectionHelper_ = new ProjectionHelperOverlay(map_); /** * addItem. */ this.addItem = function (item) { if (!isItemInViewport_(item)) { leftItems_.push(item); return; } var projection = projectionHelper_.getProjection(); var pos = projection.fromLatLngToDivPixel(item.latlng); var length = clusters_.length; var cluster = null; for (var i = length - 1; i >= 0; i--) { cluster = clusters_[i]; var gpCenter = cluster.getCenter(); if (gpCenter === null) { continue; } var ptCenter = projection.fromLatLngToDivPixel(gpCenter); // Found a cluster which contains the marker. if (pos.x >= ptCenter.x - gridSize_ && pos.x <= ptCenter.x + gridSize_ && pos.y >= ptCenter.y - gridSize_ && pos.y <= ptCenter.y + gridSize_) { cluster.addItem(item); return; } } // No cluster contain the marker, create a new cluster. createCluster(item); }; /** * Create Cluster Object. * override this method, if you want to use custom GeoCluster class. * @param item GeoItem to be set to cluster. */ function createCluster(item){ cluster = new Cluster(me_, map); cluster.addItem(item); clusters_.push(cluster); } /** * Redraw all clusters in viewport. */ this.redraw_ = function () { for (var i = 0; i < clusters_.length; ++i) { clusters_[i].redraw_(true); } }; this.getProjectionHelper = function() { return projectionHelper_; }; /** * Get all clusters in viewport. */ this.getClustersInViewport_ = function () { var clusters = []; var curBounds = map_.getBounds(); for (var i = 0; i < clusters_.length; i ++) { if (clusters_[i].isInBounds(curBounds)) { clusters.push(clusters_[i]); } } return clusters; }; /** * addleftItems_ */ function addleftItems_() { if (leftItems_.length === 0) { return; } var leftItems = leftItems_.slice(0); leftItems_.length = 0; for (i = 0; i < leftItems.length; ++i) { me_.addItem(leftItems[i]); } } /** * reAddItems_ */ function reAddItems_(items) { var len = items.length; for (var i = len - 1; i >= 0; --i) { me_.addItem(items[i]); } addleftItems_(); } /** * Remove all markers from MarkerClusterer. */ this.clear = function () { for (var i = 0; i < clusters_.length; ++i) { if (typeof clusters_[i] !== "undefined" && clusters_[i] !== null) { clusters_[i].clear(); } } clusters_ = []; leftItems_ = []; if(mcfn_){ google.maps.event.removeListener(mcfn_); mcfn_ = null; } }; /** * addItems */ this.addItems = function (items) { for (var i = 0; i < items.length; ++i) { this.addItem(items[i]); } this.redraw_(); // when map move end, regroup. mcfn_ = google.maps.event.addListener(map_, "bounds_changed", function () { me_.resetViewport(); }); }; /** * isItemInViewport_ */ function isItemInViewport_(item) { return map_.getBounds().contains(item.latlng); } /** * Get grid size */ this.getGridSize_ = function () { return gridSize_; }; /** * Collect all markers of clusters in viewport and regroup them. */ this.resetViewport = function () { var clusters = this.getClustersInViewport_(); var tmpItems = []; var removed = 0; for (var i = 0; i < clusters.length; ++i) { var cluster = clusters[i]; var oldZoom = cluster.getCurrentZoom(); if (oldZoom === null) { continue; } var curZoom = map_.getZoom(); if (curZoom !== oldZoom) { // If the cluster zoom level changed then destroy the cluster // and collect its markers. var citms = cluster.getItems(); for (j = 0; j < citms.length; ++j) { tmpItems.push(citms[j]); } cluster.clear(); removed++; for (j = 0; j < clusters_.length; ++j) { if (cluster === clusters_[j]) { clusters_.splice(j, 1); } } } } // Add the markers collected into marker cluster to reset reAddItems_(tmpItems); this.redraw_(); }; this.onClickMarker = function (cluster){ }; } /** Cluster */ function Cluster(geoClusterer,map) { var center_ = null; var items_ = []; var geoClusterer_ = geoClusterer; var map_ = map; var clusterMarker_ = null; var zoom_ = map_.getZoom(); this.getItems = function () { return items_; }; this.isInBounds = function (bounds) { if (center_ === null) { return false; } if (!bounds) { bounds = map_.getBounds(); } var ph = geoClusterer_.getProjectionHelper(); var projection = ph.getProjection(); var sw = projection.fromLatLngToDivPixel(bounds.getSouthWest()); var ne = projection.fromLatLngToDivPixel(bounds.getNorthEast()); var mapcenter = map_.getCenter(); var centerxy = projection.fromLatLngToDivPixel(center_); var inViewport = true; var gridSize = geoClusterer_.getGridSize_(); if (zoom_ !== map_.getZoom()) { var dl = map_.getZoom() - zoom_; gridSize = Math.pow(2, dl) * gridSize; } if (ne.x !== sw.x && (centerxy.x + gridSize < sw.x || centerxy.x - gridSize > ne.x)) { inViewport = false; } if (inViewport && (centerxy.y + gridSize < ne.y || centerxy.y - gridSize > sw.y)) { inViewport = false; } return inViewport; }; /** * Get cluster center. */ this.getCenter = function () { return center_; }; /** * Add a marker. */ this.addItem = function (item) { if (center_ === null) { center_ = item.latlng; } items_.push(item); }; /** * Get current zoom level of this cluster. */ this.getCurrentZoom = function () { return zoom_; }; this.redraw_ = function(){ if(!this.isInBounds()) { return; } if(clusterMarker_ == null) { clusterMarker_ = new ClusterMarker_(map_,this,geoClusterer_.onClickMarker); } } /** * Remove all the markers from this cluster. */ this.clear = function () { if (clusterMarker_ !== null) { clusterMarker_.setMap(null); clusterMarker_ = null; } items_ = []; }; /** * Get number of markers. */ this.getItemSize = function () { return items_.length; }; } /** * ClusterMarker_ creates a marker that shows the number of markers that */ function ClusterMarker_(map, cluster, clickCallback) { this.cluster_ = cluster; this.latlng_ = cluster.getCenter(); var count = cluster.getItemSize(); this.count_ = count; this.icon_ = count >= 10 ? "http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/images/m3.png" : "http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/images/m1.png"; this.width_ = count >= 10 ? 66 : 53; this.height_ = count >= 10 ? 65 : 52; this.mstyle_ = "background-image:url(" + this.icon_ + ");"; this.mstyle_ += 'height:' + this.height_ + 'px;line-height:' + this.height_ + 'px;'; this.mstyle_ += 'width:' + this.width_ + 'px;text-align:center;'; this.clickCallback_ = clickCallback; this.setMap(map); } ClusterMarker_.prototype = new google.maps.OverlayView(); ClusterMarker_.prototype.draw = function() { this.projection_ = this.getProjection(); var map = this.getMap(); var pos = this.projection_.fromLatLngToDivPixel(this.latlng_); pos.x -= parseInt(this.width_ / 2, 10); pos.y -= parseInt(this.height_ / 2, 10); this.div_.style.left = pos.x + "px"; this.div_.style.top = pos.y + "px"; var txtColor = 'white'; this.div_.style.cssText = this.mstyle_ + 'cursor:pointer; top:' + pos.y + "px;left:" + pos.x + "px; color:" + txtColor + ";position:absolute;font-size:11px;" + 'font-family:Arial,sans-serif;font-weight:bold'; this.div_.innerHTML = this.count_; }; ClusterMarker_.prototype.onAdd = function() { var map = this.getMap(); var div = document.createElement("div"); div.style.visibility = 'visible'; var cluster = this.cluster_; var callback = this.clickCallback_; google.maps.event.addDomListener(div, "click", function () { callback(cluster); }); this.div_ = div; this.getPanes().mapPane.appendChild(this.div_); }; ClusterMarker_.prototype.remove = function() { this.div_.parentNode.removeChild(this.div_); };
JavaScript
/* * StringBuffer class */ function StringBuffer() { this.buffer = []; } StringBuffer.prototype.append = function append (string) { this.buffer.push(string); return this; }; StringBuffer.prototype.toString = function toString () { return this.buffer.join(""); }; /* * Strip html tags */ function stripTags (str) { return str.replace(/<[^>].*?>/g,""); } /* * Display json with better look */ function formatJson (str) { var tab = 0; var buf = new StringBuffer(); for (var i = 0; i < str.length; i++) { var char = str.charAt(i); if (char == '{' || char == '[') { tab++; char = char + "\n"; for (var j = 0; j < tab; j++) char = char + "\t"; } if (char == '}' || char == ']') { tab--; for (var j = 0; j < tab; j++) char = "\t" + char; char = "\n" + char; } if (char == ',') { char = char + "\n"; for (var j = 0; j < tab; j++) char = char + "\t"; } buf.append(char); } return buf.toString(); }
JavaScript
/*! * jQuery Mobile v1.0b2 * http://jquerymobile.com/ * * Copyright 2010, jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ /*! * jQuery UI Widget @VERSION * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Widget */ (function( $, undefined ) { // jQuery 1.4+ if ( $.cleanData ) { var _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { $( elem ).triggerHandler( "remove" ); } _cleanData( elems ); }; } else { var _remove = $.fn.remove; $.fn.remove = function( selector, keepData ) { return this.each(function() { if ( !keepData ) { if ( !selector || $.filter( selector, [ this ] ).length ) { $( "*", this ).add( [ this ] ).each(function() { $( this ).triggerHandler( "remove" ); }); } } return _remove.call( $(this), selector, keepData ); }); }; } $.widget = function( name, base, prototype ) { var namespace = name.split( "." )[ 0 ], fullName; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName ] = function( elem ) { return !!$.data( elem, name ); }; $[ namespace ] = $[ namespace ] || {}; $[ namespace ][ name ] = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this._createWidget( options, element ); } }; var basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from // $.each( basePrototype, function( key, val ) { // if ( $.isPlainObject(val) ) { // basePrototype[ key ] = $.extend( {}, val ); // } // }); basePrototype.options = $.extend( true, {}, basePrototype.options ); $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { namespace: namespace, widgetName: name, widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, widgetBaseClass: fullName }, prototype ); $.widget.bridge( name, $[ namespace ][ name ] ); }; $.widget.bridge = function( name, object ) { $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = Array.prototype.slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.extend.apply( null, [ true, options ].concat(args) ) : options; // prevent calls to internal methods if ( isMethodCall && options.charAt( 0 ) === "_" ) { return returnValue; } if ( isMethodCall ) { this.each(function() { var instance = $.data( this, name ); if ( !instance ) { throw "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'"; } if ( !$.isFunction( instance[options] ) ) { throw "no such method '" + options + "' for " + name + " widget instance"; } var methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, name ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, name, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this._createWidget( options, element ); } }; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", options: { disabled: false }, _createWidget: function( options, element ) { // $.widget.bridge stores the plugin instance, but we do it anyway // so that it's stored even before the _create function runs $.data( element, this.widgetName, this ); this.element = $( element ); this.options = $.extend( true, {}, this.options, this._getCreateOptions(), options ); var self = this; this.element.bind( "remove." + this.widgetName, function() { self.destroy(); }); this._create(); this._trigger( "create" ); this._init(); }, _getCreateOptions: function() { var options = {}; if ( $.metadata ) { options = $.metadata.get( element )[ this.widgetName ]; } return options; }, _create: function() {}, _init: function() {}, destroy: function() { this.element .unbind( "." + this.widgetName ) .removeData( this.widgetName ); this.widget() .unbind( "." + this.widgetName ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetBaseClass + "-disabled " + "ui-state-disabled" ); }, widget: function() { return this.element; }, option: function( key, value ) { var options = key; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.extend( {}, this.options ); } if (typeof key === "string" ) { if ( value === undefined ) { return this.options[ key ]; } options = {}; options[ key ] = value; } this._setOptions( options ); return this; }, _setOptions: function( options ) { var self = this; $.each( options, function( key, value ) { self._setOption( key, value ); }); return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() [ value ? "addClass" : "removeClass"]( this.widgetBaseClass + "-disabled" + " " + "ui-state-disabled" ) .attr( "aria-disabled", value ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _trigger: function( type, event, data ) { var callback = this.options[ type ]; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); data = data || {}; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( event.originalEvent ) { for ( var i = $.event.props.length, prop; i; ) { prop = $.event.props[ --i ]; event[ prop ] = event.originalEvent[ prop ]; } } this.element.trigger( event, data ); return !( $.isFunction(callback) && callback.call( this.element[0], event, data ) === false || event.isDefaultPrevented() ); } }; })( jQuery ); /* * jQuery Mobile Framework : widget factory extentions for mobile * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.widget", { _getCreateOptions: function() { var elem = this.element, options = {}; $.each( this.options, function( option ) { var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) { return "-" + c.toLowerCase(); }) ); if ( value !== undefined ) { options[ option ] = value; } }); return options; } }); })( jQuery ); /* * jQuery Mobile Framework : resolution and CSS media query related helpers and behavior * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { var $window = $( window ), $html = $( "html" ); /* $.mobile.media method: pass a CSS media type or query and get a bool return note: this feature relies on actual media query support for media queries, though types will work most anywhere examples: $.mobile.media('screen') //>> tests for screen media type $.mobile.media('screen and (min-width: 480px)') //>> tests for screen media type with window width > 480px $.mobile.media('@media screen and (-webkit-min-device-pixel-ratio: 2)') //>> tests for webkit 2x pixel ratio (iPhone 4) */ $.mobile.media = (function() { // TODO: use window.matchMedia once at least one UA implements it var cache = {}, testDiv = $( "<div id='jquery-mediatest'>" ), fakeBody = $( "<body>" ).append( testDiv ); return function( query ) { if ( !( query in cache ) ) { var styleBlock = document.createElement( "style" ), cssrule = "@media " + query + " { #jquery-mediatest { position:absolute; } }"; //must set type for IE! styleBlock.type = "text/css"; if ( styleBlock.styleSheet ){ styleBlock.styleSheet.cssText = cssrule; } else { styleBlock.appendChild( document.createTextNode(cssrule) ); } $html.prepend( fakeBody ).prepend( styleBlock ); cache[ query ] = testDiv.css( "position" ) === "absolute"; fakeBody.add( styleBlock ).remove(); } return cache[ query ]; }; })(); })(jQuery);/* * jQuery Mobile Framework : support tests * Copyright (c) jQuery Project * Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses. */ (function( $, undefined ) { var fakeBody = $( "<body>" ).prependTo( "html" ), fbCSS = fakeBody[ 0 ].style, vendors = [ "webkit", "moz", "o" ], webos = "palmGetResource" in window, //only used to rule out scrollTop bb = window.blackberry; //only used to rule out box shadow, as it's filled opaque on BB // thx Modernizr function propExists( prop ) { var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ), props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " ); for ( var v in props ){ if ( fbCSS[ v ] !== undefined ) { return true; } } } // Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting ) function baseTagTest() { var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/", base = $( "head base" ), fauxEle = null, href = "", link, rebase; if ( !base.length ) { base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" ); } else { href = base.attr( "href" ); } link = $( "<a href='testurl'></a>" ).prependTo( fakeBody ); rebase = link[ 0 ].href; base[ 0 ].href = href ? href : location.pathname; if ( fauxEle ) { fauxEle.remove(); } return rebase.indexOf( fauxBase ) === 0; } // non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683 // allows for inclusion of IE 6+, including Windows Mobile 7 $.mobile.browser = {}; $.mobile.browser.ie = (function() { var v = 3, div = document.createElement( "div" ), a = div.all || []; while ( div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->", a[ 0 ] ); return v > 4 ? v : !v; })(); $.extend( $.support, { orientation: "orientation" in window, touch: "ontouchend" in document, cssTransitions: "WebKitTransitionEvent" in window, pushState: !!history.pushState, mediaquery: $.mobile.media( "only all" ), cssPseudoElement: !!propExists( "content" ), boxShadow: !!propExists( "boxShadow" ) && !bb, scrollTop: ( "pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[ 0 ] ) && !webos, dynamicBaseTag: baseTagTest(), // TODO: This is a weak test. We may want to beef this up later. eventCapture: "addEventListener" in document }); fakeBody.remove(); // $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian) // or that generally work better browsing in regular http for full page refreshes (Opera Mini) // Note: This detection below is used as a last resort. // We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible var nokiaLTE7_3 = (function(){ var ua = window.navigator.userAgent; //The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older return ua.indexOf( "Nokia" ) > -1 && ( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) && ua.indexOf( "AppleWebKit" ) > -1 && ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ ); })(); $.mobile.ajaxBlacklist = // BlackBerry browsers, pre-webkit window.blackberry && !window.WebKitPoint || // Opera Mini window.operamini && Object.prototype.toString.call( window.operamini ) === "[object OperaMini]" || // Symbian webkits pre 7.3 nokiaLTE7_3; // Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices // to render the stylesheets when they're referenced before this script, as we'd recommend doing. // This simply reappends the CSS in place, which for some reason makes it apply if ( nokiaLTE7_3 ) { $(function() { $( "head link[rel=stylesheet]" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" ); }); } // For ruling out shadows via css if ( !$.support.boxShadow ) { $( "html" ).addClass( "ui-mobile-nosupport-boxshadow" ); } })( jQuery );/* * jQuery Mobile Framework : "mouse" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ // This plugin is an experiment for abstracting away the touch and mouse // events so that developers don't have to worry about which method of input // the device their document is loaded on supports. // // The idea here is to allow the developer to register listeners for the // basic mouse events, such as mousedown, mousemove, mouseup, and click, // and the plugin will take care of registering the correct listeners // behind the scenes to invoke the listener at the fastest possible time // for that device, while still retaining the order of event firing in // the traditional mouse environment, should multiple handlers be registered // on the same element for different events. // // The current version exposes the following virtual events to jQuery bind methods: // "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel" (function( $, window, document, undefined ) { var dataPropertyName = "virtualMouseBindings", touchTargetPropertyName = "virtualTouchID", virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ), touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ), activeDocHandlers = {}, resetTimerID = 0, startX = 0, startY = 0, didScroll = false, clickBlockList = [], blockMouseTriggers = false, blockTouchTriggers = false, eventCaptureSupported = $.support.eventCapture, $document = $( document ), nextTouchID = 1, lastTouchID = 0; $.vmouse = { moveDistanceThreshold: 10, clickDistanceThreshold: 10, resetTimerDuration: 1500 }; function getNativeEvent( event ) { while ( event && typeof event.originalEvent !== "undefined" ) { event = event.originalEvent; } return event; } function createVirtualEvent( event, eventType ) { var t = event.type, oe, props, ne, prop, ct, touch, i, j; event = $.Event(event); event.type = eventType; oe = event.originalEvent; props = $.event.props; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( oe ) { for ( i = props.length, prop; i; ) { prop = props[ --i ]; event[ prop ] = oe[ prop ]; } } if ( t.search(/^touch/) !== -1 ) { ne = getNativeEvent( oe ); t = ne.touches; ct = ne.changedTouches; touch = ( t && t.length ) ? t[0] : ( (ct && ct.length) ? ct[ 0 ] : undefined ); if ( touch ) { for ( j = 0, len = touchEventProps.length; j < len; j++){ prop = touchEventProps[ j ]; event[ prop ] = touch[ prop ]; } } } return event; } function getVirtualBindingFlags( element ) { var flags = {}, b, k; while ( element ) { b = $.data( element, dataPropertyName ); for ( k in b ) { if ( b[ k ] ) { flags[ k ] = flags.hasVirtualBinding = true; } } element = element.parentNode; } return flags; } function getClosestElementWithVirtualBinding( element, eventType ) { var b; while ( element ) { b = $.data( element, dataPropertyName ); if ( b && ( !eventType || b[ eventType ] ) ) { return element; } element = element.parentNode; } return null; } function enableTouchBindings() { blockTouchTriggers = false; } function disableTouchBindings() { blockTouchTriggers = true; } function enableMouseBindings() { lastTouchID = 0; clickBlockList.length = 0; blockMouseTriggers = false; // When mouse bindings are enabled, our // touch bindings are disabled. disableTouchBindings(); } function disableMouseBindings() { // When mouse bindings are disabled, our // touch bindings are enabled. enableTouchBindings(); } function startResetTimer() { clearResetTimer(); resetTimerID = setTimeout(function(){ resetTimerID = 0; enableMouseBindings(); }, $.vmouse.resetTimerDuration ); } function clearResetTimer() { if ( resetTimerID ){ clearTimeout( resetTimerID ); resetTimerID = 0; } } function triggerVirtualEvent( eventType, event, flags ) { var defaultPrevented = false, ve; if ( ( flags && flags[ eventType ] ) || ( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) { ve = createVirtualEvent( event, eventType ); $( event.target).trigger( ve ); defaultPrevented = ve.isDefaultPrevented(); } return defaultPrevented; } function mouseEventCallback( event ) { var touchID = $.data(event.target, touchTargetPropertyName); if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ){ triggerVirtualEvent( "v" + event.type, event ); } } function handleTouchStart( event ) { var touches = getNativeEvent( event ).touches, target, flags; if ( touches && touches.length === 1 ) { target = event.target; flags = getVirtualBindingFlags( target ); if ( flags.hasVirtualBinding ) { lastTouchID = nextTouchID++; $.data( target, touchTargetPropertyName, lastTouchID ); clearResetTimer(); disableMouseBindings(); didScroll = false; var t = getNativeEvent( event ).touches[ 0 ]; startX = t.pageX; startY = t.pageY; triggerVirtualEvent( "vmouseover", event, flags ); triggerVirtualEvent( "vmousedown", event, flags ); } } } function handleScroll( event ) { if ( blockTouchTriggers ) { return; } if ( !didScroll ) { triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) ); } didScroll = true; startResetTimer(); } function handleTouchMove( event ) { if ( blockTouchTriggers ) { return; } var t = getNativeEvent( event ).touches[ 0 ], didCancel = didScroll, moveThreshold = $.vmouse.moveDistanceThreshold; didScroll = didScroll || ( Math.abs(t.pageX - startX) > moveThreshold || Math.abs(t.pageY - startY) > moveThreshold ), flags = getVirtualBindingFlags( event.target ); if ( didScroll && !didCancel ) { triggerVirtualEvent( "vmousecancel", event, flags ); } triggerVirtualEvent( "vmousemove", event, flags ); startResetTimer(); } function handleTouchEnd( event ) { if ( blockTouchTriggers ) { return; } disableTouchBindings(); var flags = getVirtualBindingFlags( event.target ), t; triggerVirtualEvent( "vmouseup", event, flags ); if ( !didScroll ) { if ( triggerVirtualEvent( "vclick", event, flags ) ) { // The target of the mouse events that follow the touchend // event don't necessarily match the target used during the // touch. This means we need to rely on coordinates for blocking // any click that is generated. t = getNativeEvent( event ).changedTouches[ 0 ]; clickBlockList.push({ touchID: lastTouchID, x: t.clientX, y: t.clientY }); // Prevent any mouse events that follow from triggering // virtual event notifications. blockMouseTriggers = true; } } triggerVirtualEvent( "vmouseout", event, flags); didScroll = false; startResetTimer(); } function hasVirtualBindings( ele ) { var bindings = $.data( ele, dataPropertyName ), k; if ( bindings ) { for ( k in bindings ) { if ( bindings[ k ] ) { return true; } } } return false; } function dummyMouseHandler(){} function getSpecialEventObject( eventType ) { var realType = eventType.substr( 1 ); return { setup: function( data, namespace ) { // If this is the first virtual mouse binding for this element, // add a bindings object to its data. if ( !hasVirtualBindings( this ) ) { $.data( this, dataPropertyName, {}); } // If setup is called, we know it is the first binding for this // eventType, so initialize the count for the eventType to zero. var bindings = $.data( this, dataPropertyName ); bindings[ eventType ] = true; // If this is the first virtual mouse event for this type, // register a global handler on the document. activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1; if ( activeDocHandlers[ eventType ] === 1 ) { $document.bind( realType, mouseEventCallback ); } // Some browsers, like Opera Mini, won't dispatch mouse/click events // for elements unless they actually have handlers registered on them. // To get around this, we register dummy handlers on the elements. $( this ).bind( realType, dummyMouseHandler ); // For now, if event capture is not supported, we rely on mouse handlers. if ( eventCaptureSupported ) { // If this is the first virtual mouse binding for the document, // register our touchstart handler on the document. activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1; if (activeDocHandlers[ "touchstart" ] === 1) { $document.bind( "touchstart", handleTouchStart ) .bind( "touchend", handleTouchEnd ) // On touch platforms, touching the screen and then dragging your finger // causes the window content to scroll after some distance threshold is // exceeded. On these platforms, a scroll prevents a click event from being // dispatched, and on some platforms, even the touchend is suppressed. To // mimic the suppression of the click event, we need to watch for a scroll // event. Unfortunately, some platforms like iOS don't dispatch scroll // events until *AFTER* the user lifts their finger (touchend). This means // we need to watch both scroll and touchmove events to figure out whether // or not a scroll happenens before the touchend event is fired. .bind( "touchmove", handleTouchMove ) .bind( "scroll", handleScroll ); } } }, teardown: function( data, namespace ) { // If this is the last virtual binding for this eventType, // remove its global handler from the document. --activeDocHandlers[ eventType ]; if ( !activeDocHandlers[ eventType ] ) { $document.unbind( realType, mouseEventCallback ); } if ( eventCaptureSupported ) { // If this is the last virtual mouse binding in existence, // remove our document touchstart listener. --activeDocHandlers[ "touchstart" ]; if ( !activeDocHandlers[ "touchstart" ] ) { $document.unbind( "touchstart", handleTouchStart ) .unbind( "touchmove", handleTouchMove ) .unbind( "touchend", handleTouchEnd ) .unbind( "scroll", handleScroll ); } } var $this = $( this ), bindings = $.data( this, dataPropertyName ); // teardown may be called when an element was // removed from the DOM. If this is the case, // jQuery core may have already stripped the element // of any data bindings so we need to check it before // using it. if ( bindings ) { bindings[ eventType ] = false; } // Unregister the dummy event handler. $this.unbind( realType, dummyMouseHandler ); // If this is the last virtual mouse binding on the // element, remove the binding data from the element. if ( !hasVirtualBindings( this ) ) { $this.removeData( dataPropertyName ); } } }; } // Expose our custom events to the jQuery bind/unbind mechanism. for ( var i = 0; i < virtualEventNames.length; i++ ){ $.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] ); } // Add a capture click handler to block clicks. // Note that we require event capture support for this so if the device // doesn't support it, we punt for now and rely solely on mouse events. if ( eventCaptureSupported ) { document.addEventListener( "click", function( e ){ var cnt = clickBlockList.length, target = e.target, x, y, ele, i, o, touchID; if ( cnt ) { x = e.clientX; y = e.clientY; threshold = $.vmouse.clickDistanceThreshold; // The idea here is to run through the clickBlockList to see if // the current click event is in the proximity of one of our // vclick events that had preventDefault() called on it. If we find // one, then we block the click. // // Why do we have to rely on proximity? // // Because the target of the touch event that triggered the vclick // can be different from the target of the click event synthesized // by the browser. The target of a mouse/click event that is syntehsized // from a touch event seems to be implementation specific. For example, // some browsers will fire mouse/click events for a link that is near // a touch event, even though the target of the touchstart/touchend event // says the user touched outside the link. Also, it seems that with most // browsers, the target of the mouse/click event is not calculated until the // time it is dispatched, so if you replace an element that you touched // with another element, the target of the mouse/click will be the new // element underneath that point. // // Aside from proximity, we also check to see if the target and any // of its ancestors were the ones that blocked a click. This is necessary // because of the strange mouse/click target calculation done in the // Android 2.1 browser, where if you click on an element, and there is a // mouse/click handler on one of its ancestors, the target will be the // innermost child of the touched element, even if that child is no where // near the point of touch. ele = target; while ( ele ) { for ( i = 0; i < cnt; i++ ) { o = clickBlockList[ i ]; touchID = 0; if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) || $.data( ele, touchTargetPropertyName ) === o.touchID ) { // XXX: We may want to consider removing matches from the block list // instead of waiting for the reset timer to fire. e.preventDefault(); e.stopPropagation(); return; } } ele = ele.parentNode; } } }, true); } })( jQuery, window, document ); /* * jQuery Mobile Framework : events * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, window, undefined ) { // add new event shortcuts $.each( ( "touchstart touchmove touchend orientationchange throttledresize " + "tap taphold swipe swipeleft swiperight scrollstart scrollstop" ).split( " " ), function( i, name ) { $.fn[ name ] = function( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; $.attrFn[ name ] = true; }); var supportTouch = $.support.touch, scrollEvent = "touchmove scroll", touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", touchMoveEvent = supportTouch ? "touchmove" : "mousemove"; function triggerCustomEvent( obj, eventType, event ) { var originalType = event.type; event.type = eventType; $.event.handle.call( obj, event ); event.type = originalType; } // also handles scrollstop $.event.special.scrollstart = { enabled: true, setup: function() { var thisObject = this, $this = $( thisObject ), scrolling, timer; function trigger( event, state ) { scrolling = state; triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event ); } // iPhone triggers scroll after a small delay; use touchmove instead $this.bind( scrollEvent, function( event ) { if ( !$.event.special.scrollstart.enabled ) { return; } if ( !scrolling ) { trigger( event, true ); } clearTimeout( timer ); timer = setTimeout(function() { trigger( event, false ); }, 50 ); }); } }; // also handles taphold $.event.special.tap = { setup: function() { var thisObject = this, $this = $( thisObject ); $this.bind( "vmousedown", function( event ) { if ( event.which && event.which !== 1 ) { return false; } var touching = true, origTarget = event.target, origEvent = event.originalEvent, timer; function clearTapHandlers() { touching = false; clearTimeout(timer); $this.unbind( "vclick", clickHandler ) .unbind( "vmousecancel", clearTapHandlers ); } function clickHandler(event) { clearTapHandlers(); // ONLY trigger a 'tap' event if the start target is // the same as the stop target. if ( origTarget == event.target ) { triggerCustomEvent( thisObject, "tap", event ); } } $this.bind( "vmousecancel", clearTapHandlers ) .bind( "vclick", clickHandler ); timer = setTimeout(function() { if ( touching ) { triggerCustomEvent( thisObject, "taphold", event ); } }, 750 ); }); } }; // also handles swipeleft, swiperight $.event.special.swipe = { scrollSupressionThreshold: 10, // More than this horizontal displacement, and we will suppress scrolling. durationThreshold: 1000, // More time than this, and it isn't a swipe. horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this. verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this. setup: function() { var thisObject = this, $this = $( thisObject ); $this.bind( touchStartEvent, function( event ) { var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event, start = { time: ( new Date() ).getTime(), coords: [ data.pageX, data.pageY ], origin: $( event.target ) }, stop; function moveHandler( event ) { if ( !start ) { return; } var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event; stop = { time: ( new Date() ).getTime(), coords: [ data.pageX, data.pageY ] }; // prevent scrolling if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) { event.preventDefault(); } } $this.bind( touchMoveEvent, moveHandler ) .one( touchStopEvent, function( event ) { $this.unbind( touchMoveEvent, moveHandler ); if ( start && stop ) { if ( stop.time - start.time < $.event.special.swipe.durationThreshold && Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold && Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) { start.origin.trigger( "swipe" ) .trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" ); } } start = stop = undefined; }); }); } }; (function( $, window ) { // "Cowboy" Ben Alman var win = $( window ), special_event, get_orientation, last_orientation; $.event.special.orientationchange = special_event = { setup: function() { // If the event is supported natively, return false so that jQuery // will bind to the event using DOM methods. if ( $.support.orientation ) { return false; } // Get the current orientation to avoid initial double-triggering. last_orientation = get_orientation(); // Because the orientationchange event doesn't exist, simulate the // event by testing window dimensions on resize. win.bind( "throttledresize", handler ); }, teardown: function(){ // If the event is not supported natively, return false so that // jQuery will unbind the event using DOM methods. if ( $.support.orientation ) { return false; } // Because the orientationchange event doesn't exist, unbind the // resize event handler. win.unbind( "throttledresize", handler ); }, add: function( handleObj ) { // Save a reference to the bound event handler. var old_handler = handleObj.handler; handleObj.handler = function( event ) { // Modify event object, adding the .orientation property. event.orientation = get_orientation(); // Call the originally-bound event handler and return its result. return old_handler.apply( this, arguments ); }; } }; // If the event is not supported natively, this handler will be bound to // the window resize event to simulate the orientationchange event. function handler() { // Get the current orientation. var orientation = get_orientation(); if ( orientation !== last_orientation ) { // The orientation has changed, so trigger the orientationchange event. last_orientation = orientation; win.trigger( "orientationchange" ); } }; // Get the current page orientation. This method is exposed publicly, should it // be needed, as jQuery.event.special.orientationchange.orientation() $.event.special.orientationchange.orientation = get_orientation = function() { var elem = document.documentElement; return elem && elem.clientWidth / elem.clientHeight < 1.1 ? "portrait" : "landscape"; }; })( jQuery, window ); // throttled resize event (function() { $.event.special.throttledresize = { setup: function() { $( this ).bind( "resize", handler ); }, teardown: function(){ $( this ).unbind( "resize", handler ); } }; var throttle = 250, handler = function() { curr = ( new Date() ).getTime(); diff = curr - lastCall; if ( diff >= throttle ) { lastCall = curr; $( this ).trigger( "throttledresize" ); } else { if ( heldCall ) { clearTimeout( heldCall ); } // Promise a held call will still execute heldCall = setTimeout( handler, throttle - diff ); } }, lastCall = 0, heldCall, curr, diff; })(); $.each({ scrollstop: "scrollstart", taphold: "tap", swipeleft: "swipe", swiperight: "swipe" }, function( event, sourceEvent ) { $.event.special[ event ] = { setup: function() { $( this ).bind( sourceEvent, $.noop ); } }; }); })( jQuery, this ); /*! * jQuery hashchange event - v1.3 - 7/21/2010 * http://benalman.com/projects/jquery-hashchange-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery hashchange event // // *Version: 1.3, Last updated: 7/21/2010* // // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/ // GitHub - http://github.com/cowboy/jquery-hashchange/ // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/ // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5, // Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5. // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/ // // About: Known issues // // While this jQuery hashchange event implementation is quite stable and // robust, there are a few unfortunate browser bugs surrounding expected // hashchange event-based behaviors, independent of any JavaScript // window.onhashchange abstraction. See the following examples for more // information: // // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/ // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/ // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/ // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/ // // Also note that should a browser natively support the window.onhashchange // event, but not report that it does, the fallback polling loop will be used. // // About: Release History // // 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more // "removable" for mobile-only development. Added IE6/7 document.title // support. Attempted to make Iframe as hidden as possible by using // techniques from http://www.paciellogroup.com/blog/?p=604. Added // support for the "shortcut" format $(window).hashchange( fn ) and // $(window).hashchange() like jQuery provides for built-in events. // Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and // lowered its default value to 50. Added <jQuery.fn.hashchange.domain> // and <jQuery.fn.hashchange.src> properties plus document-domain.html // file to address access denied issues when setting document.domain in // IE6/7. // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin // from a page on another domain would cause an error in Safari 4. Also, // IE6/7 Iframe is now inserted after the body (this actually works), // which prevents the page from scrolling when the event is first bound. // Event can also now be bound before DOM ready, but it won't be usable // before then in IE6/7. // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug // where browser version is incorrectly reported as 8.0, despite // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag. // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special // window.onhashchange functionality into a separate plugin for users // who want just the basic event & back button support, without all the // extra awesomeness that BBQ provides. This plugin will be included as // part of jQuery BBQ, but also be available separately. (function($,window,undefined){ '$:nomunge'; // Used by YUI compressor. // Reused string. var str_hashchange = 'hashchange', // Method / object references. doc = document, fake_onhashchange, special = $.event.special, // Does the browser support window.onhashchange? Note that IE8 running in // IE7 compatibility mode reports true for 'onhashchange' in window, even // though the event isn't supported, so also test document.documentMode. doc_mode = doc.documentMode, supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 ); // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { url = url || location.href; return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Method: jQuery.fn.hashchange // // Bind a handler to the window.onhashchange event or trigger all bound // window.onhashchange event handlers. This behavior is consistent with // jQuery's built-in event handlers. // // Usage: // // > jQuery(window).hashchange( [ handler ] ); // // Arguments: // // handler - (Function) Optional handler to be bound to the hashchange // event. This is a "shortcut" for the more verbose form: // jQuery(window).bind( 'hashchange', handler ). If handler is omitted, // all bound window.onhashchange event handlers will be triggered. This // is a shortcut for the more verbose // jQuery(window).trigger( 'hashchange' ). These forms are described in // the <hashchange event> section. // // Returns: // // (jQuery) The initial jQuery collection of elements. // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and // $(elem).hashchange() for triggering, like jQuery does for built-in events. $.fn[ str_hashchange ] = function( fn ) { return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange ); }; // Property: jQuery.fn.hashchange.delay // // The numeric interval (in milliseconds) at which the <hashchange event> // polling loop executes. Defaults to 50. // Property: jQuery.fn.hashchange.domain // // If you're setting document.domain in your JavaScript, and you want hash // history to work in IE6/7, not only must this property be set, but you must // also set document.domain BEFORE jQuery is loaded into the page. This // property is only applicable if you are supporting IE6/7 (or IE8 operating // in "IE7 compatibility" mode). // // In addition, the <jQuery.fn.hashchange.src> property must be set to the // path of the included "document-domain.html" file, which can be renamed or // modified if necessary (note that the document.domain specified must be the // same in both your main JavaScript as well as in this file). // // Usage: // // jQuery.fn.hashchange.domain = document.domain; // Property: jQuery.fn.hashchange.src // // If, for some reason, you need to specify an Iframe src file (for example, // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can // do so using this property. Note that when using this property, history // won't be recorded in IE6/7 until the Iframe src file loads. This property // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7 // compatibility" mode). // // Usage: // // jQuery.fn.hashchange.src = 'path/to/file.html'; $.fn[ str_hashchange ].delay = 50; /* $.fn[ str_hashchange ].domain = null; $.fn[ str_hashchange ].src = null; */ // Event: hashchange event // // Fired when location.hash changes. In browsers that support it, the native // HTML5 window.onhashchange event is used, otherwise a polling loop is // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7 // compatibility" mode), a hidden Iframe is created to allow the back button // and hash-based history to work. // // Usage as described in <jQuery.fn.hashchange>: // // > // Bind an event handler. // > jQuery(window).hashchange( function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).hashchange(); // // A more verbose usage that allows for event namespacing: // // > // Bind an event handler. // > jQuery(window).bind( 'hashchange', function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).trigger( 'hashchange' ); // // Additional Notes: // // * The polling loop and Iframe are not created until at least one handler // is actually bound to the 'hashchange' event. // * If you need the bound handler(s) to execute immediately, in cases where // a location.hash exists on page load, via bookmark or page refresh for // example, use jQuery(window).hashchange() or the more verbose // jQuery(window).trigger( 'hashchange' ). // * The event can be bound before DOM ready, but since it won't be usable // before then in IE6/7 (due to the necessary Iframe), recommended usage is // to bind it inside a DOM ready handler. // Override existing $.event.special.hashchange methods (allowing this plugin // to be defined after jQuery BBQ in BBQ's source code). special[ str_hashchange ] = $.extend( special[ str_hashchange ], { // Called only when the first 'hashchange' event is bound to window. setup: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to create our own. And we don't want to call this // until the user binds to the event, just in case they never do, since it // will create a polling loop and possibly even a hidden Iframe. $( fake_onhashchange.start ); }, // Called only when the last 'hashchange' event is unbound from window. teardown: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to stop ours (if possible). $( fake_onhashchange.stop ); } }); // fake_onhashchange does all the work of triggering the window.onhashchange // event for browsers that don't natively support it, including creating a // polling loop to watch for hash changes and in IE 6/7 creating a hidden // Iframe to enable back and forward. fake_onhashchange = (function(){ var self = {}, timeout_id, // Remember the initial hash so it doesn't get triggered immediately. last_hash = get_fragment(), fn_retval = function(val){ return val; }, history_set = fn_retval, history_get = fn_retval; // Start the polling loop. self.start = function() { timeout_id || poll(); }; // Stop the polling loop. self.stop = function() { timeout_id && clearTimeout( timeout_id ); timeout_id = undefined; }; // This polling loop checks every $.fn.hashchange.delay milliseconds to see // if location.hash has changed, and triggers the 'hashchange' event on // window when necessary. function poll() { var hash = get_fragment(), history_hash = history_get( last_hash ); if ( hash !== last_hash ) { history_set( last_hash = hash, history_hash ); $(window).trigger( str_hashchange ); } else if ( history_hash !== last_hash ) { location.href = location.href.replace( /#.*/, '' ) + history_hash; } timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay ); }; // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv $.browser.msie && !supports_onhashchange && (function(){ // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8 // when running in "IE7 compatibility" mode. var iframe, iframe_src; // When the event is bound and polling starts in IE 6/7, create a hidden // Iframe for history handling. self.start = function(){ if ( !iframe ) { iframe_src = $.fn[ str_hashchange ].src; iframe_src = iframe_src && iframe_src + get_fragment(); // Create hidden Iframe. Attempt to make Iframe as hidden as possible // by using techniques from http://www.paciellogroup.com/blog/?p=604. iframe = $('<iframe tabindex="-1" title="empty"/>').hide() // When Iframe has completely loaded, initialize the history and // start polling. .one( 'load', function(){ iframe_src || history_set( get_fragment() ); poll(); }) // Load Iframe src if specified, otherwise nothing. .attr( 'src', iframe_src || 'javascript:0' ) // Append Iframe after the end of the body to prevent unnecessary // initial page scrolling (yes, this works). .insertAfter( 'body' )[0].contentWindow; // Whenever `document.title` changes, update the Iframe's title to // prettify the back/next history menu entries. Since IE sometimes // errors with "Unspecified error" the very first time this is set // (yes, very useful) wrap this with a try/catch block. doc.onpropertychange = function(){ try { if ( event.propertyName === 'title' ) { iframe.document.title = doc.title; } } catch(e) {} }; } }; // Override the "stop" method since an IE6/7 Iframe was created. Even // if there are no longer any bound event handlers, the polling loop // is still necessary for back/next to work at all! self.stop = fn_retval; // Get history by looking at the hidden Iframe's location.hash. history_get = function() { return get_fragment( iframe.location.href ); }; // Set a new history item by opening and then closing the Iframe // document, *then* setting its location.hash. If document.domain has // been set, update that as well. history_set = function( hash, history_hash ) { var iframe_doc = iframe.document, domain = $.fn[ str_hashchange ].domain; if ( hash !== history_hash ) { // Update Iframe with any initial `document.title` that might be set. iframe_doc.title = doc.title; // Opening the Iframe's document after it has been closed is what // actually adds a history entry. iframe_doc.open(); // Set document.domain for the Iframe document as well, if necessary. domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' ); iframe_doc.close(); // Update the Iframe's hash, for great justice. iframe.location.hash = hash; } }; })(); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return self; })(); })(jQuery,this); /* * jQuery Mobile Framework : "page" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.page", $.mobile.widget, { options: { theme: "c", domCache: false }, _create: function() { var $elem = this.element, o = this.options; if ( this._trigger( "beforeCreate" ) === false ) { return; } $elem.addClass( "ui-page ui-body-" + o.theme ); } }); })( jQuery ); /*! * jQuery Mobile v@VERSION * http://jquerymobile.com/ * * Copyright 2010, jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, window, undefined ) { // jQuery.mobile configurable options $.extend( $.mobile, { // Namespace used framework-wide for data-attrs. Default is no namespace ns: "", // Define the url parameter used for referencing widget-generated sub-pages. // Translates to to example.html&ui-page=subpageIdentifier // hash segment before &ui-page= is used to make Ajax request subPageUrlKey: "ui-page", // Class assigned to page currently in view, and during transitions activePageClass: "ui-page-active", // Class used for "active" button state, from CSS framework activeBtnClass: "ui-btn-active", // Automatically handle clicks and form submissions through Ajax, when same-domain ajaxEnabled: true, // Automatically load and show pages based on location.hash hashListeningEnabled: true, // Set default page transition - 'none' for no transitions defaultPageTransition: "slide", // Minimum scroll distance that will be remembered when returning to a page minScrollBack: screen.height / 2, // Set default dialog transition - 'none' for no transitions defaultDialogTransition: "pop", // Show loading message during Ajax requests // if false, message will not appear, but loading classes will still be toggled on html el loadingMessage: "loading", // Error response message - appears when an Ajax page request fails pageLoadErrorMessage: "Error Loading Page", //automatically initialize the DOM when it's ready autoInitializePage: true, // Support conditions that must be met in order to proceed // default enhanced qualifications are media query support OR IE 7+ gradeA: function(){ return $.support.mediaquery || $.mobile.browser.ie && $.mobile.browser.ie >= 7; }, // TODO might be useful upstream in jquery itself ? keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, // COMMAND COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, // COMMAND_RIGHT NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91 // COMMAND }, // Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value silentScroll: function( ypos ) { if ( $.type( ypos ) !== "number" ) { ypos = $.mobile.defaultHomeScroll; } // prevent scrollstart and scrollstop events $.event.special.scrollstart.enabled = false; setTimeout(function() { window.scrollTo( 0, ypos ); $( document ).trigger( "silentscroll", { x: 0, y: ypos }); }, 20 ); setTimeout(function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, // Take a data attribute property, prepend the namespace // and then camel case the attribute string nsNormalize: function( prop ) { if ( !prop ) { return; } return $.camelCase( $.mobile.ns + prop ); } }); // Mobile version of data and removeData and hasData methods // ensures all data is set and retrieved using jQuery Mobile's data namespace $.fn.jqmData = function( prop, value ) { return this.data( prop ? $.mobile.nsNormalize( prop ) : prop, value ); }; $.jqmData = function( elem, prop, value ) { return $.data( elem, $.mobile.nsNormalize( prop ), value ); }; $.fn.jqmRemoveData = function( prop ) { return this.removeData( $.mobile.nsNormalize( prop ) ); }; $.jqmRemoveData = function( elem, prop ) { return $.removeData( elem, $.mobile.nsNormalize( prop ) ); }; $.jqmHasData = function( elem, prop ) { return $.hasData( elem, $.mobile.nsNormalize( prop ) ); }; // Monkey-patching Sizzle to filter the :jqmData selector var oldFind = $.find; $.find = function( selector, context, ret, extra ) { selector = selector.replace(/:jqmData\(([^)]*)\)/g, "[data-" + ( $.mobile.ns || "" ) + "$1]"); return oldFind.call( this, selector, context, ret, extra ); }; $.extend( $.find, oldFind ); $.find.matches = function( expr, set ) { return $.find( expr, null, null, set ); }; $.find.matchesSelector = function( node, expr ) { return $.find( expr, null, null, [ node ] ).length > 0; }; })( jQuery, this ); /* * jQuery Mobile Framework : core utilities for auto ajax navigation, base tag mgmt, * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ ( function( $, undefined ) { //define vars for interal use var $window = $( window ), $html = $( 'html' ), $head = $( 'head' ), //url path helpers for use in relative url management path = { // This scary looking regular expression parses an absolute URL or its relative // variants (protocol, site, document, query, and hash), into the various // components (protocol, host, path, query, fragment, etc that make up the // URL as well as some other commonly used sub-parts. When used with RegExp.exec() // or String.match, it parses the URL into a results array that looks like this: // // [0]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread#msg-content // [1]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread // [2]: http://jblas:password@mycompany.com:8080/mail/inbox // [3]: http://jblas:password@mycompany.com:8080 // [4]: http: // [5]: jblas:password@mycompany.com:8080 // [6]: jblas:password // [7]: jblas // [8]: password // [9]: mycompany.com:8080 // [10]: mycompany.com // [11]: 8080 // [12]: /mail/inbox // [13]: /mail/ // [14]: inbox // [15]: ?msg=1234&type=unread // [16]: #msg-content // urlParseRE: /^(((([^:\/#\?]+:)?(?:\/\/((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?]+)(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/, //Parse a URL into a structure that allows easy access to //all of the URL components by name. parseUrl: function( url ) { // If we're passed an object, we'll assume that it is // a parsed url object and just return it back to the caller. if ( $.type( url ) === "object" ) { return url; } var u = url || "", matches = path.urlParseRE.exec( url ), results; if ( matches ) { // Create an object that allows the caller to access the sub-matches // by name. Note that IE returns an empty string instead of undefined, // like all other browsers do, so we normalize everything so its consistent // no matter what browser we're running on. results = { href: matches[0] || "", hrefNoHash: matches[1] || "", hrefNoSearch: matches[2] || "", domain: matches[3] || "", protocol: matches[4] || "", authority: matches[5] || "", username: matches[7] || "", password: matches[8] || "", host: matches[9] || "", hostname: matches[10] || "", port: matches[11] || "", pathname: matches[12] || "", directory: matches[13] || "", filename: matches[14] || "", search: matches[15] || "", hash: matches[16] || "" }; } return results || {}; }, //Turn relPath into an asbolute path. absPath is //an optional absolute path which describes what //relPath is relative to. makePathAbsolute: function( relPath, absPath ) { if ( relPath && relPath.charAt( 0 ) === "/" ) { return relPath; } relPath = relPath || ""; absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : ""; var absStack = absPath ? absPath.split( "/" ) : [], relStack = relPath.split( "/" ); for ( var i = 0; i < relStack.length; i++ ) { var d = relStack[ i ]; switch ( d ) { case ".": break; case "..": if ( absStack.length ) { absStack.pop(); } break; default: absStack.push( d ); break; } } return "/" + absStack.join( "/" ); }, //Returns true if both urls have the same domain. isSameDomain: function( absUrl1, absUrl2 ) { return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain; }, //Returns true for any relative variant. isRelativeUrl: function( url ) { // All relative Url variants have one thing in common, no protocol. return path.parseUrl( url ).protocol === ""; }, //Returns true for an absolute url. isAbsoluteUrl: function( url ) { return path.parseUrl( url ).protocol !== ""; }, //Turn the specified realtive URL into an absolute one. This function //can handle all relative variants (protocol, site, document, query, fragment). makeUrlAbsolute: function( relUrl, absUrl ) { if ( !path.isRelativeUrl( relUrl ) ) { return relUrl; } var relObj = path.parseUrl( relUrl ), absObj = path.parseUrl( absUrl ), protocol = relObj.protocol || absObj.protocol, authority = relObj.authority || absObj.authority, hasPath = relObj.pathname !== "", pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ), search = relObj.search || ( !hasPath && absObj.search ) || "", hash = relObj.hash; return protocol + "//" + authority + pathname + search + hash; }, //Add search (aka query) params to the specified url. addSearchParams: function( url, params ) { var u = path.parseUrl( url ), p = ( typeof params === "object" ) ? $.param( params ) : params, s = u.search || "?"; return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" ); }, convertUrlToDataUrl: function( absUrl ) { var u = path.parseUrl( absUrl ); if ( path.isEmbeddedPage( u ) ) { // For embedded pages, remove the dialog hash key as in getFilePath(), // otherwise the Data Url won't match the id of the embedded Page. return u.hash.split( dialogHashKey )[0].replace( /^#/, "" ); } else if ( path.isSameDomain( u, documentBase ) ) { return u.hrefNoHash.replace( documentBase.domain, "" ); } return absUrl; }, //get path from current hash, or from a file path get: function( newPath ) { if( newPath === undefined ) { newPath = location.hash; } return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' ); }, //return the substring of a filepath before the sub-page key, for making a server request getFilePath: function( path ) { var splitkey = '&' + $.mobile.subPageUrlKey; return path && path.split( splitkey )[0].split( dialogHashKey )[0]; }, //set location hash to path set: function( path ) { location.hash = path; }, //test if a given url (string) is a path //NOTE might be exceptionally naive isPath: function( url ) { return ( /\// ).test( url ); }, //return a url path with the window's location protocol/hostname/pathname removed clean: function( url ) { return url.replace( documentBase.domain, "" ); }, //just return the url without an initial # stripHash: function( url ) { return url.replace( /^#/, "" ); }, //remove the preceding hash, any query params, and dialog notations cleanHash: function( hash ) { return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) ); }, //check whether a url is referencing the same domain, or an external domain or different protocol //could be mailto, etc isExternal: function( url ) { var u = path.parseUrl( url ); return u.protocol && u.domain !== documentUrl.domain ? true : false; }, hasProtocol: function( url ) { return ( /^(:?\w+:)/ ).test( url ); }, isEmbeddedPage: function( url ) { var u = path.parseUrl( url ); //if the path is absolute, then we need to compare the url against //both the documentUrl and the documentBase. The main reason for this //is that links embedded within external documents will refer to the //application document, whereas links embedded within the application //document will be resolved against the document base. if ( u.protocol !== "" ) { return ( u.hash && ( u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ) ) ); } return (/^#/).test( u.href ); } }, //will be defined when a link is clicked and given an active class $activeClickedLink = null, //urlHistory is purely here to make guesses at whether the back or forward button was clicked //and provide an appropriate transition urlHistory = { // Array of pages that are visited during a single page load. // Each has a url and optional transition, title, and pageUrl (which represents the file path, in cases where URL is obscured, such as dialogs) stack: [], //maintain an index number for the active page in the stack activeIndex: 0, //get active getActive: function() { return urlHistory.stack[ urlHistory.activeIndex ]; }, getPrev: function() { return urlHistory.stack[ urlHistory.activeIndex - 1 ]; }, getNext: function() { return urlHistory.stack[ urlHistory.activeIndex + 1 ]; }, // addNew is used whenever a new page is added addNew: function( url, transition, title, pageUrl ) { //if there's forward history, wipe it if( urlHistory.getNext() ) { urlHistory.clearForward(); } urlHistory.stack.push( {url : url, transition: transition, title: title, pageUrl: pageUrl } ); urlHistory.activeIndex = urlHistory.stack.length - 1; }, //wipe urls ahead of active index clearForward: function() { urlHistory.stack = urlHistory.stack.slice( 0, urlHistory.activeIndex + 1 ); }, directHashChange: function( opts ) { var back , forward, newActiveIndex; // check if url isp in history and if it's ahead or behind current page $.each( urlHistory.stack, function( i, historyEntry ) { //if the url is in the stack, it's a forward or a back if( opts.currentUrl === historyEntry.url ) { //define back and forward by whether url is older or newer than current page back = i < urlHistory.activeIndex; forward = !back; newActiveIndex = i; } }); // save new page index, null check to prevent falsey 0 result this.activeIndex = newActiveIndex !== undefined ? newActiveIndex : this.activeIndex; if( back ) { opts.isBack(); } else if( forward ) { opts.isForward(); } }, //disable hashchange event listener internally to ignore one change //toggled internally when location.hash is updated to match the url of a successful page load ignoreNextHashChange: false }, //define first selector to receive focus when a page is shown focusable = "[tabindex],a,button:visible,select:visible,input", //queue to hold simultanious page transitions pageTransitionQueue = [], //indicates whether or not page is in process of transitioning isPageTransitioning = false, //nonsense hash change key for dialogs, so they create a history entry dialogHashKey = "&ui-state=dialog", //existing base tag? $base = $head.children( "base" ), //tuck away the original document URL minus any fragment. documentUrl = path.parseUrl( location.href ), //if the document has an embedded base tag, documentBase is set to its //initial value. If a base tag does not exist, then we default to the documentUrl. documentBase = $base.length ? path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), documentUrl.href ) ) : documentUrl, //cache the comparison once. documentBaseDiffers = ( documentUrl.hrefNoHash !== documentBase.hrefNoHash ); //base element management, defined depending on dynamic base tag support var base = $.support.dynamicBaseTag ? { //define base element, for use in routing asset urls that are referenced in Ajax-requested markup element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ), //set the generated BASE element's href attribute to a new page's base path set: function( href ) { base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) ); }, //set the generated BASE element's href attribute to a new page's base path reset: function() { base.element.attr( "href", documentBase.hrefNoHash ); } } : undefined; /* internal utility functions --------------------------------------*/ //direct focus to the page title, or otherwise first focusable element function reFocus( page ) { var lastClicked = page.jqmData( "lastClicked" ); if( lastClicked && lastClicked.length ) { lastClicked.focus(); } else { var pageTitle = page.find( ".ui-title:eq(0)" ); if( pageTitle.length ) { pageTitle.focus(); } else{ page.find( focusable ).eq( 0 ).focus(); } } } //remove active classes after page transition or error function removeActiveLinkClass( forceRemoval ) { if( !!$activeClickedLink && ( !$activeClickedLink.closest( '.ui-page-active' ).length || forceRemoval ) ) { $activeClickedLink.removeClass( $.mobile.activeBtnClass ); } $activeClickedLink = null; } function releasePageTransitionLock() { isPageTransitioning = false; if( pageTransitionQueue.length > 0 ) { $.mobile.changePage.apply( null, pageTransitionQueue.pop() ); } } //function for transitioning between two existing pages function transitionPages( toPage, fromPage, transition, reverse ) { //get current scroll distance var currScroll = $.support.scrollTop ? $window.scrollTop() : true, toScroll = toPage.data( "lastScroll" ) || $.mobile.defaultHomeScroll, screenHeight = getScreenHeight(); //if scrolled down, scroll to top if( currScroll ){ window.scrollTo( 0, $.mobile.defaultHomeScroll ); } //if the Y location we're scrolling to is less than 10px, let it go for sake of smoothness if( toScroll < $.mobile.minScrollBack ){ toScroll = 0; } if( fromPage ) { //set as data for returning to that spot fromPage .height( screenHeight + currScroll ) .jqmData( "lastScroll", currScroll ) .jqmData( "lastClicked", $activeClickedLink ); //trigger before show/hide events fromPage.data( "page" )._trigger( "beforehide", null, { nextPage: toPage } ); } toPage .height( screenHeight + toScroll ) .data( "page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } ); //clear page loader $.mobile.hidePageLoadingMsg(); //find the transition handler for the specified transition. If there //isn't one in our transitionHandlers dictionary, use the default one. //call the handler immediately to kick-off the transition. var th = $.mobile.transitionHandlers[transition || "none"] || $.mobile.defaultTransitionHandler, promise = th( transition, reverse, toPage, fromPage ); promise.done(function() { //reset toPage height bac toPage.height( "" ); //jump to top or prev scroll, sometimes on iOS the page has not rendered yet. if( toScroll ){ $.mobile.silentScroll( toScroll ); $( document ).one( "silentscroll", function() { reFocus( toPage ); } ); } else{ reFocus( toPage ); } //trigger show/hide events if( fromPage ) { fromPage.height("").data( "page" )._trigger( "hide", null, { nextPage: toPage } ); } //trigger pageshow, define prevPage as either fromPage or empty jQuery obj toPage.data( "page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } ); }); return promise; } //simply set the active page's minimum height to screen height, depending on orientation function getScreenHeight(){ var orientation = jQuery.event.special.orientationchange.orientation(), port = orientation === "portrait", winMin = port ? 480 : 320, screenHeight = port ? screen.availHeight : screen.availWidth, winHeight = Math.max( winMin, $( window ).height() ), pageMin = Math.min( screenHeight, winHeight ); return pageMin; } //simply set the active page's minimum height to screen height, depending on orientation function resetActivePageHeight(){ $( "." + $.mobile.activePageClass ).css( "min-height", getScreenHeight() ); } //shared page enhancements function enhancePage( $page, role ) { // If a role was specified, make sure the data-role attribute // on the page element is in sync. if( role ) { $page.attr( "data-" + $.mobile.ns + "role", role ); } //run page plugin $page.page(); } /* exposed $.mobile methods */ //animation complete callback $.fn.animationComplete = function( callback ) { if( $.support.cssTransitions ) { return $( this ).one( 'webkitAnimationEnd', callback ); } else{ // defer execution for consistency between webkit/non webkit setTimeout( callback, 0 ); return $( this ); } }; //update location.hash, with or without triggering hashchange event //TODO - deprecate this one at 1.0 $.mobile.updateHash = path.set; //expose path object on $.mobile $.mobile.path = path; //expose base object on $.mobile $.mobile.base = base; //url stack, useful when plugins need to be aware of previous pages viewed //TODO: deprecate this one at 1.0 $.mobile.urlstack = urlHistory.stack; //history stack $.mobile.urlHistory = urlHistory; //default non-animation transition handler $.mobile.noneTransitionHandler = function( name, reverse, $toPage, $fromPage ) { if ( $fromPage ) { $fromPage.removeClass( $.mobile.activePageClass ); } $toPage.addClass( $.mobile.activePageClass ); return $.Deferred().resolve( name, reverse, $toPage, $fromPage ).promise(); }; //default handler for unknown transitions $.mobile.defaultTransitionHandler = $.mobile.noneTransitionHandler; //transition handler dictionary for 3rd party transitions $.mobile.transitionHandlers = { none: $.mobile.defaultTransitionHandler }; //enable cross-domain page support $.mobile.allowCrossDomainPages = false; //return the original document url $.mobile.getDocumentUrl = function(asParsedObject) { return asParsedObject ? $.extend( {}, documentUrl ) : documentUrl.href; }; //return the original document base url $.mobile.getDocumentBase = function(asParsedObject) { return asParsedObject ? $.extend( {}, documentBase ) : documentBase.href; }; // Load a page into the DOM. $.mobile.loadPage = function( url, options ) { // This function uses deferred notifications to let callers // know when the page is done loading, or if an error has occurred. var deferred = $.Deferred(), // The default loadPage options with overrides specified by // the caller. settings = $.extend( {}, $.mobile.loadPage.defaults, options ), // The DOM element for the page after it has been loaded. page = null, // If the reloadPage option is true, and the page is already // in the DOM, dupCachedPage will be set to the page element // so that it can be removed after the new version of the // page is loaded off the network. dupCachedPage = null, // determine the current base url findBaseWithDefault = function(){ var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) ); return closestBase || documentBase.hrefNoHash; }, // The absolute version of the URL passed into the function. This // version of the URL may contain dialog/subpage params in it. absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() ); // If the caller provided data, and we're using "get" request, // append the data to the URL. if ( settings.data && settings.type === "get" ) { absUrl = path.addSearchParams( absUrl, settings.data ); settings.data = undefined; } // The absolute version of the URL minus any dialog/subpage params. // In otherwords the real URL of the page to be loaded. var fileUrl = path.getFilePath( absUrl ), // The version of the Url actually stored in the data-url attribute of // the page. For embedded pages, it is just the id of the page. For pages // within the same domain as the document base, it is the site relative // path. For cross-domain pages (Phone Gap only) the entire absolute Url // used to load the page. dataUrl = path.convertUrlToDataUrl( absUrl ); // Make sure we have a pageContainer to work with. settings.pageContainer = settings.pageContainer || $.mobile.pageContainer; // Check to see if the page already exists in the DOM. page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" ); // Reset base to the default document base. if ( base ) { base.reset(); } // If the page we are interested in is already in the DOM, // and the caller did not indicate that we should force a // reload of the file, we are done. Otherwise, track the // existing page as a duplicated. if ( page.length ) { if ( !settings.reloadPage ) { enhancePage( page, settings.role ); deferred.resolve( absUrl, options, page ); return deferred.promise(); } dupCachedPage = page; } if ( settings.showLoadMsg ) { // This configurable timeout allows cached pages a brief delay to load without showing a message var loadMsgDelay = setTimeout(function(){ $.mobile.showPageLoadingMsg(); }, settings.loadMsgDelay ), // Shared logic for clearing timeout and removing message. hideMsg = function(){ // Stop message show timer clearTimeout( loadMsgDelay ); // Hide loading message $.mobile.hidePageLoadingMsg(); }; } if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) { deferred.reject( absUrl, options ); } else { // Load the new page. $.ajax({ url: fileUrl, type: settings.type, data: settings.data, dataType: "html", success: function( html ) { //pre-parse html to check for a data-url, //use it as the new fileUrl, base path, etc var all = $( "<div></div>" ), //page title regexp newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1, // TODO handle dialogs again pageElemRegex = new RegExp( ".*(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>).*" ), dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" ); // data-url must be provided for the base tag so resource requests can be directed to the // correct url. loading into a temprorary element makes these requests immediately if( pageElemRegex.test( html ) && RegExp.$1 && dataUrlRegex.test( RegExp.$1 ) && RegExp.$1 ) { url = fileUrl = path.getFilePath( RegExp.$1 ); } else{ } if ( base ) { base.set( fileUrl ); } //workaround to allow scripts to execute when included in page divs all.get( 0 ).innerHTML = html; page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first(); //if page elem couldn't be found, create one and insert the body element's contents if( !page.length ){ page = $( "<div data-" + $.mobile.ns + "role='page'>" + html.split( /<\/?body[^>]*>/gmi )[1] + "</div>" ); } if ( newPageTitle && !page.jqmData( "title" ) ) { page.jqmData( "title", newPageTitle ); } //rewrite src and href attrs to use a base url if( !$.support.dynamicBaseTag ) { var newPath = path.get( fileUrl ); page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() { var thisAttr = $( this ).is( '[href]' ) ? 'href' : $(this).is('[src]') ? 'src' : 'action', thisUrl = $( this ).attr( thisAttr ); // XXX_jblas: We need to fix this so that it removes the document // base URL, and then prepends with the new page URL. //if full path exists and is same, chop it - helps IE out thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' ); if( !/^(\w+:|#|\/)/.test( thisUrl ) ) { $( this ).attr( thisAttr, newPath + thisUrl ); } }); } //append to page and enhance page .attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) ) .appendTo( settings.pageContainer ); // wait for page creation to leverage options defined on widget page.one('pagecreate', function(){ // when dom caching is not enabled bind to remove the page on hide if( !page.data("page").options.domCache ){ page.bind( "pagehide.remove", function(){ $(this).remove(); }); } }); enhancePage( page, settings.role ); // Enhancing the page may result in new dialogs/sub pages being inserted // into the DOM. If the original absUrl refers to a sub-page, that is the // real page we are interested in. if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) { page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" ); } //bind pageHide to removePage after it's hidden, if the page options specify to do so // Remove loading message. if ( settings.showLoadMsg ) { hideMsg(); } deferred.resolve( absUrl, options, page, dupCachedPage ); }, error: function() { //set base back to current path if( base ) { base.set( path.get() ); } // Remove loading message. if ( settings.showLoadMsg ) { // Remove loading message. hideMsg(); //show error message $( "<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>"+ $.mobile.pageLoadErrorMessage +"</h1></div>" ) .css({ "display": "block", "opacity": 0.96, "top": $window.scrollTop() + 100 }) .appendTo( settings.pageContainer ) .delay( 800 ) .fadeOut( 400, function() { $( this ).remove(); }); } deferred.reject( absUrl, options ); } }); } return deferred.promise(); }; $.mobile.loadPage.defaults = { type: "get", data: undefined, reloadPage: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. showLoadMsg: false, pageContainer: undefined, loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message. }; // Show a specific page in the page container. $.mobile.changePage = function( toPage, options ) { // XXX: REMOVE_BEFORE_SHIPPING_1.0 // This is temporary code that makes changePage() compatible with previous alpha versions. if ( typeof options !== "object" ) { var opts = null; // Map old-style call signature for form submit to the new options object format. if ( typeof toPage === "object" && toPage.url && toPage.type ) { opts = { type: toPage.type, data: toPage.data, forcePageLoad: true }; toPage = toPage.url; } // The arguments passed into the function need to be re-mapped // to the new options object format. var len = arguments.length; if ( len > 1 ) { var argNames = [ "transition", "reverse", "changeHash", "fromHashChange" ], i; for ( i = 1; i < len; i++ ) { var a = arguments[ i ]; if ( typeof a !== "undefined" ) { opts = opts || {}; opts[ argNames[ i - 1 ] ] = a; } } } // If an options object was created, then we know changePage() was called // with an old signature. if ( opts ) { return $.mobile.changePage( toPage, opts ); } } // XXX: REMOVE_BEFORE_SHIPPING_1.0 // If we are in the midst of a transition, queue the current request. // We'll call changePage() once we're done with the current transition to // service the request. if( isPageTransitioning ) { pageTransitionQueue.unshift( arguments ); return; } // Set the isPageTransitioning flag to prevent any requests from // entering this method while we are in the midst of loading a page // or transitioning. isPageTransitioning = true; var settings = $.extend( {}, $.mobile.changePage.defaults, options ); // Make sure we have a pageContainer to work with. settings.pageContainer = settings.pageContainer || $.mobile.pageContainer; // If the caller passed us a url, call loadPage() // to make sure it is loaded into the DOM. We'll listen // to the promise object it returns so we know when // it is done loading or if an error ocurred. if ( typeof toPage == "string" ) { $.mobile.loadPage( toPage, settings ) .done(function( url, options, newPage, dupCachedPage ) { isPageTransitioning = false; options.duplicateCachedPage = dupCachedPage; $.mobile.changePage( newPage, options ); }) .fail(function( url, options ) { // XXX_jblas: Fire off changepagefailed notificaiton. isPageTransitioning = false; //clear out the active button state removeActiveLinkClass( true ); //release transition lock so navigation is free again releasePageTransitionLock(); settings.pageContainer.trigger("changepagefailed"); }); return; } // The caller passed us a real page DOM element. Update our // internal state and then trigger a transition to the page. var mpc = settings.pageContainer, fromPage = $.mobile.activePage, url = toPage.jqmData( "url" ), // The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path pageUrl = url, fileUrl = path.getFilePath( url ), active = urlHistory.getActive(), activeIsInitialPage = urlHistory.activeIndex === 0, historyDir = 0, pageTitle = document.title, isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog"; // Let listeners know we're about to change the current page. mpc.trigger( "beforechangepage" ); // If we are trying to transition to the same page that we are currently on ignore the request. // an illegal same page request is defined by the current page being the same as the url, as long as there's history // and toPage is not an array or object (those are allowed to be "same") // // XXX_jblas: We need to remove this at some point when we allow for transitions // to the same page. if( fromPage && fromPage[0] === toPage[0] ) { isPageTransitioning = false; mpc.trigger( "changepage" ); return; } // We need to make sure the page we are given has already been enhanced. enhancePage( toPage, settings.role ); // If the changePage request was sent from a hashChange event, check to see if the // page is already within the urlHistory stack. If so, we'll assume the user hit // the forward/back button and will try to match the transition accordingly. if( settings.fromHashChange ) { urlHistory.directHashChange({ currentUrl: url, isBack: function() { historyDir = -1; }, isForward: function() { historyDir = 1; } }); } // Kill the keyboard. // XXX_jblas: We need to stop crawling the entire document to kill focus. Instead, // we should be tracking focus with a live() handler so we already have // the element in hand at this point. // Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement // is undefined when we are in an IFrame. try { $( document.activeElement || "" ).add( "input:focus, textarea:focus, select:focus" ).blur(); } catch(e) {} // If we're displaying the page as a dialog, we don't want the url // for the dialog content to be used in the hash. Instead, we want // to append the dialogHashKey to the url of the current page. if ( isDialog && active ) { url = active.url + dialogHashKey; } // Set the location hash. if( settings.changeHash !== false && url ) { //disable hash listening temporarily urlHistory.ignoreNextHashChange = true; //update hash and history path.set( url ); } //if title element wasn't found, try the page div data attr too var newPageTitle = toPage.jqmData( "title" ) || toPage.children(":jqmData(role='header')").find(".ui-title" ).text(); if( !!newPageTitle && pageTitle == document.title ) { pageTitle = newPageTitle; } //add page to history stack if it's not back or forward if( !historyDir ) { urlHistory.addNew( url, settings.transition, pageTitle, pageUrl ); } //set page title document.title = urlHistory.getActive().title; //set "toPage" as activePage $.mobile.activePage = toPage; // Make sure we have a transition defined. settings.transition = settings.transition || ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) || ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition ); // If we're navigating back in the URL history, set reverse accordingly. settings.reverse = settings.reverse || historyDir < 0; transitionPages( toPage, fromPage, settings.transition, settings.reverse ) .done(function() { removeActiveLinkClass(); //if there's a duplicateCachedPage, remove it from the DOM now that it's hidden if ( settings.duplicateCachedPage ) { settings.duplicateCachedPage.remove(); } //remove initial build class (only present on first pageshow) $html.removeClass( "ui-mobile-rendering" ); releasePageTransitionLock(); // Let listeners know we're all done changing the current page. mpc.trigger( "changepage" ); }); }; $.mobile.changePage.defaults = { transition: undefined, reverse: false, changeHash: true, fromHashChange: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. duplicateCachedPage: undefined, pageContainer: undefined, showLoadMsg: true //loading message shows by default when pages are being fetched during changePage }; /* Event Bindings - hashchange, submit, and click */ function findClosestLink( ele ) { while ( ele ) { if ( ele.nodeName.toLowerCase() == "a" ) { break; } ele = ele.parentNode; } return ele; } // The base URL for any given element depends on the page it resides in. function getClosestBaseUrl( ele ) { // Find the closest page and extract out its url. var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ), base = documentBase.hrefNoHash; if ( !url || !path.isPath( url ) ) { url = base; } return path.makeUrlAbsolute( url, base); } //The following event bindings should be bound after mobileinit has been triggered //the following function is called in the init file $.mobile._registerInternalEvents = function(){ //bind to form submit events, handle with Ajax $( "form" ).live('submit', function( event ) { var $this = $( this ); if( !$.mobile.ajaxEnabled || $this.is( ":jqmData(ajax='false')" ) ) { return; } var type = $this.attr( "method" ), target = $this.attr( "target" ), url = $this.attr( "action" ); // If no action is specified, browsers default to using the // URL of the document containing the form. Since we dynamically // pull in pages from external documents, the form should submit // to the URL for the source document of the page containing // the form. if ( !url ) { // Get the @data-url for the page containing the form. url = getClosestBaseUrl( $this ); if ( url === documentBase.hrefNoHash ) { // The url we got back matches the document base, // which means the page must be an internal/embedded page, // so default to using the actual document url as a browser // would. url = documentUrl.hrefNoSearch; } } url = path.makeUrlAbsolute( url, getClosestBaseUrl($this) ); //external submits use regular HTTP if( path.isExternal( url ) || target ) { return; } $.mobile.changePage( url, { type: type && type.length && type.toLowerCase() || "get", data: $this.serialize(), transition: $this.jqmData( "transition" ), direction: $this.jqmData( "direction" ), reloadPage: true } ); event.preventDefault(); }); //add active state on vclick $( document ).bind( "vclick", function( event ) { var link = findClosestLink( event.target ); if ( link ) { if ( path.parseUrl( link.getAttribute( "href" ) || "#" ).hash !== "#" ) { $( link ).closest( ".ui-btn" ).not( ".ui-disabled" ).addClass( $.mobile.activeBtnClass ); $( "." + $.mobile.activePageClass + " .ui-btn" ).not( link ).blur(); } } }); // click routing - direct to HTTP or Ajax, accordingly $( document ).bind( "click", function( event ) { var link = findClosestLink( event.target ); if ( !link ) { return; } var $link = $( link ), //remove active link class if external (then it won't be there if you come back) httpCleanup = function(){ window.setTimeout( function() { removeActiveLinkClass( true ); }, 200 ); }; //if there's a data-rel=back attr, go back in history if( $link.is( ":jqmData(rel='back')" ) ) { window.history.back(); return false; } //if ajax is disabled, exit early if( !$.mobile.ajaxEnabled ){ httpCleanup(); //use default click handling return; } var baseUrl = getClosestBaseUrl( $link ), //get href, if defined, otherwise default to empty hash href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl ); // XXX_jblas: Ideally links to application pages should be specified as // an url to the application document with a hash that is either // the site relative path or id to the page. But some of the // internal code that dynamically generates sub-pages for nested // lists and select dialogs, just write a hash in the link they // create. This means the actual URL path is based on whatever // the current value of the base tag is at the time this code // is called. For now we are just assuming that any url with a // hash in it is an application page reference. if ( href.search( "#" ) != -1 ) { href = href.replace( /[^#]*#/, "" ); if ( !href ) { //link was an empty hash meant purely //for interaction, so we ignore it. event.preventDefault(); return; } else if ( path.isPath( href ) ) { //we have apath so make it the href we want to load. href = path.makeUrlAbsolute( href, baseUrl ); } else { //we have a simple id so use the documentUrl as its base. href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash ); } } // Should we handle this link, or let the browser deal with it? var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ), // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR // requests if the document doing the request was loaded via the file:// protocol. // This is usually to allow the application to "phone home" and fetch app specific // data. We normally let the browser handle external/cross-domain urls, but if the // allowCrossDomainPages option is true, we will allow cross-domain http/https // requests to go through our page loading logic. isCrossDomainPageLoad = ( $.mobile.allowCrossDomainPages && documentUrl.protocol === "file:" && href.search( /^https?:/ ) != -1 ), //check for protocol or rel and its not an embedded page //TODO overlap in logic from isExternal, rel=external check should be // moved into more comprehensive isExternalLink isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !isCrossDomainPageLoad ); $activeClickedLink = $link.closest( ".ui-btn" ); if( isExternal ) { httpCleanup(); //use default click handling return; } //use ajax var transition = $link.jqmData( "transition" ), direction = $link.jqmData( "direction" ), reverse = ( direction && direction === "reverse" ) || // deprecated - remove by 1.0 $link.jqmData( "back" ), //this may need to be more specific as we use data-rel more role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined; $.mobile.changePage( href, { transition: transition, reverse: reverse, role: role } ); event.preventDefault(); }); //prefetch pages when anchors with data-prefetch are encountered $( ".ui-page" ).live( "pageshow.prefetch", function(){ var urls = []; $( this ).find( "a:jqmData(prefetch)" ).each(function(){ var url = $( this ).attr( "href" ); if ( url && $.inArray( url, urls ) === -1 ) { urls.push( url ); $.mobile.loadPage( url ); } }); } ); //hashchange event handler $window.bind( "hashchange", function( e, triggered ) { //find first page via hash var to = path.stripHash( location.hash ), //transition is false if it's the first page, undefined otherwise (and may be overridden by default) transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined; //if listening is disabled (either globally or temporarily), or it's a dialog hash if( !$.mobile.hashListeningEnabled || urlHistory.ignoreNextHashChange ) { urlHistory.ignoreNextHashChange = false; return; } // special case for dialogs if( urlHistory.stack.length > 1 && to.indexOf( dialogHashKey ) > -1 ) { // If current active page is not a dialog skip the dialog and continue // in the same direction if(!$.mobile.activePage.is( ".ui-dialog" )) { //determine if we're heading forward or backward and continue accordingly past //the current dialog urlHistory.directHashChange({ currentUrl: to, isBack: function() { window.history.back(); }, isForward: function() { window.history.forward(); } }); // prevent changepage return; } else { var setTo = function() { to = $.mobile.urlHistory.getActive().pageUrl; }; // if the current active page is a dialog and we're navigating // to a dialog use the dialog objected saved in the stack urlHistory.directHashChange({ currentUrl: to, isBack: setTo, isForward: setTo }); } } //if to is defined, load it if ( to ) { to = ( typeof to === "string" && !path.isPath( to ) ) ? ( '#' + to ) : to; $.mobile.changePage( to, { transition: transition, changeHash: false, fromHashChange: true } ); } //there's no hash, go to the first page in the dom else { $.mobile.changePage( $.mobile.firstPage, { transition: transition, changeHash: false, fromHashChange: true } ); } }); //set page min-heights to be device specific $( document ).bind( "pageshow", resetActivePageHeight ); $( window ).bind( "throttledresize", resetActivePageHeight ); };//_registerInternalEvents callback })( jQuery ); /*! * jQuery Mobile v@VERSION * http://jquerymobile.com/ * * Copyright 2010, jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, window, undefined ) { function css3TransitionHandler( name, reverse, $to, $from ) { var deferred = new $.Deferred(), reverseClass = reverse ? " reverse" : "", viewportClass = "ui-mobile-viewport-transitioning viewport-" + name, doneFunc = function() { $to.add( $from ).removeClass( "out in reverse " + name ); if ( $from ) { $from.removeClass( $.mobile.activePageClass ); } $to.parent().removeClass( viewportClass ); deferred.resolve( name, reverse, $to, $from ); }; $to.animationComplete( doneFunc ); $to.parent().addClass( viewportClass ); if ( $from ) { $from.addClass( name + " out" + reverseClass ); } $to.addClass( $.mobile.activePageClass + " " + name + " in" + reverseClass ); return deferred.promise(); } // Make our transition handler public. $.mobile.css3TransitionHandler = css3TransitionHandler; // If the default transition handler is the 'none' handler, replace it with our handler. if ( $.mobile.defaultTransitionHandler === $.mobile.noneTransitionHandler ) { $.mobile.defaultTransitionHandler = css3TransitionHandler; } })( jQuery, this ); /* * jQuery Mobile Framework : "degradeInputs" plugin - degrades inputs to another type after custom enhancements are made. * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.mobile.page.prototype.options.degradeInputs = { color: false, date: false, datetime: false, "datetime-local": false, email: false, month: false, number: false, range: "number", search: true, tel: false, time: false, url: false, week: false }; $.mobile.page.prototype.options.keepNative = ":jqmData(role='none'), :jqmData(role='nojs')"; //auto self-init widgets $( document ).bind( "pagecreate enhance", function( e ){ var page = $( e.target ).data( "page" ), o = page.options; // degrade inputs to avoid poorly implemented native functionality $( e.target ).find( "input" ).not( o.keepNative ).each(function() { var $this = $( this ), type = this.getAttribute( "type" ), optType = o.degradeInputs[ type ] || "text"; if ( o.degradeInputs[ type ] ) { $this.replaceWith( $( "<div>" ).html( $this.clone() ).html() .replace( /\s+type=["']?\w+['"]?/, " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\" " ) ); } }); }); })( jQuery );/* * jQuery Mobile Framework : "dialog" plugin. * Copyright (c) jQuery Project * Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses. */ (function( $, window, undefined ) { $.widget( "mobile.dialog", $.mobile.widget, { options: { closeBtnText : "Close", theme : "a", initSelector : ":jqmData(role='dialog')" }, _create: function() { var $el = this.element, pageTheme = $el.attr( "class" ).match( /ui-body-[a-z]/ ); if( pageTheme.length ){ $el.removeClass( pageTheme[ 0 ] ); } $el.addClass( "ui-body-" + this.options.theme ); // Class the markup for dialog styling // Set aria role $el.attr( "role", "dialog" ) .addClass( "ui-dialog" ) .find( ":jqmData(role='header')" ) .addClass( "ui-corner-top ui-overlay-shadow" ) .prepend( "<a href='#' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "rel='back' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" ) .end() .find( ":jqmData(role='content'),:jqmData(role='footer')" ) .last() .addClass( "ui-corner-bottom ui-overlay-shadow" ); /* bind events - clicks and submits should use the closing transition that the dialog opened with unless a data-transition is specified on the link/form - if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally */ $el.bind( "vclick submit", function( event ) { var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ), active; if ( $target.length && !$target.jqmData( "transition" ) ) { active = $.mobile.urlHistory.getActive() || {}; $target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) ) .attr( "data-" + $.mobile.ns + "direction", "reverse" ); } }) .bind( "pagehide", function() { $( this ).find( "." + $.mobile.activeBtnClass ).removeClass( $.mobile.activeBtnClass ); }); }, // Close method goes back in history close: function() { window.history.back(); } }); //auto self-init widgets $( $.mobile.dialog.prototype.options.initSelector ).live( "pagecreate", function(){ $( this ).dialog(); }); })( jQuery, this ); /* * jQuery Mobile Framework : This plugin handles theming and layout of headers, footers, and content areas * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.mobile.page.prototype.options.backBtnText = "Back"; $.mobile.page.prototype.options.addBackBtn = false; $.mobile.page.prototype.options.backBtnTheme = null; $.mobile.page.prototype.options.headerTheme = "a"; $.mobile.page.prototype.options.footerTheme = "a"; $.mobile.page.prototype.options.contentTheme = null; $( ":jqmData(role='page'), :jqmData(role='dialog')" ).live( "pagecreate", function( e ) { var $page = $( this ), o = $page.data( "page" ).options, pageTheme = o.theme; $( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", this ).each(function() { var $this = $( this ), role = $this.jqmData( "role" ), theme = $this.jqmData( "theme" ), $headeranchors, leftbtn, rightbtn, backBtn; $this.addClass( "ui-" + role ); //apply theming and markup modifications to page,header,content,footer if ( role === "header" || role === "footer" ) { var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme; //add theme class $this.addClass( "ui-bar-" + thisTheme ); // Add ARIA role $this.attr( "role", role === "header" ? "banner" : "contentinfo" ); // Right,left buttons $headeranchors = $this.children( "a" ); leftbtn = $headeranchors.hasClass( "ui-btn-left" ); rightbtn = $headeranchors.hasClass( "ui-btn-right" ); if ( !leftbtn ) { leftbtn = $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length; } if ( !rightbtn ) { rightbtn = $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length; } // Auto-add back btn on pages beyond first view if ( o.addBackBtn && role === "header" && $( ".ui-page" ).length > 1 && $this.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) && !leftbtn ) { backBtn = $( "<a href='#' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" ).prependTo( $this ); // If theme is provided, override default inheritance backBtn.attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme ); } // Page title $this.children( "h1, h2, h3, h4, h5, h6" ) .addClass( "ui-title" ) // Regardless of h element number in src, it becomes h1 for the enhanced page .attr({ "tabindex": "0", "role": "heading", "aria-level": "1" }); } else if ( role === "content" ) { $this.addClass( "ui-body-" + ( theme || pageTheme || o.contentTheme ) ); // Add ARIA role $this.attr( "role", "main" ); } }); }); })( jQuery );/* * jQuery Mobile Framework : "collapsible" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.collapsible", $.mobile.widget, { options: { expandCueText: " click to expand contents", collapseCueText: " click to collapse contents", collapsed: false, heading: ">:header,>legend", theme: null, iconTheme: "d", initSelector: ":jqmData(role='collapsible')" }, _create: function() { var $el = this.element, o = this.options, collapsibleContain = $el.addClass( "ui-collapsible-contain" ), collapsibleHeading = $el.find( o.heading ).eq( 0 ), collapsibleContent = collapsibleContain.wrapInner( "<div class='ui-collapsible-content'></div>" ).find( ".ui-collapsible-content" ), collapsibleParent = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" ); // Replace collapsibleHeading if it's a legend if ( collapsibleHeading.is( "legend" ) ) { collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading ); collapsibleHeading.next().remove(); } collapsibleHeading //drop heading in before content .insertBefore( collapsibleContent ) //modify markup & attributes .addClass( "ui-collapsible-heading" ) .append( "<span class='ui-collapsible-heading-status'></span>" ) .wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" ) .find( "a:eq(0)" ) .buttonMarkup({ shadow: !collapsibleParent.length, corners: false, iconPos: "left", icon: "plus", theme: o.theme }) .find( ".ui-icon" ) .removeAttr( "class" ) .buttonMarkup({ shadow: true, corners: true, iconPos: "notext", icon: "plus", theme: o.iconTheme }); if ( !collapsibleParent.length ) { collapsibleHeading .find( "a:eq(0)" ) .addClass( "ui-corner-all" ) .find( ".ui-btn-inner" ) .addClass( "ui-corner-all" ); } else { if ( collapsibleContain.jqmData( "collapsible-last" ) ) { collapsibleHeading .find( "a:eq(0), .ui-btn-inner" ) .addClass( "ui-corner-bottom" ); } } //events collapsibleContain .bind( "collapse", function( event ) { if ( ! event.isDefaultPrevented() && $( event.target ).closest( ".ui-collapsible-contain" ).is( collapsibleContain ) ) { event.preventDefault(); collapsibleHeading .addClass( "ui-collapsible-heading-collapsed" ) .find( ".ui-collapsible-heading-status" ) .text( o.expandCueText ) .end() .find( ".ui-icon" ) .removeClass( "ui-icon-minus" ) .addClass( "ui-icon-plus" ); collapsibleContent.addClass( "ui-collapsible-content-collapsed" ).attr( "aria-hidden", true ); if ( collapsibleContain.jqmData( "collapsible-last" ) ) { collapsibleHeading .find( "a:eq(0), .ui-btn-inner" ) .addClass( "ui-corner-bottom" ); } } }) .bind( "expand", function( event ) { if ( !event.isDefaultPrevented() ) { event.preventDefault(); collapsibleHeading .removeClass( "ui-collapsible-heading-collapsed" ) .find( ".ui-collapsible-heading-status" ).text( o.collapseCueText ); collapsibleHeading.find( ".ui-icon" ).removeClass( "ui-icon-plus" ).addClass( "ui-icon-minus" ); collapsibleContent.removeClass( "ui-collapsible-content-collapsed" ).attr( "aria-hidden", false ); if ( collapsibleContain.jqmData( "collapsible-last" ) ) { collapsibleHeading .find( "a:eq(0), .ui-btn-inner" ) .removeClass( "ui-corner-bottom" ); } } }) .trigger( o.collapsed ? "collapse" : "expand" ); // Close others in a set if ( collapsibleParent.length && !collapsibleParent.jqmData( "collapsiblebound" ) ) { collapsibleParent .jqmData( "collapsiblebound", true ) .bind( "expand", function( event ) { $( event.target ) .closest( ".ui-collapsible-contain" ) .siblings( ".ui-collapsible-contain" ) .trigger( "collapse" ); }); var set = collapsibleParent.children( ":jqmData(role='collapsible')" ); set.first() .find( "a:eq(0)" ) .addClass( "ui-corner-top" ) .find( ".ui-btn-inner" ) .addClass( "ui-corner-top" ); set.last().jqmData( "collapsible-last", true ); } collapsibleHeading .bind( "vclick", function( event ) { var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ? "expand" : "collapse"; collapsibleContain.trigger( type ); event.preventDefault(); }); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.collapsible.prototype.options.initSelector, e.target ).collapsible(); }); })( jQuery ); /* * jQuery Mobile Framework : "fieldcontain" plugin - simple class additions to make form row separators * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.fn.fieldcontain = function( options ) { return this.addClass( "ui-field-contain ui-body ui-br" ); }; //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='fieldcontain')", e.target ).fieldcontain(); }); })( jQuery );/* * jQuery Mobile Framework : plugin for creating CSS grids * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.fn.grid = function( options ) { return this.each(function() { var $this = $( this ), o = $.extend({ grid: null },options), $kids = $this.children(), gridCols = {solo:1, a:2, b:3, c:4, d:5}, grid = o.grid, iterator; if ( !grid ) { if ( $kids.length <= 5 ) { for ( var letter in gridCols ) { if ( gridCols[ letter ] === $kids.length ) { grid = letter; } } } else { grid = "a"; } } iterator = gridCols[grid]; $this.addClass( "ui-grid-" + grid ); $kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" ); if ( iterator > 1 ) { $kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" ); } if ( iterator > 2 ) { $kids.filter( ":nth-child(3n+3)" ).addClass( "ui-block-c" ); } if ( iterator > 3 ) { $kids.filter( ":nth-child(4n+4)" ).addClass( "ui-block-d" ); } if ( iterator > 4 ) { $kids.filter( ":nth-child(5n+5)" ).addClass( "ui-block-e" ); } }); }; })( jQuery );/* * jQuery Mobile Framework : "navbar" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.navbar", $.mobile.widget, { options: { iconpos: "top", grid: null, initSelector: ":jqmData(role='navbar')" }, _create: function(){ var $navbar = this.element, $navbtns = $navbar.find( "a" ), iconpos = $navbtns.filter( ":jqmData(icon)" ).length ? this.options.iconpos : undefined; $navbar.addClass( "ui-navbar" ) .attr( "role","navigation" ) .find( "ul" ) .grid({ grid: this.options.grid }); if ( !iconpos ) { $navbar.addClass( "ui-navbar-noicons" ); } $navbtns.buttonMarkup({ corners: false, shadow: false, iconpos: iconpos }); $navbar.delegate( "a", "vclick", function( event ) { $navbtns.not( ".ui-state-persist" ).removeClass( $.mobile.activeBtnClass ); $( this ).addClass( $.mobile.activeBtnClass ); }); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.navbar.prototype.options.initSelector, e.target ).navbar(); }); })( jQuery ); /* * jQuery Mobile Framework : "listview" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { //Keeps track of the number of lists per page UID //This allows support for multiple nested list in the same page //https://github.com/jquery/jquery-mobile/issues/1617 var listCountPerPage = {}; $.widget( "mobile.listview", $.mobile.widget, { options: { theme: "c", countTheme: "c", headerTheme: "b", dividerTheme: "b", splitIcon: "arrow-r", splitTheme: "b", inset: false, initSelector: ":jqmData(role='listview')" }, _create: function() { var t = this; // create listview markup t.element.addClass(function( i, orig ) { return orig + " ui-listview " + ( t.options.inset ? " ui-listview-inset ui-corner-all ui-shadow " : "" ); }); t.refresh(); }, _itemApply: function( $list, item ) { // TODO class has to be defined in markup item.find( ".ui-li-count" ) .addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme ) + " ui-btn-corner-all" ).end() .find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" ).end() .find( "p, dl" ).addClass( "ui-li-desc" ).end() .find( ">img:eq(0), .ui-link-inherit>img:eq(0)" ).addClass( "ui-li-thumb" ).each(function() { item.addClass( $(this).is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" ); }).end() .find( ".ui-li-aside" ).each(function() { var $this = $(this); $this.prependTo( $this.parent() ); //shift aside to front for css float }); }, _removeCorners: function( li, which ) { var top = "ui-corner-top ui-corner-tr ui-corner-tl", bot = "ui-corner-bottom ui-corner-br ui-corner-bl"; li = li.add( li.find( ".ui-btn-inner, .ui-li-link-alt, .ui-li-thumb" ) ); if ( which === "top" ) { li.removeClass( top ); } else if ( which === "bottom" ) { li.removeClass( bot ); } else { li.removeClass( top + " " + bot ); } }, refresh: function( create ) { this.parentPage = this.element.closest( ".ui-page" ); this._createSubPages(); var o = this.options, $list = this.element, self = this, dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme, listsplittheme = $list.jqmData( "splittheme" ), listspliticon = $list.jqmData( "spliticon" ), li = $list.children( "li" ), counter = $.support.cssPseudoElement || !$.nodeName( $list[ 0 ], "ol" ) ? 0 : 1, item, itemClass, itemTheme, a, last, splittheme, countParent, icon; if ( counter ) { $list.find( ".ui-li-dec" ).remove(); } for ( var pos = 0, numli = li.length; pos < numli; pos++ ) { item = li.eq( pos ); itemClass = "ui-li"; // If we're creating the element, we update it regardless if ( create || !item.hasClass( "ui-li" ) ) { itemTheme = item.jqmData("theme") || o.theme; a = item.children( "a" ); if ( a.length ) { icon = item.jqmData("icon"); item.buttonMarkup({ wrapperEls: "div", shadow: false, corners: false, iconpos: "right", icon: a.length > 1 || icon === false ? false : icon || "arrow-r", theme: itemTheme }); a.first().addClass( "ui-link-inherit" ); if ( a.length > 1 ) { itemClass += " ui-li-has-alt"; last = a.last(); splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme; last.appendTo(item) .attr( "title", last.text() ) .addClass( "ui-li-link-alt" ) .empty() .buttonMarkup({ shadow: false, corners: false, theme: itemTheme, icon: false, iconpos: false }) .find( ".ui-btn-inner" ) .append( $( "<span />" ).buttonMarkup({ shadow: true, corners: true, theme: splittheme, iconpos: "notext", icon: listspliticon || last.jqmData( "icon" ) || o.splitIcon }) ); } } else if ( item.jqmData( "role" ) === "list-divider" ) { itemClass += " ui-li-divider ui-btn ui-bar-" + dividertheme; item.attr( "role", "heading" ); //reset counter when a divider heading is encountered if ( counter ) { counter = 1; } } else { itemClass += " ui-li-static ui-body-" + itemTheme; } } if ( o.inset ) { if ( pos === 0 ) { itemClass += " ui-corner-top"; item.add( item.find( ".ui-btn-inner" ) ) .find( ".ui-li-link-alt" ) .addClass( "ui-corner-tr" ) .end() .find( ".ui-li-thumb" ) .addClass( "ui-corner-tl" ); if ( item.next().next().length ) { self._removeCorners( item.next() ); } } if ( pos === li.length - 1 ) { itemClass += " ui-corner-bottom"; item.add( item.find( ".ui-btn-inner" ) ) .find( ".ui-li-link-alt" ) .addClass( "ui-corner-br" ) .end() .find( ".ui-li-thumb" ) .addClass( "ui-corner-bl" ); if ( item.prev().prev().length ) { self._removeCorners( item.prev() ); } else if ( item.prev().length ) { self._removeCorners( item.prev(), "bottom" ); } } } if ( counter && itemClass.indexOf( "ui-li-divider" ) < 0 ) { countParent = item.is( ".ui-li-static:first" ) ? item : item.find( ".ui-link-inherit" ); countParent.addClass( "ui-li-jsnumbering" ) .prepend( "<span class='ui-li-dec'>" + (counter++) + ". </span>" ); } item.add( item.children( ".ui-btn-inner" ) ).addClass( itemClass ); if ( !create ) { self._itemApply( $list, item ); } } }, //create a string for ID/subpage url creation _idStringEscape: function( str ) { return str.replace(/[^a-zA-Z0-9]/g, '-'); }, _createSubPages: function() { var parentList = this.element, parentPage = parentList.closest( ".ui-page" ), parentUrl = parentPage.jqmData( "url" ), parentId = parentUrl || parentPage[ 0 ][ $.expando ], parentListId = parentList.attr( "id" ), o = this.options, dns = "data-" + $.mobile.ns, self = this, persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ), hasSubPages; if ( typeof listCountPerPage[ parentId ] === "undefined" ) { listCountPerPage[ parentId ] = -1; } parentListId = parentListId || ++listCountPerPage[ parentId ]; $( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) { var self = this, list = $( this ), listId = list.attr( "id" ) || parentListId + "-" + i, parent = list.parent(), nodeEls = $( list.prevAll().toArray().reverse() ), nodeEls = nodeEls.length ? nodeEls : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ), title = nodeEls.first().text(),//url limits to first 30 chars of text id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId, theme = list.jqmData( "theme" ) || o.theme, countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme, newPage, anchor; //define hasSubPages for use in later removal hasSubPages = true; newPage = list.detach() .wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" ) .parent() .before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" ) .after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>") : "" ) .parent() .appendTo( $.mobile.pageContainer ); newPage.page(); anchor = parent.find('a:first'); if ( !anchor.length ) { anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() ); } anchor.attr( "href", "#" + id ); }).listview(); //on pagehide, remove any nested pages along with the parent page, as long as they aren't active if( hasSubPages && parentPage.data("page").options.domCache === false ){ var newRemove = function( e, ui ){ var nextPage = ui.nextPage, npURL; if( ui.nextPage ){ npURL = nextPage.jqmData( "url" ); if( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ){ self.childPages().remove(); parentPage.remove(); } } }; // unbind the original page remove and replace with our specialized version parentPage .unbind( "pagehide.remove" ) .bind( "pagehide.remove", newRemove); } }, // TODO sort out a better way to track sub pages of the listview this is brittle childPages: function(){ var parentUrl = this.parentPage.jqmData( "url" ); return $( ":jqmData(url^='"+ parentUrl + "&" + $.mobile.subPageUrlKey +"')"); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.listview.prototype.options.initSelector, e.target ).listview(); }); })( jQuery ); /* * jQuery Mobile Framework : "listview" filter extension * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.mobile.listview.prototype.options.filter = false; $.mobile.listview.prototype.options.filterPlaceholder = "Filter items..."; $.mobile.listview.prototype.options.filterTheme = "c"; $( ":jqmData(role='listview')" ).live( "listviewcreate", function() { var list = $( this ), listview = list.data( "listview" ); if ( !listview.options.filter ) { return; } var wrapper = $( "<form>", { "class": "ui-listview-filter ui-bar-" + listview.options.filterTheme, "role": "search" }), search = $( "<input>", { placeholder: listview.options.filterPlaceholder }) .attr( "data-" + $.mobile.ns + "type", "search" ) .jqmData( "lastval", "" ) .bind( "keyup change", function() { var $this = $(this), val = this.value.toLowerCase(), listItems = null, lastval = $this.jqmData( "lastval" ) + "", childItems = false, itemtext = "", item; // Change val as lastval for next execution $this.jqmData( "lastval" , val ); change = val.replace( new RegExp( "^" + lastval ) , "" ); if ( val.length < lastval.length || change.length != ( val.length - lastval.length ) ) { // Removed chars or pasted something totaly different, check all items listItems = list.children(); } else { // Only chars added, not removed, only use visible subset listItems = list.children( ":not(.ui-screen-hidden)" ); } if ( val ) { // This handles hiding regular rows without the text we search for // and any list dividers without regular rows shown under it for ( var i = listItems.length - 1; i >= 0; i-- ) { item = $( listItems[ i ] ); itemtext = item.jqmData( "filtertext" ) || item.text(); if ( item.is( "li:jqmData(role=list-divider)" ) ) { item.toggleClass( "ui-filter-hidequeue" , !childItems ); // New bucket! childItems = false; } else if ( itemtext.toLowerCase().indexOf( val ) === -1 ) { //mark to be hidden item.toggleClass( "ui-filter-hidequeue" , true ); } else { // There"s a shown item in the bucket childItems = true; } } // Show items, not marked to be hidden listItems .filter( ":not(.ui-filter-hidequeue)" ) .toggleClass( "ui-screen-hidden", false ); // Hide items, marked to be hidden listItems .filter( ".ui-filter-hidequeue" ) .toggleClass( "ui-screen-hidden", true ) .toggleClass( "ui-filter-hidequeue", false ); } else { //filtervalue is empty => show all listItems.toggleClass( "ui-screen-hidden", false ); } }) .appendTo( wrapper ) .textinput(); if ( $( this ).jqmData( "inset" ) ) { wrapper.addClass( "ui-listview-filter-inset" ); } wrapper.bind( "submit", function() { return false; }) .insertBefore( list ); }); })( jQuery );/* * jQuery Mobile Framework : "fieldcontain" plugin - simple class additions to make form row separators * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" ); }); })( jQuery );/* * jQuery Mobile Framework : "checkboxradio" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.checkboxradio", $.mobile.widget, { options: { theme: null, initSelector: "input[type='checkbox'],input[type='radio']" }, _create: function() { var self = this, input = this.element, // NOTE: Windows Phone could not find the label through a selector // filter works though. label = input.closest( "form,fieldset,:jqmData(role='page')" ).find( "label" ).filter( "[for='" + input[ 0 ].id + "']"), inputtype = input.attr( "type" ), checkedState = inputtype + "-on", uncheckedState = inputtype + "-off", icon = input.parents( ":jqmData(type='horizontal')" ).length ? undefined : uncheckedState, activeBtn = icon ? "" : " " + $.mobile.activeBtnClass, checkedClass = "ui-" + checkedState + activeBtn, uncheckedClass = "ui-" + uncheckedState, checkedicon = "ui-icon-" + checkedState, uncheckedicon = "ui-icon-" + uncheckedState; if ( inputtype !== "checkbox" && inputtype !== "radio" ) { return; } // Expose for other methods $.extend( this, { label: label, inputtype: inputtype, checkedClass: checkedClass, uncheckedClass: uncheckedClass, checkedicon: checkedicon, uncheckedicon: uncheckedicon }); // If there's no selected theme... if( !this.options.theme ) { this.options.theme = this.element.jqmData( "theme" ); } label.buttonMarkup({ theme: this.options.theme, icon: icon, shadow: false }); // Wrap the input + label in a div input.add( label ) .wrapAll( "<div class='ui-" + inputtype + "'></div>" ); label.bind({ vmouseover: function() { if ( $( this ).parent().is( ".ui-disabled" ) ) { return false; } }, vclick: function( event ) { if ( input.is( ":disabled" ) ) { event.preventDefault(); return; } self._cacheVals(); input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) ); // Input set for common radio buttons will contain all the radio // buttons, but will not for checkboxes. clearing the checked status // of other radios ensures the active button state is applied properly self._getInputSet().not( input ).prop( "checked", false ); self._updateAll(); return false; } }); input .bind({ vmousedown: function() { this._cacheVals(); }, vclick: function() { var $this = $(this); // Adds checked attribute to checked input when keyboard is used if ( $this.is( ":checked" ) ) { $this.prop( "checked", true); self._getInputSet().not($this).prop( "checked", false ); } else { $this.prop( "checked", false ); } self._updateAll(); }, focus: function() { label.addClass( "ui-focus" ); }, blur: function() { label.removeClass( "ui-focus" ); } }); this.refresh(); }, _cacheVals: function() { this._getInputSet().each(function() { var $this = $(this); $this.jqmData( "cacheVal", $this.is( ":checked" ) ); }); }, //returns either a set of radios with the same name attribute, or a single checkbox _getInputSet: function(){ if(this.inputtype == "checkbox") { return this.element; } return this.element.closest( "form,fieldset,:jqmData(role='page')" ) .find( "input[name='"+ this.element.attr( "name" ) +"'][type='"+ this.inputtype +"']" ); }, _updateAll: function() { var self = this; this._getInputSet().each(function() { var $this = $(this); if ( $this.is( ":checked" ) || self.inputtype === "checkbox" ) { $this.trigger( "change" ); } }) .checkboxradio( "refresh" ); }, refresh: function() { var input = this.element, label = this.label, icon = label.find( ".ui-icon" ); // input[0].checked expando doesn't always report the proper value // for checked='checked' if ( $( input[ 0 ] ).prop( "checked" ) ) { label.addClass( this.checkedClass ).removeClass( this.uncheckedClass ); icon.addClass( this.checkedicon ).removeClass( this.uncheckedicon ); } else { label.removeClass( this.checkedClass ).addClass( this.uncheckedClass ); icon.removeClass( this.checkedicon ).addClass( this.uncheckedicon ); } if ( input.is( ":disabled" ) ) { this.disable(); } else { this.enable(); } }, disable: function() { this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" ); }, enable: function() { this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.checkboxradio.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .checkboxradio(); }); })( jQuery ); /* * jQuery Mobile Framework : "button" plugin - links that proxy to native input/buttons * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.button", $.mobile.widget, { options: { theme: null, icon: null, iconpos: null, inline: null, corners: true, shadow: true, iconshadow: true, initSelector: "button, [type='button'], [type='submit'], [type='reset'], [type='image']" }, _create: function() { var $el = this.element, o = this.options, type; // Add ARIA role this.button = $( "<div></div>" ) .text( $el.text() || $el.val() ) .buttonMarkup({ theme: o.theme, icon: o.icon, iconpos: o.iconpos, inline: o.inline, corners: o.corners, shadow: o.shadow, iconshadow: o.iconshadow }) .insertBefore( $el ) .append( $el.addClass( "ui-btn-hidden" ) ); // Add hidden input during submit type = $el.attr( "type" ); if ( type !== "button" && type !== "reset" ) { $el.bind( "vclick", function() { var $buttonPlaceholder = $( "<input>", { type: "hidden", name: $el.attr( "name" ), value: $el.attr( "value" ) }) .insertBefore( $el ); // Bind to doc to remove after submit handling $( document ).submit(function(){ $buttonPlaceholder.remove(); }); }); } this.refresh(); }, enable: function() { this.element.attr( "disabled", false ); this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); }, disable: function() { this.element.attr( "disabled", true ); this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); }, refresh: function() { if ( this.element.attr( "disabled" ) ) { this.disable(); } else { this.enable(); } } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.button.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .button(); }); })( jQuery );/* * jQuery Mobile Framework : "slider" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ ( function( $, undefined ) { $.widget( "mobile.slider", $.mobile.widget, { options: { theme: null, trackTheme: null, disabled: false, initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')" }, _create: function() { // TODO: Each of these should have comments explain what they're for var self = this, control = this.element, parentTheme = control.parents( "[class*='ui-bar-'],[class*='ui-body-']" ).eq( 0 ), parentTheme = parentTheme.length ? parentTheme.attr( "class" ).match( /ui-(bar|body)-([a-z])/ )[ 2 ] : "c", theme = this.options.theme ? this.options.theme : parentTheme, trackTheme = this.options.trackTheme ? this.options.trackTheme : parentTheme, cType = control[ 0 ].nodeName.toLowerCase(), selectClass = ( cType == "select" ) ? "ui-slider-switch" : "", controlID = control.attr( "id" ), labelID = controlID + "-label", label = $( "[for='"+ controlID +"']" ).attr( "id", labelID ), val = function() { return cType == "input" ? parseFloat( control.val() ) : control[0].selectedIndex; }, min = cType == "input" ? parseFloat( control.attr( "min" ) ) : 0, max = cType == "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1, step = window.parseFloat( control.attr( "step" ) || 1 ), slider = $( "<div class='ui-slider " + selectClass + " ui-btn-down-" + trackTheme + " ui-btn-corner-all' role='application'></div>" ), handle = $( "<a href='#' class='ui-slider-handle'></a>" ) .appendTo( slider ) .buttonMarkup({ corners: true, theme: theme, shadow: true }) .attr({ "role": "slider", "aria-valuemin": min, "aria-valuemax": max, "aria-valuenow": val(), "aria-valuetext": val(), "title": val(), "aria-labelledby": labelID }), options; $.extend( this, { slider: slider, handle: handle, dragging: false, beforeStart: null }); if ( cType == "select" ) { slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" ); options = control.find( "option" ); control.find( "option" ).each(function( i ) { var side = !i ? "b":"a", corners = !i ? "right" :"left", theme = !i ? " ui-btn-down-" + trackTheme :" ui-btn-active"; $( "<div class='ui-slider-labelbg ui-slider-labelbg-" + side + theme + " ui-btn-corner-" + corners + "'></div>" ) .prependTo( slider ); $( "<span class='ui-slider-label ui-slider-label-" + side + theme + " ui-btn-corner-" + corners + "' role='img'>" + $( this ).text() + "</span>" ) .prependTo( handle ); }); } label.addClass( "ui-slider" ); // monitor the input for updated values control.addClass( cType === "input" ? "ui-slider-input" : "ui-slider-switch" ) .change( function() { self.refresh( val(), true ); }) .keyup( function() { // necessary? self.refresh( val(), true, true ); }) .blur( function() { self.refresh( val(), true ); }); // prevent screen drag when slider activated $( document ).bind( "vmousemove", function( event ) { if ( self.dragging ) { self.refresh( event ); return false; } }); slider.bind( "vmousedown", function( event ) { self.dragging = true; if ( cType === "select" ) { self.beforeStart = control[0].selectedIndex; } self.refresh( event ); return false; }); slider.add( document ) .bind( "vmouseup", function() { if ( self.dragging ) { self.dragging = false; if ( cType === "select" ) { if ( self.beforeStart === control[ 0 ].selectedIndex ) { //tap occurred, but value didn't change. flip it! self.refresh( !self.beforeStart ? 1 : 0 ); } var curval = val(); var snapped = Math.round( curval / ( max - min ) * 100 ); handle .addClass( "ui-slider-handle-snapping" ) .css( "left", snapped + "%" ) .animationComplete( function() { handle.removeClass( "ui-slider-handle-snapping" ); }); } return false; } }); slider.insertAfter( control ); // NOTE force focus on handle this.handle .bind( "vmousedown", function() { $( this ).focus(); }) .bind( "vclick", false ); this.handle .bind( "keydown", function( event ) { var index = val(); if ( self.options.disabled ) { return; } // In all cases prevent the default and mark the handle as active switch ( event.keyCode ) { case $.mobile.keyCode.HOME: case $.mobile.keyCode.END: case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: event.preventDefault(); if ( !self._keySliding ) { self._keySliding = true; $( this ).addClass( "ui-state-active" ); } break; } // move the slider according to the keypress switch ( event.keyCode ) { case $.mobile.keyCode.HOME: self.refresh( min ); break; case $.mobile.keyCode.END: self.refresh( max ); break; case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: self.refresh( index + step ); break; case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: self.refresh( index - step ); break; } }) // remove active mark .keyup( function( event ) { if ( self._keySliding ) { self._keySliding = false; $( this ).removeClass( "ui-state-active" ); } }); this.refresh(undefined, undefined, true); }, refresh: function( val, isfromControl, preventInputUpdate ) { if ( this.options.disabled ) { return; } var control = this.element, percent, cType = control[0].nodeName.toLowerCase(), min = cType === "input" ? parseFloat( control.attr( "min" ) ) : 0, max = cType === "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length - 1; if ( typeof val === "object" ) { var data = val, // a slight tolerance helped get to the ends of the slider tol = 8; if ( !this.dragging || data.pageX < this.slider.offset().left - tol || data.pageX > this.slider.offset().left + this.slider.width() + tol ) { return; } percent = Math.round( ( ( data.pageX - this.slider.offset().left ) / this.slider.width() ) * 100 ); } else { if ( val == null ) { val = cType === "input" ? parseFloat( control.val() ) : control[0].selectedIndex; } percent = ( parseFloat( val ) - min ) / ( max - min ) * 100; } if ( isNaN( percent ) ) { return; } if ( percent < 0 ) { percent = 0; } if ( percent > 100 ) { percent = 100; } var newval = Math.round( ( percent / 100 ) * ( max - min ) ) + min; if ( newval < min ) { newval = min; } if ( newval > max ) { newval = max; } // Flip the stack of the bg colors if ( percent > 60 && cType === "select" ) { // TODO: Dead path? } this.handle.css( "left", percent + "%" ); this.handle.attr( { "aria-valuenow": cType === "input" ? newval : control.find( "option" ).eq( newval ).attr( "value" ), "aria-valuetext": cType === "input" ? newval : control.find( "option" ).eq( newval ).text(), title: newval }); // add/remove classes for flip toggle switch if ( cType === "select" ) { if ( newval === 0 ) { this.slider.addClass( "ui-slider-switch-a" ) .removeClass( "ui-slider-switch-b" ); } else { this.slider.addClass( "ui-slider-switch-b" ) .removeClass( "ui-slider-switch-a" ); } } if ( !preventInputUpdate ) { // update control"s value if ( cType === "input" ) { control.val( newval ); } else { control[ 0 ].selectedIndex = newval; } if ( !isfromControl ) { control.trigger( "change" ); } } }, enable: function() { this.element.attr( "disabled", false ); this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); }, disable: function() { this.element.attr( "disabled", true ); this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.slider.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .slider(); }); })( jQuery );/* * jQuery Mobile Framework : "textinput" plugin for text inputs, textareas * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.textinput", $.mobile.widget, { options: { theme: null, initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea" }, _create: function() { var input = this.element, o = this.options, theme = o.theme, themedParent, themeclass, themeLetter, focusedEl, clearbtn; if ( !theme ) { themedParent = this.element.closest( "[class*='ui-bar-'],[class*='ui-body-']" ); themeLetter = themedParent.length && /ui-(bar|body)-([a-z])/.exec( themedParent.attr( "class" ) ); theme = themeLetter && themeLetter[2] || "c"; } themeclass = " ui-body-" + theme; $( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" ); input.addClass("ui-input-text ui-body-"+ o.theme ); focusedEl = input; // XXX: Temporary workaround for issue 785. Turn off autocorrect and // autocomplete since the popup they use can't be dismissed by // the user. Note that we test for the presence of the feature // by looking for the autocorrect property on the input element. if ( typeof input[0].autocorrect !== "undefined" ) { // Set the attribute instead of the property just in case there // is code that attempts to make modifications via HTML. input[0].setAttribute( "autocorrect", "off" ); input[0].setAttribute( "autocomplete", "off" ); } //"search" input widget if ( input.is( "[type='search'],:jqmData(type='search')" ) ) { focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + "'></div>" ).parent(); clearbtn = $( "<a href='#' class='ui-input-clear' title='clear text'>clear text</a>" ) .tap(function( event ) { input.val( "" ).focus(); input.trigger( "change" ); clearbtn.addClass( "ui-input-clear-hidden" ); event.preventDefault(); }) .appendTo( focusedEl ) .buttonMarkup({ icon: "delete", iconpos: "notext", corners: true, shadow: true }); function toggleClear() { if ( !input.val() ) { clearbtn.addClass( "ui-input-clear-hidden" ); } else { clearbtn.removeClass( "ui-input-clear-hidden" ); } } toggleClear(); input.keyup( toggleClear ) .focus( toggleClear ); } else { input.addClass( "ui-corner-all ui-shadow-inset" + themeclass ); } input.focus(function() { focusedEl.addClass( "ui-focus" ); }) .blur(function(){ focusedEl.removeClass( "ui-focus" ); }); // Autogrow if ( input.is( "textarea" ) ) { var extraLineHeight = 15, keyupTimeoutBuffer = 100, keyup = function() { var scrollHeight = input[ 0 ].scrollHeight, clientHeight = input[ 0 ].clientHeight; if ( clientHeight < scrollHeight ) { input.css({ height: (scrollHeight + extraLineHeight) }); } }, keyupTimeout; input.keyup(function() { clearTimeout( keyupTimeout ); keyupTimeout = setTimeout( keyup, keyupTimeoutBuffer ); }); } }, disable: function(){ ( this.element.attr( "disabled", true ).is( "[type='search'],:jqmData(type='search')" ) ? this.element.parent() : this.element ).addClass( "ui-disabled" ); }, enable: function(){ ( this.element.attr( "disabled", false).is( "[type='search'],:jqmData(type='search')" ) ? this.element.parent() : this.element ).removeClass( "ui-disabled" ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.textinput.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .textinput(); }); })( jQuery ); /* * jQuery Mobile Framework : "selectmenu" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.selectmenu", $.mobile.widget, { options: { theme: null, disabled: false, icon: "arrow-d", iconpos: "right", inline: null, corners: true, shadow: true, iconshadow: true, menuPageTheme: "b", overlayTheme: "a", hidePlaceholderMenuItems: true, closeText: "Close", nativeMenu: true, initSelector: "select:not(:jqmData(role='slider'))" }, _create: function() { var self = this, o = this.options, select = this.element .wrap( "<div class='ui-select'>" ), selectID = select.attr( "id" ), label = $( "label[for='"+ selectID +"']" ).addClass( "ui-select" ), // IE throws an exception at options.item() function when // there is no selected item // select first in this case selectedIndex = select[ 0 ].selectedIndex == -1 ? 0 : select[ 0 ].selectedIndex, button = ( self.options.nativeMenu ? $( "<div/>" ) : $( "<a>", { "href": "#", "role": "button", "id": buttonId, "aria-haspopup": "true", "aria-owns": menuId }) ) .text( $( select[ 0 ].options.item( selectedIndex ) ).text() ) .insertBefore( select ) .buttonMarkup({ theme: o.theme, icon: o.icon, iconpos: o.iconpos, inline: o.inline, corners: o.corners, shadow: o.shadow, iconshadow: o.iconshadow }), // Multi select or not isMultiple = self.isMultiple = select[ 0 ].multiple; // Opera does not properly support opacity on select elements // In Mini, it hides the element, but not its text // On the desktop,it seems to do the opposite // for these reasons, using the nativeMenu option results in a full native select in Opera if ( o.nativeMenu && window.opera && window.opera.version ) { select.addClass( "ui-select-nativeonly" ); } //vars for non-native menus if ( !o.nativeMenu ) { var options = select.find("option"), buttonId = selectID + "-button", menuId = selectID + "-menu", thisPage = select.closest( ".ui-page" ), //button theme theme = /ui-btn-up-([a-z])/.exec( button.attr( "class" ) )[1], menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' data-" +$.mobile.ns + "theme='"+ o.menuPageTheme +"'>" + "<div data-" + $.mobile.ns + "role='header'>" + "<div class='ui-title'>" + label.text() + "</div>"+ "</div>"+ "<div data-" + $.mobile.ns + "role='content'></div>"+ "</div>" ) .appendTo( $.mobile.pageContainer ) .page(), menuPageContent = menuPage.find( ".ui-content" ), menuPageClose = menuPage.find( ".ui-header a" ), screen = $( "<div>", {"class": "ui-selectmenu-screen ui-screen-hidden"}) .appendTo( thisPage ), listbox = $("<div>", { "class": "ui-selectmenu ui-selectmenu-hidden ui-overlay-shadow ui-corner-all ui-body-" + o.overlayTheme + " " + $.mobile.defaultDialogTransition }) .insertAfter(screen), list = $( "<ul>", { "class": "ui-selectmenu-list", "id": menuId, "role": "listbox", "aria-labelledby": buttonId }) .attr( "data-" + $.mobile.ns + "theme", theme ) .appendTo( listbox ), header = $( "<div>", { "class": "ui-header ui-bar-" + theme }) .prependTo( listbox ), headerTitle = $( "<h1>", { "class": "ui-title" }) .appendTo( header ), headerClose = $( "<a>", { "text": o.closeText, "href": "#", "class": "ui-btn-left" }) .attr( "data-" + $.mobile.ns + "iconpos", "notext" ) .attr( "data-" + $.mobile.ns + "icon", "delete" ) .appendTo( header ) .buttonMarkup(), menuType; } // End non native vars // Add counter for multi selects if ( isMultiple ) { self.buttonCount = $( "<span>" ) .addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" ) .hide() .appendTo( button ); } // Disable if specified if ( o.disabled ) { this.disable(); } // Events on native select select.change(function() { self.refresh(); }); // Expose to other methods $.extend( self, { select: select, optionElems: options, selectID: selectID, label: label, buttonId: buttonId, menuId: menuId, thisPage: thisPage, button: button, menuPage: menuPage, menuPageContent: menuPageContent, screen: screen, listbox: listbox, list: list, menuType: menuType, header: header, headerClose: headerClose, headerTitle: headerTitle, placeholder: "" }); // Support for using the native select menu with a custom button if ( o.nativeMenu ) { select.appendTo( button ) .bind( "vmousedown", function() { // Add active class to button button.addClass( $.mobile.activeBtnClass ); }) .bind( "focus vmouseover", function() { button.trigger( "vmouseover" ); }) .bind( "vmousemove", function() { // Remove active class on scroll/touchmove button.removeClass( $.mobile.activeBtnClass ); }) .bind( "change blur vmouseout", function() { button.trigger( "vmouseout" ) .removeClass( $.mobile.activeBtnClass ); }); } else { // Create list from select, update state self.refresh(); select.attr( "tabindex", "-1" ) .focus(function() { $(this).blur(); button.focus(); }); // Button events button.bind( "vclick keydown" , function( event ) { if ( event.type == "vclick" || event.keyCode && ( event.keyCode === $.mobile.keyCode.ENTER || event.keyCode === $.mobile.keyCode.SPACE ) ) { self.open(); event.preventDefault(); } }); // Events for list items list.attr( "role", "listbox" ) .delegate( ".ui-li>a", "focusin", function() { $( this ).attr( "tabindex", "0" ); }) .delegate( ".ui-li>a", "focusout", function() { $( this ).attr( "tabindex", "-1" ); }) .delegate( "li:not(.ui-disabled, .ui-li-divider)", "vclick", function( event ) { var $this = $( this ), // index of option tag to be selected oldIndex = select[ 0 ].selectedIndex, newIndex = $this.jqmData( "option-index" ), option = self.optionElems[ newIndex ]; // toggle selected status on the tag for multi selects option.selected = isMultiple ? !option.selected : true; // toggle checkbox class for multiple selects if ( isMultiple ) { $this.find( ".ui-icon" ) .toggleClass( "ui-icon-checkbox-on", option.selected ) .toggleClass( "ui-icon-checkbox-off", !option.selected ); } // trigger change if value changed if ( isMultiple || oldIndex !== newIndex ) { select.trigger( "change" ); } //hide custom select for single selects only if ( !isMultiple ) { self.close(); } event.preventDefault(); }) //keyboard events for menu items .keydown(function( event ) { var target = $( event.target ), li = target.closest( "li" ), prev, next; // switch logic based on which key was pressed switch ( event.keyCode ) { // up or left arrow keys case 38: prev = li.prev(); // if there's a previous option, focus it if ( prev.length ) { target .blur() .attr( "tabindex", "-1" ); prev.find( "a" ).first().focus(); } return false; break; // down or right arrow keys case 40: next = li.next(); // if there's a next option, focus it if ( next.length ) { target .blur() .attr( "tabindex", "-1" ); next.find( "a" ).first().focus(); } return false; break; // If enter or space is pressed, trigger click case 13: case 32: target.trigger( "vclick" ); return false; break; } }); // button refocus ensures proper height calculation // by removing the inline style and ensuring page inclusion self.menuPage.bind( "pagehide", function(){ self.list.appendTo( self.listbox ); self._focusButton(); }); // Events on "screen" overlay screen.bind( "vclick", function( event ) { self.close(); }); // Close button on small overlays self.headerClose.click(function() { if ( self.menuType == "overlay" ) { self.close(); return false; } }); } }, _buildList: function() { var self = this, o = this.options, placeholder = this.placeholder, optgroups = [], lis = [], dataIcon = self.isMultiple ? "checkbox-off" : "false"; self.list.empty().filter( ".ui-listview" ).listview( "destroy" ); // Populate menu with options from select element self.select.find( "option" ).each(function( i ) { var $this = $( this ), $parent = $this.parent(), text = $this.text(), anchor = "<a href='#'>"+ text +"</a>", classes = [], extraAttrs = []; // Are we inside an optgroup? if ( $parent.is( "optgroup" ) ) { var optLabel = $parent.attr( "label" ); // has this optgroup already been built yet? if ( $.inArray( optLabel, optgroups ) === -1 ) { lis.push( "<li data-" + $.mobile.ns + "role='list-divider'>"+ optLabel +"</li>" ); optgroups.push( optLabel ); } } // Find placeholder text // TODO: Are you sure you want to use getAttribute? ^RW if ( !this.getAttribute( "value" ) || text.length == 0 || $this.jqmData( "placeholder" ) ) { if ( o.hidePlaceholderMenuItems ) { classes.push( "ui-selectmenu-placeholder" ); } placeholder = self.placeholder = text; } // support disabled option tags if ( this.disabled ) { classes.push( "ui-disabled" ); extraAttrs.push( "aria-disabled='true'" ); } lis.push( "<li data-" + $.mobile.ns + "option-index='" + i + "' data-" + $.mobile.ns + "icon='"+ dataIcon +"' class='"+ classes.join(" ") + "' " + extraAttrs.join(" ") +">"+ anchor +"</li>" ) }); self.list.html( lis.join(" ") ); self.list.find( "li" ) .attr({ "role": "option", "tabindex": "-1" }) .first().attr( "tabindex", "0" ); // Hide header close link for single selects if ( !this.isMultiple ) { this.headerClose.hide(); } // Hide header if it's not a multiselect and there's no placeholder if ( !this.isMultiple && !placeholder.length ) { this.header.hide(); } else { this.headerTitle.text( this.placeholder ); } // Now populated, create listview self.list.listview(); }, refresh: function( forceRebuild ) { var self = this, select = this.element, isMultiple = this.isMultiple, options = this.optionElems = select.find( "option" ), selected = options.filter( ":selected" ), // return an array of all selected index's indicies = selected.map(function() { return options.index( this ); }).get(); if ( !self.options.nativeMenu && ( forceRebuild || select[0].options.length != self.list.find( "li" ).length ) ) { self._buildList(); } self.button.find( ".ui-btn-text" ) .text(function() { if ( !isMultiple ) { return selected.text(); } return selected.length ? selected.map(function() { return $( this ).text(); }).get().join( ", " ) : self.placeholder; }); // multiple count inside button if ( isMultiple ) { self.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length ); } if ( !self.options.nativeMenu ) { self.list.find( "li:not(.ui-li-divider)" ) .removeClass( $.mobile.activeBtnClass ) .attr( "aria-selected", false ) .each(function( i ) { if ( $.inArray( i, indicies ) > -1 ) { var item = $( this ).addClass( $.mobile.activeBtnClass ); // Aria selected attr item.find( "a" ).attr( "aria-selected", true ); // Multiple selects: add the "on" checkbox state to the icon if ( isMultiple ) { item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" ); } } }); } }, open: function() { if ( this.options.disabled || this.options.nativeMenu ) { return; } var self = this, menuHeight = self.list.parent().outerHeight(), menuWidth = self.list.parent().outerWidth(), scrollTop = $( window ).scrollTop(), btnOffset = self.button.offset().top, screenHeight = window.innerHeight, screenWidth = window.innerWidth; //add active class to button self.button.addClass( $.mobile.activeBtnClass ); //remove after delay setTimeout(function() { self.button.removeClass( $.mobile.activeBtnClass ); }, 300); function focusMenuItem() { self.list.find( ".ui-btn-active" ).focus(); } if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) { // prevent the parent page from being removed from the DOM, // otherwise the results of selecting a list item in the dialog // fall into a black hole self.thisPage.unbind( "pagehide.remove" ); //for webos (set lastscroll using button offset) if ( scrollTop == 0 && btnOffset > screenHeight ) { self.thisPage.one( "pagehide", function() { $( this ).jqmData( "lastScroll", btnOffset ); }); } self.menuPage.one( "pageshow", function() { // silentScroll() is called whenever a page is shown to restore // any previous scroll position the page may have had. We need to // wait for the "silentscroll" event before setting focus to avoid // the browser"s "feature" which offsets rendering to make sure // whatever has focus is in view. $( window ).one( "silentscroll", function() { focusMenuItem(); }); self.isOpen = true; }); self.menuType = "page"; self.menuPageContent.append( self.list ); $.mobile.changePage( self.menuPage, { transition: $.mobile.defaultDialogTransition }); } else { self.menuType = "overlay"; self.screen.height( $(document).height() ) .removeClass( "ui-screen-hidden" ); // Try and center the overlay over the button var roomtop = btnOffset - scrollTop, roombot = scrollTop + screenHeight - btnOffset, halfheight = menuHeight / 2, maxwidth = parseFloat( self.list.parent().css( "max-width" ) ), newtop, newleft; if ( roomtop > menuHeight / 2 && roombot > menuHeight / 2 ) { newtop = btnOffset + ( self.button.outerHeight() / 2 ) - halfheight; } else { // 30px tolerance off the edges newtop = roomtop > roombot ? scrollTop + screenHeight - menuHeight - 30 : scrollTop + 30; } // If the menuwidth is smaller than the screen center is if ( menuWidth < maxwidth ) { newleft = ( screenWidth - menuWidth ) / 2; } else { //otherwise insure a >= 30px offset from the left newleft = self.button.offset().left + self.button.outerWidth() / 2 - menuWidth / 2; // 30px tolerance off the edges if ( newleft < 30 ) { newleft = 30; } else if ( ( newleft + menuWidth ) > screenWidth ) { newleft = screenWidth - menuWidth - 30; } } self.listbox.append( self.list ) .removeClass( "ui-selectmenu-hidden" ) .css({ top: newtop, left: newleft }) .addClass( "in" ); focusMenuItem(); // duplicate with value set in page show for dialog sized selects self.isOpen = true; } }, _focusButton : function(){ var self = this; setTimeout(function() { self.button.focus(); }, 40); }, close: function() { if ( this.options.disabled || !this.isOpen || this.options.nativeMenu ) { return; } var self = this; if ( self.menuType == "page" ) { // rebind the page remove that was unbound in the open function // to allow for the parent page removal from actions other than the use // of a dialog sized custom select self.thisPage.bind( "pagehide.remove", function(){ $(this).remove(); }); // doesn't solve the possible issue with calling change page // where the objects don't define data urls which prevents dialog key // stripping - changePage has incoming refactor window.history.back(); } else{ self.screen.addClass( "ui-screen-hidden" ); self.listbox.addClass( "ui-selectmenu-hidden" ).removeAttr( "style" ).removeClass( "in" ); self.list.appendTo( self.listbox ); self._focusButton(); } // allow the dialog to be closed again this.isOpen = false; }, disable: function() { this.element.attr( "disabled", true ); this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); }, enable: function() { this.element.attr( "disabled", false ); this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.selectmenu.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .selectmenu(); }); })( jQuery ); /* * jQuery Mobile Framework : plugin for making button-like links * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ ( function( $, undefined ) { $.fn.buttonMarkup = function( options ) { return this.each( function() { var el = $( this ), o = $.extend( {}, $.fn.buttonMarkup.defaults, el.jqmData(), options ), // Classes Defined innerClass = "ui-btn-inner", buttonClass, iconClass, themedParent, wrap; if ( attachEvents ) { attachEvents(); } // if not, try to find closest theme container if ( !o.theme ) { themedParent = el.closest( "[class*='ui-bar-'],[class*='ui-body-']" ); o.theme = themedParent.length ? /ui-(bar|body)-([a-z])/.exec( themedParent.attr( "class" ) )[2] : "c"; } buttonClass = "ui-btn ui-btn-up-" + o.theme; if ( o.inline ) { buttonClass += " ui-btn-inline"; } if ( o.icon ) { o.icon = "ui-icon-" + o.icon; o.iconpos = o.iconpos || "left"; iconClass = "ui-icon " + o.icon; if ( o.iconshadow ) { iconClass += " ui-icon-shadow"; } } if ( o.iconpos ) { buttonClass += " ui-btn-icon-" + o.iconpos; if ( o.iconpos == "notext" && !el.attr( "title" ) ) { el.attr( "title", el.text() ); } } if ( o.corners ) { buttonClass += " ui-btn-corner-all"; innerClass += " ui-btn-corner-all"; } if ( o.shadow ) { buttonClass += " ui-shadow"; } el.attr( "data-" + $.mobile.ns + "theme", o.theme ) .addClass( buttonClass ); wrap = ( "<D class='" + innerClass + "'><D class='ui-btn-text'></D>" + ( o.icon ? "<span class='" + iconClass + "'></span>" : "" ) + "</D>" ).replace( /D/g, o.wrapperEls ); el.wrapInner( wrap ); }); }; $.fn.buttonMarkup.defaults = { corners: true, shadow: true, iconshadow: true, wrapperEls: "span" }; function closestEnabledButton( element ) { while ( element ) { var $ele = $( element ); if ( $ele.hasClass( "ui-btn" ) && !$ele.hasClass( "ui-disabled" ) ) { break; } element = element.parentNode; } return element; } var attachEvents = function() { $( document ).bind( { "vmousedown": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-down-" + theme ); } }, "vmousecancel vmouseup": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme ); } }, "vmouseover focus": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-hover-" + theme ); } }, "vmouseout blur": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-hover-" + theme ).addClass( "ui-btn-up-" + theme ); } } }); attachEvents = null; }; //links in bars, or those with data-role become buttons //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target ) .not( ".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" ) .buttonMarkup(); }); })( jQuery ); /* * jQuery Mobile Framework: "controlgroup" plugin - corner-rounding for groups of buttons, checks, radios, etc * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.fn.controlgroup = function( options ) { return this.each(function() { var $el = $( this ), o = $.extend({ direction: $el.jqmData( "type" ) || "vertical", shadow: false, excludeInvisible: true }, options ), groupheading = $el.find( ">legend" ), flCorners = o.direction == "horizontal" ? [ "ui-corner-left", "ui-corner-right" ] : [ "ui-corner-top", "ui-corner-bottom" ], type = $el.find( "input:eq(0)" ).attr( "type" ); // Replace legend with more stylable replacement div if ( groupheading.length ) { $el.wrapInner( "<div class='ui-controlgroup-controls'></div>" ); $( "<div role='heading' class='ui-controlgroup-label'>" + groupheading.html() + "</div>" ).insertBefore( $el.children(0) ); groupheading.remove(); } $el.addClass( "ui-corner-all ui-controlgroup ui-controlgroup-" + o.direction ); // TODO: This should be moved out to the closure // otherwise it is redefined each time controlgroup() is called function flipClasses( els ) { els.removeClass( "ui-btn-corner-all ui-shadow" ) .eq( 0 ).addClass( flCorners[ 0 ] ) .end() .filter( ":last" ).addClass( flCorners[ 1 ] ).addClass( "ui-controlgroup-last" ); } flipClasses( $el.find( ".ui-btn" + ( o.excludeInvisible ? ":visible" : "" ) ) ); flipClasses( $el.find( ".ui-btn-inner" ) ); if ( o.shadow ) { $el.addClass( "ui-shadow" ); } }); }; //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='controlgroup')", e.target ).controlgroup({ excludeInvisible: false }); }); })(jQuery);/* * jQuery Mobile Framework : "fieldcontain" plugin - simple class additions to make form row separators * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $( document ).bind( "pagecreate create", function( e ){ //links within content areas $( e.target ) .find( "a" ) .not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" ) .addClass( "ui-link" ); }); })( jQuery );/* * jQuery Mobile Framework : "fixHeaderFooter" plugin - on-demand positioning for headers,footers * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { var slideDownClass = "ui-header-fixed ui-fixed-inline fade", slideUpClass = "ui-footer-fixed ui-fixed-inline fade", slideDownSelector = ".ui-header:jqmData(position='fixed')", slideUpSelector = ".ui-footer:jqmData(position='fixed')"; $.fn.fixHeaderFooter = function( options ) { if ( !$.support.scrollTop ) { return this; } return this.each(function() { var $this = $( this ); if ( $this.jqmData( "fullscreen" ) ) { $this.addClass( "ui-page-fullscreen" ); } // Should be slidedown $this.find( slideDownSelector ).addClass( slideDownClass ); // Should be slideup $this.find( slideUpSelector ).addClass( slideUpClass ); }); }; // single controller for all showing,hiding,toggling $.mobile.fixedToolbars = (function() { if ( !$.support.scrollTop ) { return; } var stickyFooter, delayTimer, currentstate = "inline", autoHideMode = false, showDelay = 100, ignoreTargets = "a,input,textarea,select,button,label,.ui-header-fixed,.ui-footer-fixed", toolbarSelector = ".ui-header-fixed:first, .ui-footer-fixed:not(.ui-footer-duplicate):last", // for storing quick references to duplicate footers supportTouch = $.support.touch, touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", stateBefore = null, scrollTriggered = false, touchToggleEnabled = true; function showEventCallback( event ) { // An event that affects the dimensions of the visual viewport has // been triggered. If the header and/or footer for the current page are in overlay // mode, we want to hide them, and then fire off a timer to show them at a later // point. Events like a resize can be triggered continuously during a scroll, on // some platforms, so the timer is used to delay the actual positioning until the // flood of events have subsided. // // If we are in autoHideMode, we don't do anything because we know the scroll // callbacks for the plugin will fire off a show when the scrolling has stopped. if ( !autoHideMode && currentstate === "overlay" ) { if ( !delayTimer ) { $.mobile.fixedToolbars.hide( true ); } $.mobile.fixedToolbars.startShowTimer(); } } $(function() { var $document = $( document ), $window = $( window ); $document .bind( "vmousedown", function( event ) { if ( touchToggleEnabled ) { stateBefore = currentstate; } }) .bind( "vclick", function( event ) { if ( touchToggleEnabled ) { if ( $(event.target).closest( ignoreTargets ).length ) { return; } if ( !scrollTriggered ) { $.mobile.fixedToolbars.toggle( stateBefore ); stateBefore = null; } } }) .bind( "silentscroll", showEventCallback ); // The below checks first for a $(document).scrollTop() value, and if zero, binds scroll events to $(window) instead. // If the scrollTop value is actually zero, both will return zero anyway. // // Works with $(document), not $(window) : Opera Mobile (WinMO phone; kinda broken anyway) // Works with $(window), not $(document) : IE 7/8 // Works with either $(window) or $(document) : Chrome, FF 3.6/4, Android 1.6/2.1, iOS // Needs work either way : BB5, Opera Mobile (iOS) ( ( $document.scrollTop() === 0 ) ? $window : $document ) .bind( "scrollstart", function( event ) { scrollTriggered = true; if ( stateBefore === null ) { stateBefore = currentstate; } // We only enter autoHideMode if the headers/footers are in // an overlay state or the show timer was started. If the // show timer is set, clear it so the headers/footers don't // show up until after we're done scrolling. var isOverlayState = stateBefore == "overlay"; autoHideMode = isOverlayState || !!delayTimer; if ( autoHideMode ) { $.mobile.fixedToolbars.clearShowTimer(); if ( isOverlayState ) { $.mobile.fixedToolbars.hide( true ); } } }) .bind( "scrollstop", function( event ) { if ( $( event.target ).closest( ignoreTargets ).length ) { return; } scrollTriggered = false; if ( autoHideMode ) { $.mobile.fixedToolbars.startShowTimer(); autoHideMode = false; } stateBefore = null; }); $window.bind( "resize", showEventCallback ); }); // 1. Before page is shown, check for duplicate footer // 2. After page is shown, append footer to new page $( ".ui-page" ) .live( "pagebeforeshow", function( event, ui ) { var page = $( event.target ), footer = page.find( ":jqmData(role='footer')" ), id = footer.data( "id" ), prevPage = ui.prevPage, prevFooter = prevPage && prevPage.find( ":jqmData(role='footer')" ), prevFooterMatches = prevFooter.length && prevFooter.jqmData( "id" ) === id; if ( id && prevFooterMatches ) { stickyFooter = footer; setTop( stickyFooter.removeClass( "fade in out" ).appendTo( $.mobile.pageContainer ) ); } }) .live( "pageshow", function( event, ui ) { var $this = $( this ); if ( stickyFooter && stickyFooter.length ) { setTimeout(function() { setTop( stickyFooter.appendTo( $this ).addClass( "fade" ) ); stickyFooter = null; }, 500); } $.mobile.fixedToolbars.show( true, this ); }); // When a collapsiable is hidden or shown we need to trigger the fixed toolbar to reposition itself (#1635) $( ".ui-collapsible-contain" ).live( "collapse expand", showEventCallback ); // element.getBoundingClientRect() is broken in iOS 3.2.1 on the iPad. The // coordinates inside of the rect it returns don't have the page scroll position // factored out of it like the other platforms do. To get around this, // we'll just calculate the top offset the old fashioned way until core has // a chance to figure out how to handle this situation. // // TODO: We'll need to get rid of getOffsetTop() once a fix gets folded into core. function getOffsetTop( ele ) { var top = 0, op, body; if ( ele ) { body = document.body; op = ele.offsetParent; top = ele.offsetTop; while ( ele && ele != body ) { top += ele.scrollTop || 0; if ( ele == op ) { top += op.offsetTop; op = ele.offsetParent; } ele = ele.parentNode; } } return top; } function setTop( el ) { var fromTop = $(window).scrollTop(), thisTop = getOffsetTop( el[ 0 ] ), // el.offset().top returns the wrong value on iPad iOS 3.2.1, call our workaround instead. thisCSStop = el.css( "top" ) == "auto" ? 0 : parseFloat(el.css( "top" )), screenHeight = window.innerHeight, thisHeight = el.outerHeight(), useRelative = el.parents( ".ui-page:not(.ui-page-fullscreen)" ).length, relval; if ( el.is( ".ui-header-fixed" ) ) { relval = fromTop - thisTop + thisCSStop; if ( relval < thisTop ) { relval = 0; } return el.css( "top", useRelative ? relval : fromTop ); } else { // relval = -1 * (thisTop - (fromTop + screenHeight) + thisCSStop + thisHeight); // if ( relval > thisTop ) { relval = 0; } relval = fromTop + screenHeight - thisHeight - (thisTop - thisCSStop ); return el.css( "top", useRelative ? relval : fromTop + screenHeight - thisHeight ); } } // Exposed methods return { show: function( immediately, page ) { $.mobile.fixedToolbars.clearShowTimer(); currentstate = "overlay"; var $ap = page ? $( page ) : ( $.mobile.activePage ? $.mobile.activePage : $( ".ui-page-active" ) ); return $ap.children( toolbarSelector ).each(function() { var el = $( this ), fromTop = $( window ).scrollTop(), // el.offset().top returns the wrong value on iPad iOS 3.2.1, call our workaround instead. thisTop = getOffsetTop( el[ 0 ] ), screenHeight = window.innerHeight, thisHeight = el.outerHeight(), alreadyVisible = ( el.is( ".ui-header-fixed" ) && fromTop <= thisTop + thisHeight ) || ( el.is( ".ui-footer-fixed" ) && thisTop <= fromTop + screenHeight ); // Add state class el.addClass( "ui-fixed-overlay" ).removeClass( "ui-fixed-inline" ); if ( !alreadyVisible && !immediately ) { el.animationComplete(function() { el.removeClass( "in" ); }).addClass( "in" ); } setTop(el); }); }, hide: function( immediately ) { currentstate = "inline"; var $ap = $.mobile.activePage ? $.mobile.activePage : $( ".ui-page-active" ); return $ap.children( toolbarSelector ).each(function() { var el = $(this), thisCSStop = el.css( "top" ), classes; thisCSStop = thisCSStop == "auto" ? 0 : parseFloat(thisCSStop); // Add state class el.addClass( "ui-fixed-inline" ).removeClass( "ui-fixed-overlay" ); if ( thisCSStop < 0 || ( el.is( ".ui-header-fixed" ) && thisCSStop !== 0 ) ) { if ( immediately ) { el.css( "top", 0); } else { if ( el.css( "top" ) !== "auto" && parseFloat( el.css( "top" ) ) !== 0 ) { classes = "out reverse"; el.animationComplete(function() { el.removeClass( classes ).css( "top", 0 ); }).addClass( classes ); } } } }); }, startShowTimer: function() { $.mobile.fixedToolbars.clearShowTimer(); var args = [].slice.call( arguments ); delayTimer = setTimeout(function() { delayTimer = undefined; $.mobile.fixedToolbars.show.apply( null, args ); }, showDelay); }, clearShowTimer: function() { if ( delayTimer ) { clearTimeout( delayTimer ); } delayTimer = undefined; }, toggle: function( from ) { if ( from ) { currentstate = from; } return ( currentstate === "overlay" ) ? $.mobile.fixedToolbars.hide() : $.mobile.fixedToolbars.show(); }, setTouchToggleEnabled: function( enabled ) { touchToggleEnabled = enabled; } }; })(); // TODO - Deprecated namepace on $. Remove in a later release $.fixedToolbars = $.mobile.fixedToolbars; //auto self-init widgets $( document ).bind( "pagecreate create", function( event ) { if ( $( ":jqmData(position='fixed')", event.target ).length ) { $( event.target ).each(function() { if ( !$.support.scrollTop ) { return this; } var $this = $( this ); if ( $this.jqmData( "fullscreen" ) ) { $this.addClass( "ui-page-fullscreen" ); } // Should be slidedown $this.find( slideDownSelector ).addClass( slideDownClass ); // Should be slideup $this.find( slideUpSelector ).addClass( slideUpClass ); }) } }); })( jQuery ); /* * jQuery Mobile Framework : resolution and CSS media query related helpers and behavior * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { var $window = $( window ), $html = $( "html" ), //media-query-like width breakpoints, which are translated to classes on the html element resolutionBreakpoints = [ 320, 480, 768, 1024 ]; /* private function for adding/removing breakpoint classes to HTML element for faux media-query support It does not require media query support, instead using JS to detect screen width > cross-browser support This function is called on orientationchange, resize, and mobileinit, and is bound via the 'htmlclass' event namespace */ function detectResolutionBreakpoints() { var currWidth = $window.width(), minPrefix = "min-width-", maxPrefix = "max-width-", minBreakpoints = [], maxBreakpoints = [], unit = "px", breakpointClasses; $html.removeClass( minPrefix + resolutionBreakpoints.join(unit + " " + minPrefix) + unit + " " + maxPrefix + resolutionBreakpoints.join( unit + " " + maxPrefix) + unit ); $.each( resolutionBreakpoints, function( i, breakPoint ) { if( currWidth >= breakPoint ) { minBreakpoints.push( minPrefix + breakPoint + unit ); } if( currWidth <= breakPoint ) { maxBreakpoints.push( maxPrefix + breakPoint + unit ); } }); if ( minBreakpoints.length ) { breakpointClasses = minBreakpoints.join(" "); } if ( maxBreakpoints.length ) { breakpointClasses += " " + maxBreakpoints.join(" "); } $html.addClass( breakpointClasses ); }; /* $.mobile.addResolutionBreakpoints method: pass either a number or an array of numbers and they'll be added to the min/max breakpoint classes Examples: $.mobile.addResolutionBreakpoints( 500 ); $.mobile.addResolutionBreakpoints( [500, 1200] ); */ $.mobile.addResolutionBreakpoints = function( newbps ) { if( $.type( newbps ) === "array" ){ resolutionBreakpoints = resolutionBreakpoints.concat( newbps ); } else { resolutionBreakpoints.push( newbps ); } resolutionBreakpoints.sort(function( a, b ) { return a - b; }); detectResolutionBreakpoints(); }; /* on mobileinit, add classes to HTML element and set handlers to update those on orientationchange and resize */ $( document ).bind( "mobileinit.htmlclass", function() { // bind to orientationchange and resize // to add classes to HTML element for min/max breakpoints and orientation var ev = $.support.orientation; $window.bind( "orientationchange.htmlclass throttledResize.htmlclass", function( event ) { // add orientation class to HTML element on flip/resize. if ( event.orientation ) { $html.removeClass( "portrait landscape" ).addClass( event.orientation ); } // add classes to HTML element for min/max breakpoints detectResolutionBreakpoints(); }); }); /* Manually trigger an orientationchange event when the dom ready event fires. This will ensure that any viewport meta tag that may have been injected has taken effect already, allowing us to properly calculate the width of the document. */ $(function() { //trigger event manually $window.trigger( "orientationchange.htmlclass" ); }); })(jQuery);/*! * jQuery Mobile v@VERSION * http://jquerymobile.com/ * * Copyright 2010, jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, window, undefined ) { var $html = $( "html" ), $head = $( "head" ), $window = $( window ); //trigger mobileinit event - useful hook for configuring $.mobile settings before they're used $( window.document ).trigger( "mobileinit" ); //support conditions //if device support condition(s) aren't met, leave things as they are -> a basic, usable experience, //otherwise, proceed with the enhancements if ( !$.mobile.gradeA() ) { return; } // override ajaxEnabled on platforms that have known conflicts with hash history updates // or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini) if( $.mobile.ajaxBlacklist ){ $.mobile.ajaxEnabled = false; } //add mobile, initial load "rendering" classes to docEl $html.addClass( "ui-mobile ui-mobile-rendering" ); //loading div which appears during Ajax requests //will not appear if $.mobile.loadingMessage is false var $loader = $( "<div class='ui-loader ui-body-a ui-corner-all'><span class='ui-icon ui-icon-loading spin'></span><h1></h1></div>" ); $.extend($.mobile, { // turn on/off page loading message. showPageLoadingMsg: function() { if( $.mobile.loadingMessage ){ var activeBtn = $( "." + $.mobile.activeBtnClass ).first(); $loader .find( "h1" ) .text( $.mobile.loadingMessage ) .end() .appendTo( $.mobile.pageContainer ) //position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top .css( { top: $.support.scrollTop && $(window).scrollTop() + $(window).height() / 2 || activeBtn.length && activeBtn.offset().top || 100 } ); } $html.addClass( "ui-loading" ); }, hidePageLoadingMsg: function() { $html.removeClass( "ui-loading" ); }, // XXX: deprecate for 1.0 pageLoading: function ( done ) { if ( done ) { $.mobile.hidePageLoadingMsg(); } else { $.mobile.showPageLoadingMsg(); } }, // find and enhance the pages in the dom and transition to the first page. initializePage: function(){ //find present pages var $pages = $( ":jqmData(role='page')" ); //if no pages are found, create one with body's inner html if( !$pages.length ){ $pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 ); } //add dialogs, set data-url attrs $pages.add( ":jqmData(role='dialog')" ).each(function(){ var $this = $(this); // unless the data url is already set set it to the id if( !$this.jqmData('url') ){ $this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) ); } }); //define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback) $.mobile.firstPage = $pages.first(); //define page container $.mobile.pageContainer = $pages.first().parent().addClass( "ui-mobile-viewport" ); //cue page loading message $.mobile.showPageLoadingMsg(); // if hashchange listening is disabled or there's no hash deeplink, change to the first page in the DOM if( !$.mobile.hashListeningEnabled || !$.mobile.path.stripHash( location.hash ) ){ $.mobile.changePage( $.mobile.firstPage, { transition: "none", reverse: true, changeHash: false, fromHashChange: true } ); } // otherwise, trigger a hashchange to load a deeplink else { $window.trigger( "hashchange", [ true ] ); } } }); //initialize events now, after mobileinit has occurred $.mobile._registerInternalEvents(); //check which scrollTop value should be used by scrolling to 1 immediately at domready //then check what the scroll top is. Android will report 0... others 1 //note that this initial scroll won't hide the address bar. It's just for the check. $(function(){ window.scrollTo( 0, 1 ); //if defaultHomeScroll hasn't been set yet, see if scrollTop is 1 //it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar) //so if it's 1, use 0 from now on $.mobile.defaultHomeScroll = ( !$.support.scrollTop || $(window).scrollTop() === 1 ) ? 0 : 1; //dom-ready inits if( $.mobile.autoInitializePage ){ $( $.mobile.initializePage ); } //window load event //hide iOS browser chrome on load $window.load( $.mobile.silentScroll ); }); })( jQuery, this );
JavaScript
//quick view source in new window links $.fn.addSourceLink = function(style){ return $(this).each(function(){ var link = $('<a href="#" data-'+ $.mobile.ns +'inline="true">View Source</a>'), src = src = $('<div></div>').append( $(this).clone() ).html(), page = $( "<div data-"+ $.mobile.ns +"role='dialog' data-"+ $.mobile.ns +"theme='a'>" + "<div data-"+ $.mobile.ns +"role='header' data-"+ $.mobile.ns +"theme='b'>" + "<a href='#' class='ui-btn-left' data-"+ $.mobile.ns +"icon='delete' data-"+ $.mobile.ns +"iconpos='notext'>Close</a>"+ "<div class='ui-title'>jQuery Mobile Source Excerpt</div>"+ "</div>"+ "<div data-"+ $.mobile.ns +"role='content'></div>"+ "</div>" ) .appendTo( "body" ) .page(); $('<a href="#">View Source</a>') .buttonMarkup({ icon: 'arrow-u', iconpos: 'notext' }) .click(function(){ var codeblock = $('<pre><code></code></pre>'); src = src.replace(/&/gmi, '&amp;').replace(/"/gmi, '&quot;').replace(/>/gmi, '&gt;').replace(/</gmi, '&lt;').replace('data-'+ $.mobile.ns +'source="true"',''); codeblock.find('code').append(src); var activePage = $(this).parents('.ui-page-active'); page.find('.ui-content').append(codeblock); $.changePage(page, 'slideup',false); page.find('.ui-btn-left').click(function(){ $.changePage(activepage, 'slideup',true); return false; }); }) .insertAfter(this); }); }; //set up view source links $('div').live('pagebeforecreate',function(){ $(this).find('[data-'+ $.mobile.ns +'source="true"]').addSourceLink(); });
JavaScript
//set up the theme switcher on the homepage $('div').live('pagecreate',function(event){ if( !$(this).is('.ui-dialog')){ var appendEl = $(this).find('.ui-footer:last'); if( !appendEl.length ){ appendEl = $(this).find('.ui-content'); } if( appendEl.is("[data-position]") ){ return; } $('<a href="#themeswitcher" data-'+ $.mobile.ns +'rel="dialog" data-'+ $.mobile.ns +'transition="pop">Switch theme</a>') .buttonMarkup({ 'icon':'gear', 'inline': true, 'shadow': false, 'theme': 'd' }) .appendTo( appendEl ) .wrap('<div class="jqm-themeswitcher">') .bind( "vclick", function(){ $.themeswitcher(); }); } }); //collapse page navs after use $(function(){ $('body').delegate('.content-secondary .ui-collapsible-content', 'click', function(){ $(this).trigger("collapse") }); }); function setDefaultTransition(){ var winwidth = $( window ).width(), trans ="slide"; if( winwidth >= 1000 ){ trans = "none"; } else if( winwidth >= 650 ){ trans = "fade"; } $.mobile.defaultPageTransition = trans; } $(function(){ setDefaultTransition(); $( window ).bind( "throttledresize", setDefaultTransition ); });
JavaScript
/* * mobile button unit tests */ (function($){ $.mobile.page.prototype.options.keepNative = "button.should-be-native"; test( "button elements in the keepNative set shouldn't be enhanced", function() { same( $("button.should-be-native").siblings("div.ui-slider").length, 0 ); }); test( "button elements should be enhanced", function() { ok( $("#enhanced").hasClass( "ui-btn-hidden" ) ); }); test( "button markup text value should be changed on refresh", function() { var textValueButton = $("#text"), valueButton = $("#value"); // the value shouldn't change unless it's been altered textValueButton.button( 'refresh' ); same( textValueButton.siblings().text(), "foo" ); // use the text where it's provided same( textValueButton.siblings().text(), "foo" ); textValueButton.text( "bar" ).button( 'refresh' ); same( textValueButton.siblings().text(), "bar" ); // use the val if it's provided where the text isn't same( valueButton.siblings().text(), "foo" ); valueButton.val( "bar" ).button( 'refresh' ); same( valueButton.siblings().text(), "bar" ); // prefer the text to the value textValueButton.text( "bar" ).val( "baz" ).button( 'refresh' ); same( textValueButton.siblings().text(), "bar" ); }); // Issue 2877 test( "verify the button placeholder is added many times", function() { var $form = $( "#hidden-element-addition-form" ), count = 3; expect( count * 2 ); for( var x = 0; x < count; x++ ) { $( "#hidden-element-addition" ).trigger( "vclick" ); same( $form.find( "input[type='hidden']" ).length, 1, "hidden form input should be added" ); $form.trigger( "submit" ); same( $form.find( "[type='hidden']" ).length, 0, "hidden form input is removed" ); } }); })( jQuery );
JavaScript
/* * mobile page unit tests */ (function($){ var libName = 'jquery.mobile.page.js'; module(libName); test( "nested header anchors aren't altered", function(){ ok(!$('.ui-header > div > a').hasClass('ui-btn')); }); test( "nested footer anchors aren't altered", function(){ ok(!$('.ui-footer > div > a').hasClass('ui-btn')); }); test( "nested bar anchors aren't styled", function(){ ok(!$('.ui-bar > div > a').hasClass('ui-btn')); }); test( "unnested footer anchors are styled", function(){ ok($('.ui-footer > a').hasClass('ui-btn')); }); test( "unnested footer anchors are styled", function(){ ok($('.ui-footer > a').hasClass('ui-btn')); }); test( "unnested bar anchors are styled", function(){ ok($('.ui-bar > a').hasClass('ui-btn')); }); test( "no auto-generated back button exists on first page", function(){ ok( !$(".ui-header > :jqmData(rel='back')").length ); }); })(jQuery);
JavaScript
/* * mobile textinput unit tests */ (function($){ module( "jquery.mobile.forms.textinput.js" ); test( "inputs without type specified are enhanced", function(){ ok( $( "#typeless-input" ).hasClass( "ui-input-text" ) ); }); $.mobile.page.prototype.options.keepNative = "textarea.should-be-native"; // not testing the positive case here since's it's obviously tested elsewhere test( "textarea in the keepNative set shouldn't be enhanced", function() { ok( !$("textarea.should-be-native").is("ui-input-text") ); }); asyncTest( "textarea should autogrow on document ready", function() { var test = $( "#init-autogrow" ); setTimeout(function() { ok( $( "#reference-autogrow" )[0].clientHeight < test[0].clientHeight, "the height is greater than the reference text area with no content" ); ok( test[0].clientHeight > 100, "autogrow text area's height is greater than any style padding"); start(); }, 400); }); asyncTest( "textarea should autogrow when text is added via the keyboard", function() { var test = $( "#keyup-autogrow" ), originalHeight = test[0].clientHeight; test.keyup(function() { setTimeout(function() { ok( test[0].clientHeight > originalHeight, "the height is greater than original with no content" ); ok( test[0].clientHeight > 100, "autogrow text area's height is greater any style/padding"); start(); }, 400); }); test.val("foo\n\n\n\n\n\n\n\n\n\n\n\n\n\n").trigger("keyup"); }); asyncTest( "text area should auto grow when the parent page is loaded via ajax", function() { $.testHelper.pageSequence([ function() { $("#external").click(); }, function() { setTimeout(function() { ok($.mobile.activePage.find( "textarea" )[0].clientHeight > 100, "text area's height has grown"); window.history.back(); }, 1000); }, function() { start(); } ]); }); })(jQuery);
JavaScript
(function($) { asyncTest( "nested pages hash key is always in the hash on default page with no id (replaceState) ", function(){ $.testHelper.pageSequence([ function(){ // Click on the link of the third li element $('.ui-page-active li:eq(2) a:eq(0)').click(); }, function(){ ok( location.hash.search($.mobile.subPageUrlKey) >= 0 ); start(); } ]); }); })(jQuery);
JavaScript
/* * mobile listview unit tests */ // TODO split out into seperate test files (function($){ var home = $.mobile.path.parseUrl( location.href ).pathname; $.mobile.defaultTransition = "none"; module( "Basic Linked list", { setup: function(){ $.testHelper.openPage( "#basic-linked-test" ); } }); asyncTest( "The page should enhanced correctly", function(){ setTimeout(function() { ok($('#basic-linked-test .ui-li').length, ".ui-li classes added to li elements"); start(); }, 800); }); asyncTest( "Slides to the listview page when the li a is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#basic-linked-test"); }, function(){ $('#basic-linked-test li a').first().click(); }, function(){ ok($('#basic-link-results').hasClass('ui-page-active')); start(); } ]); }); asyncTest( "Slides back to main page when back button is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#basic-link-results"); }, function(){ window.history.back(); }, function(){ ok($('#basic-linked-test').hasClass('ui-page-active')); start(); } ]); }); asyncTest( "Presence of ui-li-has- classes", function(){ $.testHelper.pageSequence( [ function() { $.testHelper.openPage( "#ui-li-has-test" ); }, function() { var page = $( ".ui-page-active" ), items = page.find( "li" ); ok( items.eq( 0 ).hasClass( "ui-li-has-count"), "First LI should have ui-li-has-count class" ); ok( items.eq( 0 ).hasClass( "ui-li-has-arrow"), "First LI should have ui-li-has-arrow class" ); ok( !items.eq( 1 ).hasClass( "ui-li-has-count"), "Second LI should NOT have ui-li-has-count class" ); ok( items.eq( 1 ).hasClass( "ui-li-has-arrow"), "Second LI should have ui-li-has-arrow class" ); ok( !items.eq( 2 ).hasClass( "ui-li-has-count"), "Third LI should NOT have ui-li-has-count class" ); ok( !items.eq( 2 ).hasClass( "ui-li-has-arrow"), "Third LI should NOT have ui-li-has-arrow class" ); ok( items.eq( 3 ).hasClass( "ui-li-has-count"), "Fourth LI should have ui-li-has-count class" ); ok( !items.eq( 3 ).hasClass( "ui-li-has-arrow"), "Fourth LI should NOT have ui-li-has-arrow class" ); ok( !items.eq( 4 ).hasClass( "ui-li-has-count"), "Fifth LI should NOT have ui-li-has-count class" ); ok( !items.eq( 4 ).hasClass( "ui-li-has-arrow"), "Fifth LI should NOT have ui-li-has-arrow class" ); start(); } ]); }); module('Nested List Test'); asyncTest( "Changes page to nested list test and enhances", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#nested-list-test"); }, function(){ ok($('#nested-list-test').hasClass('ui-page-active'), "makes nested list test page active"); ok($(':jqmData(url="nested-list-test&ui-page=0-0")').length == 1, "Adds first UL to the page"); ok($(':jqmData(url="nested-list-test&ui-page=0-1")').length == 1, "Adds second nested UL to the page"); start(); } ]); }); asyncTest( "change to nested page when the li a is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#nested-list-test"); }, function(){ $('.ui-page-active li:eq(1) a:eq(0)').click(); }, function(){ var $new_page = $(':jqmData(url="nested-list-test&ui-page=0-0")'); ok($new_page.hasClass('ui-page-active'), 'Makes the nested page the active page.'); ok($('.ui-listview', $new_page).find(":contains('Rhumba of rattlesnakes')").length == 1, "The current page should have the proper text in the list."); ok($('.ui-listview', $new_page).find(":contains('Shoal of Bass')").length == 1, "The current page should have the proper text in the list."); start(); } ]); }); asyncTest( "should go back to top level when the back button is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#nested-list-test&ui-page=0-0"); }, function(){ window.history.back(); }, function(){ ok($('#nested-list-test').hasClass('ui-page-active'), 'Transitions back to the parent nested page'); start(); } ]); }); test( "nested list title should use first text node, regardless of line breaks", function(){ ok($('#nested-list-test .linebreaknode').text() === "More animals", 'Text should be "More animals"'); }); asyncTest( "Multiple nested lists on a page with same labels", function() { $.testHelper.pageSequence([ function(){ // https://github.com/jquery/jquery-mobile/issues/1617 $.testHelper.openPage("#nested-lists-test"); }, function(){ // Click on the link of the third li element $('.ui-page-active li:eq(2) a:eq(0)').click(); }, function(){ equal($('.ui-page-active .ui-content .ui-listview li').text(), "Item A-3-0Item A-3-1Item A-3-2", 'Text should be "Item A-3-0Item A-3-1Item A-3-2"'); start(); } ]); }); module('Ordered Lists'); asyncTest( "changes to the numbered list page and enhances it", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#numbered-list-test"); }, function(){ var $new_page = $('#numbered-list-test'); ok($new_page.hasClass('ui-page-active'), "Makes the new page active when the hash is changed."); ok($('.ui-link-inherit', $new_page).first().text() == "Number 1", "The text of the first LI should be Number 1"); start(); } ]); }); asyncTest( "changes to number 1 page when the li a is clicked", function() { $.testHelper.pageSequence([ function(){ $('#numbered-list-test li a').first().click(); }, function(){ ok($('#numbered-list-results').hasClass('ui-page-active'), "The new numbered page was transitioned correctly."); start(); } ]); }); asyncTest( "takes us back to the numbered list when the back button is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage('#numbered-list-test'); }, function(){ $.testHelper.openPage('#numbered-list-results'); }, function(){ window.history.back(); }, function(){ ok($('#numbered-list-test').hasClass('ui-page-active')); start(); } ]); }); module('Read only list'); asyncTest( "changes to the read only page when hash is changed", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#read-only-list-test"); }, function(){ var $new_page = $('#read-only-list-test'); ok($new_page.hasClass('ui-page-active'), "makes the read only page the active page"); ok($('li', $new_page).first().text() === "Read", "The first LI has the proper text."); start(); } ]); }); module('Split view list'); asyncTest( "changes the page to the split view list and enhances it correctly.", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#split-list-test"); }, function(){ var $new_page = $('#split-list-test'); ok($('.ui-li-link-alt', $new_page).length == 3); ok($('.ui-link-inherit', $new_page).length == 3); start(); } ]); }); asyncTest( "change the page to the split view page 1 when the first link is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#split-list-test"); }, function(){ $('.ui-page-active .ui-li a:eq(0)').click(); }, function(){ ok($('#split-list-link1').hasClass('ui-page-active')); start(); } ]); }); asyncTest( "Slide back to the parent list view when the back button is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#split-list-test"); }, function(){ $('.ui-page-active .ui-listview a:eq(0)').click(); }, function(){ history.back(); }, function(){ ok($('#split-list-test').hasClass('ui-page-active')); start(); } ]); }); asyncTest( "Clicking on the icon (the second link) should take the user to other a href of this LI", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#split-list-test"); }, function(){ $('.ui-page-active .ui-li-link-alt:eq(0)').click(); }, function(){ ok($('#split-list-link2').hasClass('ui-page-active')); start(); } ]); }); module( "List Dividers" ); asyncTest( "Makes the list divider page the active page and enhances it correctly.", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#list-divider-test"); }, function(){ var $new_page = $('#list-divider-test'); ok($new_page.find('.ui-li-divider').length == 2); ok($new_page.hasClass('ui-page-active')); start(); } ]); }); module( "Search Filter"); var searchFilterId = "#search-filter-test"; asyncTest( "Filter downs results when the user enters information", function() { var $searchPage = $(searchFilterId); $.testHelper.pageSequence([ function() { $.testHelper.openPage(searchFilterId); }, function() { $searchPage.find('input').val('at'); $searchPage.find('input').trigger('change'); same($searchPage.find('li.ui-screen-hidden').length, 2); start(); } ]); }); asyncTest( "Redisplay results when user removes values", function() { var $searchPage = $(searchFilterId); $.testHelper.pageSequence([ function() { $.testHelper.openPage(searchFilterId); }, function() { $searchPage.find('input').val('a'); $searchPage.find('input').trigger('change'); same($searchPage.find("li[style^='display: none;']").length, 0); start(); } ]); }); asyncTest( "Filter works fine with \\W- or regexp-special-characters", function() { var $searchPage = $(searchFilterId); $.testHelper.pageSequence([ function() { $.testHelper.openPage(searchFilterId); }, function() { $searchPage.find('input').val('*'); $searchPage.find('input').trigger('change'); same($searchPage.find('li.ui-screen-hidden').length, 4); start(); } ]); }); test( "Refresh applies thumb styling", function(){ var ul = $('.ui-page-active ul'); ul.append("<li id='fiz'><img/></li>"); ok(!ul.find("#fiz img").hasClass("ui-li-thumb")); ul.listview('refresh'); ok(ul.find("#fiz img").hasClass("ui-li-thumb")); }); asyncTest( "Filter downs results and dividers when the user enters information", function() { var $searchPage = $("#search-filter-with-dividers-test"); $.testHelper.pageSequence([ function() { $.testHelper.openPage("#search-filter-with-dividers-test"); }, // wait for the page to become active/enhanced function(){ $searchPage.find('input').val('at'); $searchPage.find('input').trigger('change'); setTimeout(function() { //there should be four hidden list entries same($searchPage.find('li.ui-screen-hidden').length, 4); //there should be two list entries that are list dividers and hidden same($searchPage.find('li.ui-screen-hidden:jqmData(role=list-divider)').length, 2); //there should be two list entries that are not list dividers and hidden same($searchPage.find('li.ui-screen-hidden:not(:jqmData(role=list-divider))').length, 2); start(); }, 1000); } ]); }); asyncTest( "Redisplay results when user removes values", function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#search-filter-with-dividers-test"); }, function() { $('.ui-page-active input').val('a'); $('.ui-page-active input').trigger('change'); setTimeout(function() { same($('.ui-page-active input').val(), 'a'); same($('.ui-page-active li[style^="display: none;"]').length, 0); start(); }, 1000); } ]); }); asyncTest( "Dividers are hidden when preceding hidden rows and shown when preceding shown rows", function () { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#search-filter-with-dividers-test"); }, function() { var $page = $('.ui-page-active'); $page.find('input').val('at'); $page.find('input').trigger('change'); setTimeout(function() { same($page.find('li:jqmData(role=list-divider):hidden').length, 2); same($page.find('li:jqmData(role=list-divider):hidden + li:not(:jqmData(role=list-divider)):hidden').length, 2); same($page.find('li:jqmData(role=list-divider):not(:hidden) + li:not(:jqmData(role=list-divider)):not([:hidden)').length, 2); start(); }, 1000); } ]); }); asyncTest( "Inset List View should refresh corner classes after filtering", 4 * 2, function () { var checkClasses = function() { var $page = $( ".ui-page-active" ), $li = $page.find( "li:visible" ); ok($li.first().hasClass( "ui-corner-top" ), $li.length+" li elements: First visible element should have class ui-corner-top"); ok($li.last().hasClass( "ui-corner-bottom" ), $li.length+" li elements: Last visible element should have class ui-corner-bottom"); }; $.testHelper.pageSequence([ function() { $.testHelper.openPage("#search-filter-inset-test"); }, function() { var $page = $('.ui-page-active'); $.testHelper.sequence([ function() { checkClasses(); $page.find('input').val('man'); $page.find('input').trigger('change'); }, function() { checkClasses(); $page.find('input').val('at'); $page.find('input').trigger('change'); }, function() { checkClasses(); $page.find('input').val('catwoman'); $page.find('input').trigger('change'); }, function() { checkClasses(); start(); } ], 50); } ]); }); module( "Programmatically generated list items", { setup: function(){ var item, data = [ { id: 1, label: "Item 1" }, { id: 2, label: "Item 2" }, { id: 3, label: "Item 3" }, { id: 4, label: "Item 4" } ]; $( "#programmatically-generated-list-items" ).html(""); for ( var i = 0, len = data.length; i < len; i++ ) { item = $( '<li id="myItem' + data[i].id + '">' ); label = $( "<strong>" + data[i].label + "</strong>").appendTo( item ); $( "#programmatically-generated-list-items" ).append( item ); } } }); asyncTest( "Corner styling on programmatically created list items", function() { // https://github.com/jquery/jquery-mobile/issues/1470 $.testHelper.pageSequence([ function() { $.testHelper.openPage( "#programmatically-generated-list" ); }, function() { ok(!$( "#programmatically-generated-list-items li:first-child" ).hasClass( "ui-corner-bottom" ), "First list item should not have class ui-corner-bottom" ); start(); } ]); }); module("Programmatic list items manipulation"); asyncTest("Removing list items", 4, function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#removing-items-from-list-test"); }, function() { var ul = $('#removing-items-from-list-test ul'); ul.find("li").first().remove(); equal(ul.find("li").length, 3, "There should be only 3 list items left"); ul.listview('refresh'); ok(ul.find("li").first().hasClass("ui-corner-top"), "First list item should have class ui-corner-top"); ul.find("li").last().remove(); equal(ul.find("li").length, 2, "There should be only 2 list items left"); ul.listview('refresh'); ok(ul.find("li").last().hasClass("ui-corner-bottom"), "Last list item should have class ui-corner-bottom"); start(); } ]); }); module("Rounded corners"); asyncTest("Top and bottom corners rounded in inset list", 14, function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#corner-rounded-test"); }, function() { var ul = $('#corner-rounded-test ul'); for( var t = 0; t<3; t++){ ul.append("<li>Item " + t + "</li>"); ul.listview('refresh'); equals(ul.find(".ui-corner-top").length, 1, "There should be only one element with class ui-corner-top"); equals(ul.find("li:visible").first()[0], ul.find(".ui-corner-top")[0], "First list item should have class ui-corner-top in list with " + ul.find("li").length + " item(s)"); equals(ul.find(".ui-corner-bottom").length, 1, "There should be only one element with class ui-corner-bottom"); equals(ul.find("li:visible").last()[0], ul.find(".ui-corner-bottom")[0], "Last list item should have class ui-corner-bottom in list with " + ul.find("li").length + " item(s)"); } ul.find( "li" ).first().hide(); ul.listview( "refresh" ); equals(ul.find("li:visible").first()[0], ul.find(".ui-corner-top")[0], "First visible list item should have class ui-corner-top"); ul.find( "li" ).last().hide(); ul.listview( "refresh" ); equals(ul.find("li:visible").last()[0], ul.find(".ui-corner-bottom")[0], "Last visible list item should have class ui-corner-bottom"); start(); } ]); }); test( "Listview will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-listview").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-listview").length, "enhancements applied" ); }); module( "Cached Linked List" ); var findNestedPages = function(selector){ return $( selector + " #topmost" ).listview( 'childPages' ); }; asyncTest( "nested pages are removed from the dom by default", function(){ $.testHelper.pageSequence([ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function(){ $.testHelper.openPage( "#cache-tests/uncached-nested.html" ); }, function(){ ok( findNestedPages( "#uncached-nested-list" ).length > 0, "verify that there are nested pages" ); $.testHelper.openPage( "#" + home ); }, function() { $.testHelper.openPage( "#cache-tests/clear.html" ); }, function(){ same( findNestedPages( "#uncached-nested-list" ).length, 0 ); start(); } ]); }); asyncTest( "nested pages preserved when parent page is cached", function(){ $.testHelper.pageSequence([ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function(){ $.testHelper.openPage( "#cache-tests/cached-nested.html" ); }, function(){ ok( findNestedPages( "#cached-nested-list" ).length > 0, "verify that there are nested pages" ); $.testHelper.openPage( "#" + home ); }, function() { $.testHelper.openPage( "#cache-tests/clear.html" ); }, function(){ ok( findNestedPages( "#cached-nested-list" ).length > 0, "nested pages remain" ); start(); } ]); }); asyncTest( "parent page is not removed when visiting a sub page", function(){ $.testHelper.pageSequence([ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function(){ $.testHelper.openPage( "#cache-tests/cached-nested.html" ); }, function(){ same( $("#cached-nested-list").length, 1 ); $.testHelper.openPage( "#" + home ); }, function() { $.testHelper.openPage( "#cache-tests/clear.html" ); }, function(){ same( $("#cached-nested-list").length, 1 ); start(); } ]); }); asyncTest( "filterCallback can be altered after widget creation", function(){ var listPage = $( "#search-filter-test" ); expect( listPage.find("li").length ); $.testHelper.pageSequence( [ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function() { $.testHelper.openPage( "#search-filter-test" ); }, function() { // set the listview instance callback listPage.find( "ul" ).listview( "option", "filterCallback", function() { ok(true, "custom callback invoked"); }); // trigger a change in the search filter listPage.find( "input" ).val( "foo" ).trigger( "change" ); //NOTE beware a poossible issue with timing here start(); } ]); }); asyncTest( "nested pages hash key is always in the hash (replaceState)", function(){ $.testHelper.pageSequence([ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function(){ // https://github.com/jquery/jquery-mobile/issues/1617 $.testHelper.openPage("#nested-lists-test"); }, function(){ // Click on the link of the third li element $('.ui-page-active li:eq(2) a:eq(0)').click(); }, function(){ ok( location.hash.search($.mobile.subPageUrlKey) >= 0 ); start(); } ]); }); asyncTest( "embedded listview page with nested pages is not removed from the dom", function() { $.testHelper.pageSequence([ function() { // open the nested list page same( $("div#nested-list-test").length, 1 ); $( "a#nested-list-test-anchor" ).click(); }, function() { // go back to the origin page window.history.back(); }, function() { // make sure the page is still in place same( $("div#nested-list-test").length, 1 ); start(); } ]); }); asyncTest( "list inherits theme from parent", function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#list-theme-inherit"); }, function() { var theme = $.mobile.activePage.jqmData('theme'); ok( $.mobile.activePage.find("ul > li").hasClass("ui-body-b"), "theme matches the parent"); window.history.back(); }, start ]); }); })(jQuery);
JavaScript
/* * mobile event unit tests */ (function($){ var libName = "jquery.mobile.event.js", absFn = Math.abs, originalEventFn = $.Event.prototype.originalEvent, preventDefaultFn = $.Event.prototype.preventDefault, events = ("touchstart touchmove touchend orientationchange tap taphold " + "swipe swipeleft swiperight scrollstart scrollstop").split( " " ); module(libName, { setup: function(){ // ensure bindings are removed $.each(events + "vmouseup vmousedown".split(" "), function(i, name){ $("#qunit-fixture").unbind(); }); //NOTE unmock Math.abs = absFn; $.Event.prototype.originalEvent = originalEventFn; $.Event.prototype.preventDefault = preventDefaultFn; // make sure the event objects respond to touches to simulate // the collections existence in non touch enabled test browsers $.Event.prototype.touches = [{pageX: 1, pageY: 1 }]; $($.mobile.pageContainer).unbind( "throttledresize" ); } }); $.testHelper.excludeFileProtocol(function(){ test( "new events defined on the jquery object", function(){ $.each(events, function( i, name ) { delete $.fn[name]; same($.fn[name], undefined); }); $.testHelper.reloadLib(libName); $.each(events, function( i, name ) { ok($.fn[name] !== undefined, name + " is not undefined"); }); }); }); asyncTest( "defined event functions bind a closure when passed", function(){ expect( 1 ); $('#qunit-fixture').bind(events[0], function(){ ok(true, "event fired"); start(); }); $('#qunit-fixture').trigger(events[0]); }); asyncTest( "defined event functions trigger the event with no arguments", function(){ expect( 1 ); $('#qunit-fixture').bind('touchstart', function(){ ok(true, "event fired"); start(); }); $('#qunit-fixture').touchstart(); }); test( "defining event functions sets the attrFn to true", function(){ $.each(events, function(i, name){ ok($.attrFn[name], "attribute function is true"); }); }); test( "scrollstart enabled defaults to true", function(){ $.event.special.scrollstart.enabled = false; $.testHelper.reloadLib(libName); ok($.event.special.scrollstart.enabled, "scrollstart enabled"); }); asyncTest( "scrollstart setup binds a function that returns when its disabled", function(){ expect( 1 ); $.event.special.scrollstart.enabled = false; $( "#qunit-fixture" ).bind("scrollstart", function(){ ok(false, "scrollstart fired"); }); $( "#qunit-fixture" ).bind("touchmove", function(){ ok(true, "touchmove fired"); start(); }); $( "#qunit-fixture" ).trigger("touchmove"); }); asyncTest( "scrollstart setup binds a function that triggers scroll start when enabled", function(){ $.event.special.scrollstart.enabled = true; $( "#qunit-fixture" ).bind("scrollstart", function(){ ok(true, "scrollstart fired"); start(); }); $( "#qunit-fixture" ).trigger("touchmove"); }); asyncTest( "scrollstart setup binds a function that triggers scroll stop after 50 ms", function(){ var triggered = false; $.event.special.scrollstart.enabled = true; $( "#qunit-fixture" ).bind("scrollstop", function(){ triggered = true; }); ok(!triggered, "not triggered"); $( "#qunit-fixture" ).trigger("touchmove"); setTimeout(function(){ ok(triggered, "triggered"); start(); }, 50); }); var forceTouchSupport = function(){ $.support.touch = true; $.testHelper.reloadLib(libName); //mock originalEvent information $.Event.prototype.originalEvent = { touches: [{ 'pageX' : 0 }, { 'pageY' : 0 }] }; }; asyncTest( "long press fires tap hold after 750 ms", function(){ var taphold = false; forceTouchSupport(); $( "#qunit-fixture" ).bind("taphold", function(){ taphold = true; }); $( "#qunit-fixture" ).trigger("vmousedown"); setTimeout(function(){ ok(taphold); start(); }, 751); }); //NOTE used to simulate movement when checked //TODO find a better way ... var mockAbs = function(value){ Math.abs = function(){ return value; }; }; asyncTest( "move prevents taphold", function(){ expect( 1 ); var taphold = false; forceTouchSupport(); mockAbs(100); //NOTE record taphold event $( "#qunit-fixture" ).bind("taphold", function(){ ok(false, "taphold fired"); taphold = true; }); //NOTE start the touch events $( "#qunit-fixture" ).trigger("vmousedown"); //NOTE fire touchmove to push back taphold setTimeout(function(){ $( "#qunit-fixture" ).trigger("vmousecancel"); }, 100); //NOTE verify that the taphold hasn't been fired // with the normal timing setTimeout(function(){ ok(!taphold, "taphold not fired"); start(); }, 751); }); asyncTest( "tap event fired without movement", function(){ expect( 1 ); var tap = false, checkTap = function(){ ok(true, "tap fired"); }; forceTouchSupport(); //NOTE record the tap event $( "#qunit-fixture" ).bind("tap", checkTap); $( "#qunit-fixture" ).trigger("vmousedown"); $( "#qunit-fixture" ).trigger("vmouseup"); $( "#qunit-fixture" ).trigger("vclick"); setTimeout(function(){ start(); }, 400); }); asyncTest( "tap event not fired when there is movement", function(){ expect( 1 ); var tap = false; forceTouchSupport(); //NOTE record tap event $( "#qunit-fixture" ).bind("tap", function(){ ok(false, "tap fired"); tap = true; }); //NOTE make sure movement is recorded mockAbs(100); //NOTE start and move right away $( "#qunit-fixture" ).trigger("touchstart"); $( "#qunit-fixture" ).trigger("touchmove"); //NOTE end touch sequence after 20 ms setTimeout(function(){ $( "#qunit-fixture" ).trigger("touchend"); }, 20); setTimeout(function(){ ok(!tap, "not tapped"); start(); }, 40); }); asyncTest( "tap event propagates up DOM tree", function(){ var tap = 0, $qf = $( "#qunit-fixture" ), $doc = $( document ), docTapCB = function(){ same(++tap, 2, "document tap callback called once after #qunit-fixture callback"); }; $qf.bind( "tap", function() { same(++tap, 1, "#qunit-fixture tap callback called once"); }); $doc.bind( "tap", docTapCB ); $qf.trigger( "vmousedown" ) .trigger( "vmouseup" ) .trigger( "vclick" ); // tap binding should be triggered twice, once for // #qunit-fixture, and a second time for document. same( tap, 2, "final tap callback count is 2" ); $doc.unbind( "tap", docTapCB ); start(); }); asyncTest( "stopPropagation() prevents tap from propagating up DOM tree", function(){ var tap = 0, $qf = $( "#qunit-fixture" ), $doc = $( document ), docTapCB = function(){ ok(false, "tap should NOT be triggered on document"); }; $qf.bind( "tap", function(e) { same(++tap, 1, "tap callback 1 triggered once on #qunit-fixture"); e.stopPropagation(); }) .bind( "tap", function(e) { same(++tap, 2, "tap callback 2 triggered once on #qunit-fixture"); }); $doc.bind( "tap", docTapCB); $qf.trigger( "vmousedown" ) .trigger( "vmouseup" ) .trigger( "vclick" ); // tap binding should be triggered twice. same( tap, 2, "final tap count is 2" ); $doc.unbind( "tap", docTapCB ); start(); }); asyncTest( "stopImmediatePropagation() prevents tap propagation and execution of 2nd handler", function(){ var tap = 0, $cf = $( "#qunit-fixture" ); $doc = $( document ), docTapCB = function(){ ok(false, "tap should NOT be triggered on document"); }; // Bind 2 tap callbacks on qunit-fixture. Only the first // one should ever be called. $cf.bind( "tap", function(e) { same(++tap, 1, "tap callback 1 triggered once on #qunit-fixture"); e.stopImmediatePropagation(); }) .bind( "tap", function(e) { ok(false, "tap callback 2 should NOT be triggered on #qunit-fixture"); }); $doc.bind( "tap", docTapCB); $cf.trigger( "vmousedown" ) .trigger( "vmouseup" ) .trigger( "vclick" ); // tap binding should be triggered once. same( tap, 1, "final tap count is 1" ); $doc.unbind( "tap", docTapCB ); start(); }); var swipeTimedTest = function(opts){ var swipe = false; forceTouchSupport(); $( "#qunit-fixture" ).bind('swipe', function(){ swipe = true; }); //NOTE bypass the trigger source check $.Event.prototype.originalEvent = { touches: false }; $( "#qunit-fixture" ).trigger("touchstart"); //NOTE make sure the coordinates are calculated within range // to be registered as a swipe mockAbs(opts.coordChange); setTimeout(function(){ $( "#qunit-fixture" ).trigger("touchmove"); $( "#qunit-fixture" ).trigger("touchend"); }, opts.timeout + 100); setTimeout(function(){ same(swipe, opts.expected, "swipe expected"); start(); }, opts.timeout + 200); stop(); }; test( "swipe fired when coordinate change in less than a second", function(){ swipeTimedTest({ timeout: 10, coordChange: 35, expected: true }); }); test( "swipe not fired when coordinate change takes more than a second", function(){ swipeTimedTest({ timeout: 1000, coordChange: 35, expected: false }); }); test( "swipe not fired when coordinate change <= 30", function(){ swipeTimedTest({ timeout: 1000, coordChange: 30, expected: false }); }); test( "swipe not fired when coordinate change >= 75", function(){ swipeTimedTest({ timeout: 1000, coordChange: 75, expected: false }); }); asyncTest( "scrolling prevented when coordinate change > 10", function(){ expect( 1 ); forceTouchSupport(); // ensure the swipe custome event is setup $( "#qunit-fixture" ).bind('swipe', function(){}); //NOTE bypass the trigger source check $.Event.prototype.originalEvent = { touches: false }; $.Event.prototype.preventDefault = function(){ ok(true, "prevent default called"); start(); }; mockAbs(11); $( "#qunit-fixture" ).trigger("touchstart"); $( "#qunit-fixture" ).trigger("touchmove"); }); asyncTest( "move handler returns when touchstart has been fired since touchstop", function(){ expect( 1 ); // bypass triggered event check $.Event.prototype.originalEvent = { touches: false }; forceTouchSupport(); // ensure the swipe custome event is setup $( "#qunit-fixture" ).bind('swipe', function(){}); $( "#qunit-fixture" ).trigger("touchstart"); $( "#qunit-fixture" ).trigger("touchend"); $( "#qunit-fixture" ).bind("touchmove", function(){ ok(true, "touchmove bound functions are fired"); start(); }); Math.abs = function(){ ok(false, "shouldn't compare coordinates"); }; $( "#qunit-fixture" ).trigger("touchmove"); }); var nativeSupportTest = function(opts){ $.support.orientation = opts.orientationSupport; same($.event.special.orientationchange[opts.method](), opts.returnValue); }; test( "orientation change setup should do nothing when natively supported", function(){ nativeSupportTest({ method: 'setup', orientationSupport: true, returnValue: false }); }); test( "orientation change setup should bind resize when not supported natively", function(){ nativeSupportTest({ method: 'setup', orientationSupport: false, returnValue: undefined //NOTE result of bind function call }); }); test( "orientation change teardown should do nothing when natively supported", function(){ nativeSupportTest({ method: 'teardown', orientationSupport: true, returnValue: false }); }); test( "orientation change teardown should unbind resize when not supported natively", function(){ nativeSupportTest({ method: 'teardown', orientationSupport: false, returnValue: undefined //NOTE result of unbind function call }); }); /* The following 4 tests are async so that the throttled event triggers don't interfere with subsequent tests */ asyncTest( "throttledresize event proxies resize events", function(){ $( window ).one( "throttledresize", function(){ ok( true, "throttledresize called"); start(); }); $( window ).trigger( "resize" ); }); asyncTest( "throttledresize event prevents resize events from firing more frequently than 250ms", function(){ var called = 0; $(window).bind( "throttledresize", function(){ called++; }); // NOTE 250 ms * 3 = 750ms which is plenty of time // for the events to trigger before the next test, but // not so much time that the second resize will be triggered // before the call to same() is made $.testHelper.sequence([ function(){ $(window).trigger( "resize" ).trigger( "resize" ); }, // verify that only one throttled resize was called after 250ms function(){ same( called, 1 ); }, function(){ start(); } ], 250); }); asyncTest( "throttledresize event promises that a held call will execute only once after throttled timeout", function(){ var called = 0; expect( 2 ); $.testHelper.eventSequence( "throttledresize", [ // ignore the first call $.noop, function(){ ok( true, "second throttled resize should run" ); }, function(timedOut){ ok( timedOut, "third throttled resize should not run"); start(); } ]); $.mobile.pageContainer .trigger( "resize" ) .trigger( "resize" ) .trigger( "resize" ); }); asyncTest( "mousedown mouseup and click events should add a which when its not defined", function() { var whichDefined = function( event ){ same(event.which, 1); }; $( document ).bind( "vclick", whichDefined); $( document ).trigger( "click" ); $( document ).bind( "vmousedown", whichDefined); $( document ).trigger( "mousedown" ); $( document ).bind( "vmouseup", function( event ){ same(event.which, 1); start(); }); $( document ).trigger( "mouseup" ); }); })(jQuery);
JavaScript
/* * mobile dialog unit tests */ (function($){ module('jquery.mobile.fieldContain.js'); test( "Field container contains appropriate css styles", function(){ ok($('#test-fieldcontain').hasClass('ui-field-contain ui-body ui-br'), 'A fieldcontain element must contain styles "ui-field-contain ui-body ui-br"'); }); test( "Field container will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-field-contain").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-field-contain").length, "enhancements applied" ); }); })(jQuery);
JavaScript
/* * mobile buttonMarkup tests */ (function($){ module("jquery.mobile.buttonMarkup.js"); test( "control group buttons should be enhanced inside a footer", function(){ var group, linkCount; group = $("#control-group-footer"); linkCount = group.find( "a" ).length; same( group.find("a.ui-btn").length, linkCount, "all 4 links should be buttons"); same( group.find("a > span.ui-corner-left").length, 1, "only 1 left cornered button"); same( group.find("a > span.ui-corner-right").length, 1, "only 1 right cornered button"); same( group.find("a > span:not(.ui-corner-left):not(.ui-corner-right)").length, linkCount - 2, "only 2 buttons are cornered"); }); test( "control group buttons should respect theme-related data attributes", function(){ var group = $("#control-group-content"); ok(!group.find('[data-shadow=false]').hasClass("ui-shadow"), "buttons with data-shadow=false should not have the ui-shadow class"); ok(!group.find('[data-corners=false]').hasClass("ui-btn-corner-all"), "buttons with data-corners=false should not have the ui-btn-corner-all class"); ok(!group.find('[data-iconshadow=false] .ui-icon').hasClass("ui-icon-shadow"), "buttons with data-iconshadow=false should not have the ui-icon-shadow class on their icons"); }); // Test for issue #3046 and #3054: test( "mousedown on SVG elements should not throw an exception", function(){ var svg = $("#embedded-svg"), success = true, rect; ok(svg.length > 0, "found embedded svg document" ); if ( svg.length > 0 ) { rect = $( "rect", svg ); ok(rect.length > 0, "found rect" ); try { rect.trigger("mousedown"); } catch ( ex ) { success = false; } ok( success, "mousedown executed without exception"); } }); })(jQuery);
JavaScript
/* * mobile listview unit tests */ // TODO split out into seperate test files (function( $ ){ module( "Collapsible section", {}); asyncTest( "The page should enhanced correctly", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-test" ); }, function() { var $page = $( "#basic-collapsible-test" ); ok($page.find( ".ui-content >:eq(0)" ).hasClass( "ui-collapsible" ), ".ui-collapsible class added to collapsible elements" ); ok($page.find( ".ui-content >:eq(0) >:header" ).hasClass( "ui-collapsible-heading" ), ".ui-collapsible-heading class added to collapsible heading" ); ok($page.find( ".ui-content >:eq(0) > div" ).hasClass( "ui-collapsible-content" ), ".ui-collapsible-content class added to collapsible content" ); ok($page.find( ".ui-content >:eq(0)" ).hasClass( "ui-collapsible-collapsed" ), ".ui-collapsible-collapsed added to collapsed elements" ); ok(!$page.find( ".ui-content >:eq(1)" ).hasClass( "ui-collapsible-collapsed" ), ".ui-collapsible-collapsed not added to expanded elements" ); ok($page.find( ".ui-collapsible.ui-collapsible-collapsed" ).find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-top ui-corner-bottom" ), "Collapsible header button should have class ui-corner-all" ); start(); } ]); }); asyncTest( "Expand/Collapse", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-test" ); }, function() { ok($( "#basic-collapsible-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be collapsed"); $( "#basic-collapsible-test .ui-collapsible-heading-toggle" ).eq(0).click(); ok(!$( "#basic-collapsible-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be expanded after click"); $( "#basic-collapsible-test .ui-collapsible-heading-toggle" ).eq(0).click(); ok($( "#basic-collapsible-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be collapsed"); start(); } ]); }); module( "Collapsible set", {}); asyncTest( "The page should enhanced correctly", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-set-test" ); }, function() { var $page = $( "#basic-collapsible-set-test" ); ok($page.find( ".ui-content >:eq(0)" ).hasClass( "ui-collapsible-set" ), ".ui-collapsible-set class added to collapsible set" ); ok($page.find( ".ui-content >:eq(0) > div" ).hasClass( "ui-collapsible" ), ".ui-collapsible class added to collapsible elements" ); $page.find( ".ui-collapsible-set" ).each(function() { var $this = $( this ); ok($this.find( ".ui-collapsible" ).first().find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-top" ), "First collapsible header button should have class ui-corner-top" ); ok($this.find( ".ui-collapsible" ).last().find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-bottom" ), "Last collapsible header button should have class ui-corner-bottom" ); }); start(); } ]); }); asyncTest( "Collapsible set with only one collapsible", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#collapsible-set-with-lonely-collapsible-test" ); }, function() { var $page = $( "#collapsible-set-with-lonely-collapsible-test" ); $page.find( ".ui-collapsible-set" ).each(function() { var $this = $( this ); ok($this.find( ".ui-collapsible" ).first().find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-top" ), "First collapsible header button should have class ui-corner-top" ); ok($this.find( ".ui-collapsible" ).last().find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-bottom" ), "Last collapsible header button should have class ui-corner-bottom" ); }); start(); } ]); }); asyncTest( "Section expanded by default", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-set-test" ); }, function() { equals($( "#basic-collapsible-set-test .ui-content >:eq(0) .ui-collapsible-collapsed" ).length, 2, "There should be 2 section collapsed" ); ok(!$( "#basic-collapsible-set-test .ui-content >:eq(0) >:eq(1)" ).hasClass( "ui-collapsible-collapsed" ), "Section B should be expanded" ); start(); } ]); }); asyncTest( "Expand/Collapse", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-set-test" ); }, function() { ok($( "#basic-collapsible-set-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be collapsed"); $( "#basic-collapsible-set-test .ui-collapsible-heading-toggle" ).eq(0).click(); ok(!$( "#basic-collapsible-set-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be expanded after click"); $( "#basic-collapsible-set-test .ui-collapsible-heading-toggle" ).eq(0).click(); ok($( "#basic-collapsible-set-test .ui-collapsible" ).hasClass( "ui-collapsible-collapsed" ), "All collapsible should be collapsed"); start(); } ]); }); module( "Theming", {}); asyncTest( "Collapsible", 6, function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#collapsible-with-theming" ); }, function() { var collapsibles = $.mobile.activePage.find( ".ui-collapsible" ); ok( collapsibles.eq(0).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-a" ), "Heading of first collapsible should have class ui-btn-up-a"); ok( !collapsibles.eq(0).find( ".ui-collapsible-content" ).hasClass( "ui-btn-up-a" ), "Content of first collapsible should NOT have class ui-btn-up-a"); ok( collapsibles.eq(1).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-b" ), "Heading of second collapsible should have class ui-btn-up-b"); ok( collapsibles.eq(1).find( ".ui-collapsible-content" ).hasClass( "ui-body-b" ), "Content of second collapsible should have class ui-btn-up-b"); ok( collapsibles.eq(2).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-c" ), "Heading of third collapsible should have class ui-btn-up-c"); ok( collapsibles.eq(2).find( ".ui-collapsible-content" ).hasClass( "ui-body-c" ), "Content of third collapsible should have class ui-btn-up-c"); start(); } ]); }); asyncTest( "Collapsible Set", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#collapsible-set-with-theming" ); }, function() { var collapsibles = $.mobile.activePage.find( ".ui-collapsible" ); ok( collapsibles.eq(0).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-a" ), "Heading of first collapsible should have class ui-btn-up-a"); ok( !collapsibles.eq(0).find( ".ui-collapsible-content" ).is( ".ui-body-a,.ui-body-b,.ui-body-c" ), "Content of first collapsible should NOT have class ui-btn-up-[a,b,c]"); ok( collapsibles.eq(0).find( ".ui-collapsible-content" ).hasClass( "ui-body-d" ), "Content of first collapsible should NOT have class ui-btn-up-d"); ok( collapsibles.eq(1).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-b" ), "Heading of second collapsible should have class ui-btn-up-b"); ok( !collapsibles.eq(1).find( ".ui-collapsible-content" ).is( ".ui-body-a,.ui-body-c,.ui-body-d" ), "Content of second collapsible should NOT have class ui-btn-up-[a,c,d]"); ok( collapsibles.eq(1).find( ".ui-collapsible-content" ).hasClass( "ui-body-b" ), "Content of second collapsible should have class ui-btn-up-b"); ok( collapsibles.eq(2).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-d" ), "Heading of third collapsible should have class ui-btn-up-d"); ok( !collapsibles.eq(2).find( ".ui-collapsible-content" ).is( ".ui-body-a,.ui-body-b,.ui-body-c" ), "Content of third collapsible should NOT have class ui-btn-up-[a,b,c]"); ok( collapsibles.eq(2).find( ".ui-collapsible-content" ).hasClass( "ui-body-d" ), "Content of third collapsible should have class ui-btn-up-d"); ok( !collapsibles.eq(2).find( ".ui-collapsible-content" ).hasClass( "ui-collapsible-content-collapsed" ), "Content of third collapsible should NOT have class ui-collapsible-content-collapsed"); ok( collapsibles.eq(3).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-d" ), "Heading of fourth collapsible should have class ui-btn-up-d"); ok( !collapsibles.eq(3).find( ".ui-collapsible-content" ).is( ".ui-body-a,.ui-body-b,.ui-body-c" ), "Content of fourth collapsible should NOT have class ui-btn-up-[a,b,c]"); ok( collapsibles.eq(3).find( ".ui-collapsible-content" ).hasClass( "ui-body-d" ), "Content of fourth collapsible should have class ui-btn-up-d"); start(); } ]); }); })( jQuery );
JavaScript
// load testswarm agent (function() { var url = window.location.search; url = decodeURIComponent( url.slice( url.indexOf("swarmURL=") + 9 ) ); if ( !url || url.indexOf("http") !== 0 ) { return; } document.write("<scr" + "ipt src='http://swarm.jquery.org/js/inject.js?" + (new Date).getTime() + "'></scr" + "ipt>"); })();
JavaScript
/* * mobile media unit tests */ (function($){ var cssFn = $.fn.css, widthFn = $.fn.width; // make sure original definitions are reset module('jquery.mobile.media.js', { setup: function(){ $(document).trigger('mobileinit.htmlclass'); }, teardown: function(){ $.fn.css = cssFn; $.fn.width = widthFn; } }); test( "media query check returns true when the position is absolute", function(){ $.fn.css = function(){ return "absolute"; }; same($.mobile.media("screen 1"), true); }); test( "media query check returns false when the position is not absolute", function(){ $.fn.css = function(){ return "not absolute"; }; same($.mobile.media("screen 2"), false); }); test( "media query check is cached", function(){ $.fn.css = function(){ return "absolute"; }; same($.mobile.media("screen 3"), true); $.fn.css = function(){ return "not absolute"; }; same($.mobile.media("screen 3"), true); }); })(jQuery);
JavaScript
/* * mobile page unit tests */ (function($){ var libName = 'jquery.mobile.page.sections.js', themedefault = $.mobile.page.prototype.options.theme, keepNative = $.mobile.page.prototype.options.keepNative; module(libName, { setup: function() { $.mobile.page.prototype.options.keepNative = keepNative; } }); var eventStack = [], etargets = [], cEvents=[], cTargets=[]; $( document ).bind( "pagebeforecreate pagecreate", function( e ){ eventStack.push( e.type ); etargets.push( e.target ); }); $("#c").live( "pagebeforecreate", function( e ){ cEvents.push( e.type ); cTargets.push( e.target ); return false; }); test( "pagecreate event fires when page is created", function(){ ok( eventStack[0] === "pagecreate" || eventStack[1] === "pagecreate" ); }); test( "pagebeforecreate event fires when page is created", function(){ ok( eventStack[0] === "pagebeforecreate" || eventStack[1] === "pagebeforecreate" ); }); test( "pagebeforecreate fires before pagecreate", function(){ ok( eventStack[0] === "pagebeforecreate" ); }); test( "target of pagebeforecreate event was div #a", function(){ ok( $( etargets[0] ).is("#a") ); }); test( "target of pagecreate event was div #a" , function(){ ok( $( etargets[0] ).is("#a") ); }); test( "page element has ui-page class" , function(){ ok( $( "#a" ).hasClass( "ui-page" ) ); }); test( "page element has default body theme when not overidden" , function(){ ok( $( "#a" ).hasClass( "ui-body-" + themedefault ) ); }); test( "B page has non-default theme matching its data-theme attr" , function(){ $( "#b" ).page(); var btheme = $( "#b" ).jqmData( "theme" ); ok( $( "#b" ).hasClass( "ui-body-" + btheme ) ); }); test( "Binding to pagebeforecreate and returning false prevents pagecreate event from firing" , function(){ $("#c").page(); ok( cEvents[0] === "pagebeforecreate" ); ok( !cTargets[1] ); }); test( "Binding to pagebeforecreate and returning false prevents classes from being applied to page" , function(){ ok( !$( "#b" ).hasClass( "ui-body-" + themedefault ) ); ok( !$( "#b" ).hasClass( "ui-page" ) ); }); test( "keepNativeSelector returns the default where keepNative is not different", function() { var pageProto = $.mobile.page.prototype; pageProto.options.keepNative = pageProto.options.keepNativeDefault; same(pageProto.keepNativeSelector(), pageProto.options.keepNativeDefault); }); test( "keepNativeSelector returns the default where keepNative is empty, undefined, whitespace", function() { var pageProto = $.mobile.page.prototype; pageProto.options.keepNative = ""; same(pageProto.keepNativeSelector(), pageProto.options.keepNativeDefault); pageProto.options.keepNative = undefined; same(pageProto.keepNativeSelector(), pageProto.options.keepNativeDefault); pageProto.options.keepNative = " "; same(pageProto.keepNativeSelector(), pageProto.options.keepNativeDefault); }); test( "keepNativeSelector returns a selector joined with the default", function() { var pageProto = $.mobile.page.prototype; pageProto.options.keepNative = "foo, bar"; same(pageProto.keepNativeSelector(), "foo, bar, " + pageProto.options.keepNativeDefault); }); })(jQuery);
JavaScript
$(function() { var Runner = function( ) { var self = this; $.extend( self, { frame: window.frames[ "testFrame" ], testTimeout: 3 * 60 * 1000, $frameElem: $( "#testFrame" ), assertionResultPrefix: "assertion result for test:", onTimeout: QUnit.start, onFrameLoad: function() { // establish a timeout for a given suite in case of async tests hanging self.testTimer = setTimeout( self.onTimeout, self.testTimeout ); // it might be a redirect with query params for push state // tests skip this call and expect another if( !self.frame.QUnit ) { self.$frameElem.one( "load", self.onFrameLoad ); return; } // when the QUnit object reports done in the iframe // run the onFrameDone method self.frame.QUnit.done = self.onFrameDone; self.frame.QUnit.testDone = self.onTestDone; }, onTestDone: function( result ) { QUnit.ok( !(result.failed > 0), result.name ); self.recordAssertions( result.total - result.failed, result.name ); }, onFrameDone: function( failed, passed, total, runtime ){ // make sure we don't time out the tests clearTimeout( self.testTimer ); // TODO decipher actual cause of multiple test results firing twice // clear the done call to prevent early completion of other test cases self.frame.QUnit.done = $.noop; self.frame.QUnit.testDone = $.noop; // hide the extra assertions made to propogate the count // to the suite level test self.hideAssertionResults(); // continue on to the next suite QUnit.start(); }, recordAssertions: function( count, parentTest ) { for( var i = 0; i < count; i++ ) { ok( true, self.assertionResultPrefix + parentTest ); } }, hideAssertionResults: function() { $( "li:not([id]):contains('" + self.assertionResultPrefix + "')" ).hide(); }, exec: function( data ) { var template = self.$frameElem.attr( "data-src" ); $.each( data.testPages, function(i, dir) { QUnit.asyncTest( dir, function() { self.dir = dir; self.$frameElem.one( "load", self.onFrameLoad ); self.$frameElem.attr( "src", template.replace("{{testdir}}", dir) ); }); }); // having defined all suite level tests let QUnit run QUnit.start(); } }); }; // prevent qunit from starting the test suite until all tests are defined QUnit.begin = function( ) { this.config.autostart = false; }; // get the test directories $.get( "ls.php", (new Runner()).exec ); });
JavaScript
/* * mobile init tests */ (function($){ test( "page element is generated when not present in initial markup", function(){ ok( $( ".ui-page" ).length, 1 ); }); })(jQuery);
JavaScript
/* * mobile init tests */ (function($){ var mobilePage = undefined, libName = 'jquery.mobile.init.js', coreLib = 'jquery.mobile.core.js', extendFn = $.extend, setGradeA = function(value) { $.mobile.gradeA = function(){ return value; }; }, reloadCoreNSandInit = function(){ $.testHelper.reloadLib(coreLib); $.testHelper.reloadLib("jquery.setNamespace.js"); $.testHelper.reloadLib(libName); }; module(libName, { setup: function(){ // NOTE reset for gradeA tests $('html').removeClass('ui-mobile'); // TODO add post reload callback $('.ui-loader').remove(); }, teardown: function(){ $.extend = extendFn; // NOTE reset for showPageLoadingMsg/hidePageLoadingMsg tests $('.ui-loader').remove(); // clear the classes added by reloading the init $("html").attr('class', ''); } }); // NOTE important to use $.fn.one here to make sure library reloads don't fire // the event before the test check below $(document).one("mobileinit", function(){ mobilePage = $.mobile.page; }); // NOTE for the following two tests see index html for the binding test( "mobile.page is available when mobile init is fired", function(){ ok( mobilePage !== undefined, "$.mobile.page is defined" ); }); $.testHelper.excludeFileProtocol(function(){ asyncTest( "loading the init library triggers mobilinit on the document", function(){ var initFired = false; expect( 1 ); $(window.document).one('mobileinit', function(event){ initFired = true; }); $.testHelper.reloadLib(libName); setTimeout(function(){ ok(initFired, "init fired"); start(); }, 1000); }); test( "enhancments are skipped when the browser is not grade A", function(){ setGradeA(false); $.testHelper.reloadLib(libName); //NOTE easiest way to check for enhancements, not the most obvious ok(!$("html").hasClass("ui-mobile"), "html elem doesn't have class ui-mobile"); }); test( "enhancments are added when the browser is grade A", function(){ setGradeA(true); $.testHelper.reloadLib(libName); ok($("html").hasClass("ui-mobile"), "html elem has class mobile"); }); asyncTest( "useFastClick is configurable via mobileinit", function(){ $(document).one( "mobileinit", function(){ $.mobile.useFastClick = false; start(); }); $.testHelper.reloadLib(libName); same( $.mobile.useFastClick, false , "fast click is set to false after init" ); $.mobile.useFastClick = true; }); var findFirstPage = function() { return $(":jqmData(role='page')").first(); }; test( "active page and start page should be set to the fist page in the selected set", function(){ expect( 2 ); $.testHelper.reloadLib(libName); var firstPage = findFirstPage(); same($.mobile.firstPage[0], firstPage[0]); same($.mobile.activePage[0], firstPage[0]); }); test( "mobile viewport class is defined on the first page's parent", function(){ expect( 1 ); $.testHelper.reloadLib(libName); var firstPage = findFirstPage(); ok(firstPage.parent().hasClass("ui-mobile-viewport"), "first page has viewport"); }); test( "mobile page container is the first page's parent", function(){ expect( 1 ); $.testHelper.reloadLib(libName); var firstPage = findFirstPage(); same($.mobile.pageContainer[0], firstPage.parent()[0]); }); asyncTest( "hashchange triggered on document ready with single argument: true", function(){ $.testHelper.sequence([ function(){ location.hash = "#foo"; }, // delay the bind until the first hashchange function(){ $(window).one("hashchange", function(ev, arg){ same(arg, true); start(); }); }, function(){ $.testHelper.reloadLib(libName); } ], 1000); }); test( "pages without a data-url attribute have it set to their id", function(){ same($("#foo").jqmData('url'), "foo"); }); test( "pages with a data-url attribute are left with the original value", function(){ same($("#bar").jqmData('url'), "bak"); }); asyncTest( "showPageLoadingMsg doesn't add the dialog to the page when loading message is false", function(){ expect( 1 ); $.mobile.loadingMessage = false; $.mobile.showPageLoadingMsg(); setTimeout(function(){ ok(!$(".ui-loader").length, "no ui-loader element"); start(); }, 500); }); asyncTest( "hidePageLoadingMsg doesn't add the dialog to the page when loading message is false", function(){ expect( 1 ); $.mobile.loadingMessage = true; $.mobile.hidePageLoadingMsg(); setTimeout(function(){ same($(".ui-loading").length, 0, "page should not be in the loading state"); start(); }, 500); }); asyncTest( "showPageLoadingMsg adds the dialog to the page when loadingMessage is true", function(){ expect( 1 ); $.mobile.loadingMessage = true; $.mobile.showPageLoadingMsg(); setTimeout(function(){ same($(".ui-loading").length, 1, "page should be in the loading state"); start(); }, 500); }); asyncTest( "page loading should contain default loading message", function(){ expect( 1 ); reloadCoreNSandInit(); $.mobile.showPageLoadingMsg(); setTimeout(function(){ same($(".ui-loader h1").text(), "loading"); start(); }, 500); }); asyncTest( "page loading should contain custom loading message", function(){ $.mobile.loadingMessage = "foo"; $.testHelper.reloadLib(libName); $.mobile.showPageLoadingMsg(); setTimeout(function(){ same($(".ui-loader h1").text(), "foo"); start(); }, 500); }); asyncTest( "page loading should contain custom loading message when set during runtime", function(){ $.mobile.loadingMessage = "bar"; $.mobile.showPageLoadingMsg(); setTimeout(function(){ same($(".ui-loader h1").text(), "bar"); start(); }, 500); }); // NOTE: the next two tests work on timeouts that assume a page will be created within 2 seconds // it'd be great to get these using a more reliable callback or event asyncTest( "page does auto-initialize at domready when autoinitialize option is true (default) ", function(){ $( "<div />", { "data-nstest-role": "page", "id": "autoinit-on" } ).prependTo( "body" ) $(document).one("mobileinit", function(){ $.mobile.autoInitializePage = true; }); location.hash = ""; reloadCoreNSandInit(); setTimeout(function(){ same( $( "#autoinit-on.ui-page" ).length, 1 ); start(); }, 2000); }); asyncTest( "page does not initialize at domready when autoinitialize option is false ", function(){ $(document).one("mobileinit", function(){ $.mobile.autoInitializePage = false; }); $( "<div />", { "data-nstest-role": "page", "id": "autoinit-off" } ).prependTo( "body" ) location.hash = ""; reloadCoreNSandInit(); setTimeout(function(){ same( $( "#autoinit-off.ui-page" ).length, 0 ); $(document).bind("mobileinit", function(){ $.mobile.autoInitializePage = true; }); reloadCoreNSandInit(); start(); }, 2000); }); }); })(jQuery);
JavaScript
/* * mobile dialog unit tests */ (function($) { module( "jquery.mobile.dialog.js", { setup: function() { $.mobile.page.prototype.options.contentTheme = "d"; } }); asyncTest( "dialog hash is added when the dialog is opened and removed when closed", function() { expect( 2 ); $.testHelper.pageSequence([ function() { $.mobile.changePage( $( "#mypage" ) ); }, function() { //bring up the dialog $( "#foo-dialog-link" ).click(); }, function() { var fooDialog = $( "#foo-dialog" ); // make sure the dialog came up ok( /&ui-state=dialog/.test(location.hash), "ui-state=dialog =~ location.hash", "dialog open" ); // close the dialog $( ".ui-dialog" ).dialog( "close" ); }, function() { ok( !/&ui-state=dialog/.test(location.hash), "ui-state=dialog !~ location.hash" ); start(); } ]); }); asyncTest( "dialog element with no theming", function() { expect(4); $.testHelper.pageSequence([ function() { $.mobile.changePage( $( "#mypage" ) ); }, function() { //bring up the dialog $( "#link-a" ).click(); }, function() { var dialog = $( "#dialog-a" ); // Assert dialog theme inheritance (issue 1375): ok( dialog.hasClass( "ui-body-c" ), "Expected explicit theme ui-body-c" ); ok( dialog.find( ":jqmData(role=header)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected header to inherit from $.mobile.page.prototype.options.headerTheme" ); ok( dialog.find( ":jqmData(role=content)" ).hasClass( "ui-body-" + $.mobile.page.prototype.options.contentTheme ), "Expect content to inherit from $.mobile.page.prototype.options.contentTheme" ); ok( dialog.find( ":jqmData(role=footer)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected footer to inherit from $.mobile.page.prototype.options.footerTheme" ); start(); } ]); }); asyncTest( "dialog element with data-theme", function() { // Reset fallback theme for content $.mobile.page.prototype.options.contentTheme = null; expect(5); $.testHelper.pageSequence([ function() { $.mobile.changePage( $( "#mypage" ) ); }, function() { //bring up the dialog $( "#link-b" ).click(); }, function() { var dialog = $( "#dialog-b" ); // Assert dialog theme inheritance (issue 1375): ok( dialog.hasClass( "ui-body-e" ), "Expected explicit theme ui-body-e" ); ok( !dialog.hasClass( "ui-overlay-b" ), "Expected no theme ui-overlay-b" ); ok( dialog.find( ":jqmData(role=header)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected header to inherit from $.mobile.page.prototype.options.headerTheme" ); ok( dialog.find( ":jqmData(role=content)" ).hasClass( "ui-body-e" ), "Expect content to inherit from data-theme" ); ok( dialog.find( ":jqmData(role=footer)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected footer to inherit from $.mobile.page.prototype.options.footerTheme" ); start(); } ]); }); asyncTest( "dialog element with data-theme & data-overlay-theme", function() { expect(5); $.testHelper.pageSequence([ function() { $.mobile.changePage( $( "#mypage" ) ); }, function() { //bring up the dialog $( "#link-c" ).click(); }, function() { var dialog = $( "#dialog-c" ); // Assert dialog theme inheritance (issue 1375): ok( dialog.hasClass( "ui-body-e" ), "Expected explicit theme ui-body-e" ); ok( dialog.hasClass( "ui-overlay-b" ), "Expected explicit theme ui-overlay-b" ); ok( dialog.find( ":jqmData(role=header)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected header to inherit from $.mobile.page.prototype.options.headerTheme" ); ok( dialog.find( ":jqmData(role=content)" ).hasClass( "ui-body-" + $.mobile.page.prototype.options.contentTheme ), "Expect content to inherit from $.mobile.page.prototype.options.contentTheme" ); ok( dialog.find( ":jqmData(role=footer)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected footer to inherit from $.mobile.page.prototype.options.footerTheme" ); start(); } ]); }); })( jQuery );
JavaScript
//set namespace for unit test markp $( document ).bind( "mobileinit", function(){ $.mobile.ns = "nstest-"; });
JavaScript
/* * mobile core unit tests */ (function($){ var libName = "jquery.mobile.core.js", setGradeA = function(value, version) { $.support.mediaquery = value; $.mobile.browser.ie = version; }, extendFn = $.extend; module(libName, { setup: function(){ // NOTE reset for gradeA tests $('html').removeClass('ui-mobile'); // NOTE reset for pageLoading tests $('.ui-loader').remove(); }, teardown: function(){ $.extend = extendFn; } }); $.testHelper.excludeFileProtocol(function(){ test( "grade A browser either supports media queries or is IE 7+", function(){ setGradeA(false, 6); $.testHelper.reloadLib(libName); ok(!$.mobile.gradeA()); setGradeA(true, 8); $.testHelper.reloadLib(libName); ok($.mobile.gradeA()); }); }); function clearNSNormalizeDictionary() { var dict = $.mobile.nsNormalizeDict; for ( var prop in dict ) { delete dict[ prop ]; } } test( "$.mobile.nsNormalize works properly with namespace defined (test default)", function(){ // Start with a fresh namespace property cache, just in case // the previous test mucked with namespaces. clearNSNormalizeDictionary(); equal($.mobile.nsNormalize("foo"), "nstestFoo", "appends ns and initcaps"); equal($.mobile.nsNormalize("fooBar"), "nstestFooBar", "leaves capped strings intact"); equal($.mobile.nsNormalize("foo-bar"), "nstestFooBar", "changes dashed strings"); equal($.mobile.nsNormalize("foo-bar-bak"), "nstestFooBarBak", "changes multiple dashed strings"); // Reset the namespace property cache for the next test. clearNSNormalizeDictionary(); }); test( "$.mobile.nsNormalize works properly with an empty namespace", function(){ var realNs = $.mobile.ns; $.mobile.ns = ""; // Start with a fresh namespace property cache, just in case // the previous test mucked with namespaces. clearNSNormalizeDictionary(); equal($.mobile.nsNormalize("foo"), "foo", "leaves uncapped and undashed"); equal($.mobile.nsNormalize("fooBar"), "fooBar", "leaves capped strings intact"); equal($.mobile.nsNormalize("foo-bar"), "fooBar", "changes dashed strings"); equal($.mobile.nsNormalize("foo-bar-bak"), "fooBarBak", "changes multiple dashed strings"); $.mobile.ns = realNs; // Reset the namespace property cache for the next test. clearNSNormalizeDictionary(); }); //data tests test( "$.fn.jqmData and $.fn.jqmRemoveData methods are working properly", function(){ var data; same( $("body").jqmData("foo", true), $("body"), "setting data returns the element" ); same( $("body").jqmData("foo"), true, "getting data returns the right value" ); same( $("body").data($.mobile.nsNormalize("foo")), true, "data was set using namespace" ); same( $("body").jqmData("foo", undefined), true, "getting data still returns the value if there's an undefined second arg" ); data = $.extend( {}, $("body").data() ); delete data[ $.expando ]; //discard the expando for that test same( data , { "nstestFoo": true }, "passing .data() no arguments returns a hash with all set properties" ); same( $("body").jqmData(), undefined, "passing no arguments returns undefined" ); same( $("body").jqmData(undefined), undefined, "passing a single undefined argument returns undefined" ); same( $("body").jqmData(undefined, undefined), undefined, "passing 2 undefined arguments returns undefined" ); same( $("body").jqmRemoveData("foo"), $("body"), "jqmRemoveData returns the element" ); same( $("body").jqmData("foo"), undefined, "jqmRemoveData properly removes namespaced data" ); }); test( "$.jqmData and $.jqmRemoveData methods are working properly", function(){ same( $.jqmData(document.body, "foo", true), true, "setting data returns the value" ); same( $.jqmData(document.body, "foo"), true, "getting data returns the right value" ); same( $.data(document.body, $.mobile.nsNormalize("foo")), true, "data was set using namespace" ); same( $.jqmData(document.body, "foo", undefined), true, "getting data still returns the value if there's an undefined second arg" ); same( $.jqmData(document.body), undefined, "passing no arguments returns undefined" ); same( $.jqmData(document.body, undefined), undefined, "passing a single undefined argument returns undefined" ); same( $.jqmData(document.body, undefined, undefined), undefined, "passing 2 undefined arguments returns undefined" ); same( $.jqmRemoveData(document.body, "foo"), undefined, "jqmRemoveData returns the undefined value" ); same( $("body").jqmData("foo"), undefined, "jqmRemoveData properly removes namespaced data" ); }); test( "addDependents works properly", function() { same( $("#parent").jqmData('dependents'), undefined ); $( "#parent" ).addDependents( $("#dependent") ); same( $("#parent").jqmData('dependents').length, 1 ); }); test( "removeWithDependents removes the parent element and ", function(){ $( "#parent" ).addDependents( $("#dependent") ); same($( "#parent, #dependent" ).length, 2); $( "#parent" ).removeWithDependents(); same($( "#parent, #dependent" ).length, 0); }); test( "$.fn.getEncodedText should return the encoded value where $.fn.text doesn't", function() { same( $("#encoded").text(), "foo>"); same( $("#encoded").getEncodedText(), "foo&gt;"); same( $("#unencoded").getEncodedText(), "foo"); }); })(jQuery);
JavaScript
/* * mobile core unit tests */ (function($){ var libName = "jquery.mobile.core.js", scrollTimeout = 20, // TODO expose timing as an attribute scrollStartEnabledTimeout = 150; module(libName, { setup: function(){ $("<div id='scroll-testing' style='height: 1000px'></div>").appendTo("body"); }, teardown: function(){ $("#scroll-testing").remove(); } }); var scrollUp = function( pos ){ $(window).scrollTop(1000); ok($(window).scrollTop() > 0, $(window).scrollTop()); $.mobile.silentScroll(pos); }; asyncTest( "silent scroll scrolls the page to the top by default", function(){ scrollUp(); setTimeout(function(){ same($(window).scrollTop(), 0); start(); }, scrollTimeout); }); asyncTest( "silent scroll scrolls the page to the passed y position", function(){ var pos = 10; scrollUp(pos); setTimeout(function(){ same($(window).scrollTop(), pos); start(); }, scrollTimeout); }); test( "silent scroll is async", function(){ scrollUp(); ok($(window).scrollTop() != 0, "scrolltop position should not be zero"); start(); }); asyncTest( "scrolling marks scrollstart as disabled for 150 ms", function(){ $.event.special.scrollstart.enabled = true; scrollUp(); ok(!$.event.special.scrollstart.enabled); setTimeout(function(){ ok($.event.special.scrollstart.enabled); start(); }, scrollStartEnabledTimeout); }); //TODO test that silentScroll is called on window load })(jQuery);
JavaScript
/* * mobile support unit tests */ $.testHelper.excludeFileProtocol(function(){ var prependToFn = $.fn.prependTo, libName = "jquery.mobile.support.js"; module(libName, { teardown: function(){ //NOTE undo any mocking $.fn.prependTo = prependToFn; } }); // NOTE following two tests have debatable value as they only // prevent property name changes and improper attribute checks test( "detects functionality from basic affirmative properties and attributes", function(){ // TODO expose properties for less brittle tests $.extend(window, { WebKitTransitionEvent: true, orientation: true, onorientationchange: true }); document.ontouchend = true; window.history.pushState = function(){}; window.history.replaceState = function(){}; $.mobile.media = function(){ return true; }; $.testHelper.reloadLib(libName); ok($.support.orientation); ok($.support.touch); ok($.support.cssTransitions); ok($.support.pushState); ok($.support.mediaquery); }); test( "detects functionality from basic negative properties and attributes (where possible)", function(){ delete window["orientation"]; delete document["ontouchend"]; $.testHelper.reloadLib(libName); ok(!$.support.orientation); ok(!$.support.touch); }); // NOTE mocks prependTo to simulate base href updates or lack thereof var mockBaseCheck = function( url ){ var prependToFn = $.fn.prependTo; $.fn.prependTo = function( selector ){ var result = prependToFn.call(this, selector); if(this[0].href && this[0].href.indexOf("testurl") != -1) result = [{href: url}]; return result; }; }; test( "detects dynamic base tag when new base element added and base href updates", function(){ mockBaseCheck(location.protocol + '//' + location.host + location.pathname + "ui-dir/"); $.testHelper.reloadLib(libName); ok($.support.dynamicBaseTag); }); test( "detects no dynamic base tag when new base element added and base href unchanged", function(){ mockBaseCheck('testurl'); $.testHelper.reloadLib(libName); ok(!$.support.dynamicBaseTag); }); test( "jQM's IE browser check properly detects IE versions", function(){ $.testHelper.reloadLib(libName); //here we're just comparing our version to what the conditional compilation finds var ie = !!$.browser.msie, //get a boolean version = parseInt( $.browser.version, 10), jqmdetectedver = $.mobile.browser.ie; if( ie ){ same(version, jqmdetectedver, "It's IE and the version is correct"); } else{ same(ie, jqmdetectedver, "It's not IE"); } }); //TODO propExists testing, refactor propExists into mockable method //TODO scrollTop testing, refactor scrollTop logic into mockable method });
JavaScript
/* * mobile navigation unit tests */ (function($){ var siteDirectory = location.pathname.replace(/[^/]+$/, ""); module('jquery.mobile.navigation.js', { setup: function(){ if ( location.hash ) { stop(); $(document).one("pagechange", function() { start(); } ); location.hash = ""; } } }); test( "path.get method is working properly", function(){ window.location.hash = "foo"; same($.mobile.path.get(), "foo", "get method returns location.hash minus hash character"); same($.mobile.path.get( "#foo/bar/baz.html" ), "foo/bar/", "get method with hash arg returns path with no filename or hash prefix"); same($.mobile.path.get( "#foo/bar/baz.html/" ), "foo/bar/baz.html/", "last segment of hash is retained if followed by a trailing slash"); }); test( "path.isPath method is working properly", function(){ ok(!$.mobile.path.isPath('bar'), "anything without a slash is not a path"); ok($.mobile.path.isPath('bar/'), "anything with a slash is a path"); ok($.mobile.path.isPath('/bar'), "anything with a slash is a path"); ok($.mobile.path.isPath('a/r'), "anything with a slash is a path"); ok($.mobile.path.isPath('/'), "anything with a slash is a path"); }); test( "path.getFilePath method is working properly", function(){ same($.mobile.path.getFilePath("foo.html" + "&" + $.mobile.subPageUrlKey ), "foo.html", "returns path without sub page key"); }); test( "path.set method is working properly", function(){ $.mobile.urlHistory.ignoreNextHashChange = false; $.mobile.path.set("foo"); same("foo", window.location.hash.replace(/^#/,""), "sets location.hash properly"); }); test( "path.makeUrlAbsolute is working properly", function(){ var mua = $.mobile.path.makeUrlAbsolute, p1 = "http://jqm.com/", p2 = "http://jqm.com/?foo=1&bar=2", p3 = "http://jqm.com/#spaz", p4 = "http://jqm.com/?foo=1&bar=2#spaz", p5 = "http://jqm.com/test.php", p6 = "http://jqm.com/test.php?foo=1&bar=2", p7 = "http://jqm.com/test.php#spaz", p8 = "http://jqm.com/test.php?foo=1&bar=2#spaz", p9 = "http://jqm.com/dir1/dir2/", p10 = "http://jqm.com/dir1/dir2/?foo=1&bar=2", p11 = "http://jqm.com/dir1/dir2/#spaz", p12 = "http://jqm.com/dir1/dir2/?foo=1&bar=2#spaz", p13 = "http://jqm.com/dir1/dir2/test.php", p14 = "http://jqm.com/dir1/dir2/test.php?foo=1&bar=2", p15 = "http://jqm.com/dir1/dir2/test.php#spaz", p16 = "http://jqm.com/dir1/dir2/test.php?foo=1&bar=2#spaz"; // Test URL conversion against an absolute URL to the site root. // directory tests same( mua( "http://jqm.com/", p1 ), "http://jqm.com/", "absolute root - absolute root" ); same( mua( "//jqm.com/", p1 ), "http://jqm.com/", "protocol relative root - absolute root" ); same( mua( "/", p1 ), "http://jqm.com/", "site relative root - absolute root" ); same( mua( "http://jqm.com/?foo=1&bar=2", p1 ), "http://jqm.com/?foo=1&bar=2", "absolute root with query - absolute root" ); same( mua( "//jqm.com/?foo=1&bar=2", p1 ), "http://jqm.com/?foo=1&bar=2", "protocol relative root with query - absolute root" ); same( mua( "/?foo=1&bar=2", p1 ), "http://jqm.com/?foo=1&bar=2", "site relative root with query - absolute root" ); same( mua( "?foo=1&bar=2", p1 ), "http://jqm.com/?foo=1&bar=2", "query relative - absolute root" ); same( mua( "http://jqm.com/#spaz", p1 ), "http://jqm.com/#spaz", "absolute root with fragment - absolute root" ); same( mua( "//jqm.com/#spaz", p1 ), "http://jqm.com/#spaz", "protocol relative root with fragment - absolute root" ); same( mua( "/#spaz", p1 ), "http://jqm.com/#spaz", "site relative root with fragment - absolute root" ); same( mua( "#spaz", p1 ), "http://jqm.com/#spaz", "fragment relative - absolute root" ); same( mua( "http://jqm.com/?foo=1&bar=2#spaz", p1 ), "http://jqm.com/?foo=1&bar=2#spaz", "absolute root with query and fragment - absolute root" ); same( mua( "//jqm.com/?foo=1&bar=2#spaz", p1 ), "http://jqm.com/?foo=1&bar=2#spaz", "protocol relative root with query and fragment - absolute root" ); same( mua( "/?foo=1&bar=2#spaz", p1 ), "http://jqm.com/?foo=1&bar=2#spaz", "site relative root with query and fragment - absolute root" ); same( mua( "?foo=1&bar=2#spaz", p1 ), "http://jqm.com/?foo=1&bar=2#spaz", "query relative and fragment - absolute root" ); // file tests same( mua( "http://jqm.com/test.php", p1 ), "http://jqm.com/test.php", "absolute file at root - absolute root" ); same( mua( "//jqm.com/test.php", p1 ), "http://jqm.com/test.php", "protocol relative file at root - absolute root" ); same( mua( "/test.php", p1 ), "http://jqm.com/test.php", "site relative file at root - absolute root" ); same( mua( "test.php", p1 ), "http://jqm.com/test.php", "document relative file at root - absolute root" ); same( mua( "http://jqm.com/test.php?foo=1&bar=2", p1 ), "http://jqm.com/test.php?foo=1&bar=2", "absolute file at root with query - absolute root" ); same( mua( "//jqm.com/test.php?foo=1&bar=2", p1 ), "http://jqm.com/test.php?foo=1&bar=2", "protocol relative file at root with query - absolute root" ); same( mua( "/test.php?foo=1&bar=2", p1 ), "http://jqm.com/test.php?foo=1&bar=2", "site relative file at root with query - absolute root" ); same( mua( "test.php?foo=1&bar=2", p1 ), "http://jqm.com/test.php?foo=1&bar=2", "document relative file at root with query - absolute root" ); same( mua( "http://jqm.com/test.php#spaz", p1 ), "http://jqm.com/test.php#spaz", "absolute file at root with fragment - absolute root" ); same( mua( "//jqm.com/test.php#spaz", p1 ), "http://jqm.com/test.php#spaz", "protocol relative file at root with fragment - absolute root" ); same( mua( "/test.php#spaz", p1 ), "http://jqm.com/test.php#spaz", "site relative file at root with fragment - absolute root" ); same( mua( "test.php#spaz", p1 ), "http://jqm.com/test.php#spaz", "file at root with fragment - absolute root" ); same( mua( "http://jqm.com/test.php?foo=1&bar=2#spaz", p1 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "absolute file at root with query and fragment - absolute root" ); same( mua( "//jqm.com/test.php?foo=1&bar=2#spaz", p1 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "protocol relative file at root with query and fragment - absolute root" ); same( mua( "/test.php?foo=1&bar=2#spaz", p1 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "site relative file at root with query and fragment - absolute root" ); same( mua( "test.php?foo=1&bar=2#spaz", p1 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "query relative file at root fragment - absolute root" ); // Test URL conversion against an absolute URL to a file at the site root. same( mua( "http://jqm.com/", p5 ), "http://jqm.com/", "absolute root - absolute root" ); same( mua( "//jqm.com/", p5 ), "http://jqm.com/", "protocol relative root - absolute root" ); same( mua( "/", p5 ), "http://jqm.com/", "site relative root - absolute root" ); same( mua( "http://jqm.com/?foo=1&bar=2", p5 ), "http://jqm.com/?foo=1&bar=2", "absolute root with query - absolute root" ); same( mua( "//jqm.com/?foo=1&bar=2", p5 ), "http://jqm.com/?foo=1&bar=2", "protocol relative root with query - absolute root" ); same( mua( "/?foo=1&bar=2", p5 ), "http://jqm.com/?foo=1&bar=2", "site relative root with query - absolute root" ); same( mua( "?foo=1&bar=2", p5 ), "http://jqm.com/test.php?foo=1&bar=2", "query relative - absolute root" ); same( mua( "http://jqm.com/#spaz", p5 ), "http://jqm.com/#spaz", "absolute root with fragment - absolute root" ); same( mua( "//jqm.com/#spaz", p5 ), "http://jqm.com/#spaz", "protocol relative root with fragment - absolute root" ); same( mua( "/#spaz", p5 ), "http://jqm.com/#spaz", "site relative root with fragment - absolute root" ); same( mua( "#spaz", p5 ), "http://jqm.com/test.php#spaz", "fragment relative - absolute root" ); same( mua( "http://jqm.com/?foo=1&bar=2#spaz", p5 ), "http://jqm.com/?foo=1&bar=2#spaz", "absolute root with query and fragment - absolute root" ); same( mua( "//jqm.com/?foo=1&bar=2#spaz", p5 ), "http://jqm.com/?foo=1&bar=2#spaz", "protocol relative root with query and fragment - absolute root" ); same( mua( "/?foo=1&bar=2#spaz", p5 ), "http://jqm.com/?foo=1&bar=2#spaz", "site relative root with query and fragment - absolute root" ); same( mua( "?foo=1&bar=2#spaz", p5 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "query relative and fragment - absolute root" ); }); // https://github.com/jquery/jquery-mobile/issues/2362 test( "ipv6 host support", function(){ // http://www.ietf.org/rfc/rfc2732.txt ipv6 examples for tests // most definitely not comprehensive var ipv6_1 = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html", ipv6_2 = "http://[1080:0:0:0:8:800:200C:417A]/index.html", ipv6_3 = "http://[3ffe:2a00:100:7031::1]", ipv6_4 = "http://[1080::8:800:200C:417A]/foo", ipv6_5 = "http://[::192.9.5.5]/ipng", ipv6_6 = "http://[::FFFF:129.144.52.38]:80/index.html", ipv6_7 = "http://[2010:836B:4179::836B:4179]", fromIssue = "http://[3fff:cafe:babe::]:443/foo"; same( $.mobile.path.parseUrl(ipv6_1).host, "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80"); same( $.mobile.path.parseUrl(ipv6_1).hostname, "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]"); same( $.mobile.path.parseUrl(ipv6_2).host, "[1080:0:0:0:8:800:200C:417A]"); same( $.mobile.path.parseUrl(ipv6_3).host, "[3ffe:2a00:100:7031::1]"); same( $.mobile.path.parseUrl(ipv6_4).host, "[1080::8:800:200C:417A]"); same( $.mobile.path.parseUrl(ipv6_5).host, "[::192.9.5.5]"); same( $.mobile.path.parseUrl(ipv6_6).host, "[::FFFF:129.144.52.38]:80"); same( $.mobile.path.parseUrl(ipv6_6).hostname, "[::FFFF:129.144.52.38]"); same( $.mobile.path.parseUrl(ipv6_7).host, "[2010:836B:4179::836B:4179]"); same( $.mobile.path.parseUrl(fromIssue).host, "[3fff:cafe:babe::]:443"); same( $.mobile.path.parseUrl(fromIssue).hostname, "[3fff:cafe:babe::]"); }); test( "path.clean is working properly", function(){ var localroot = location.protocol + "//" + location.host + location.pathname, remoteroot = "http://google.com/", fakepath = "#foo/bar/baz.html", pathWithParam = localroot + "bar?baz=" + localroot, localpath = localroot + fakepath, remotepath = remoteroot + fakepath; same( $.mobile.path.clean( localpath ), location.pathname + fakepath, "removes location protocol, host, and portfrom same-domain path"); same( $.mobile.path.clean( remotepath ), remotepath, "does nothing to an external domain path"); same( $.mobile.path.clean( pathWithParam ), location.pathname + "bar?baz=" + localroot, "doesn't remove params with localroot value"); }); test( "path.stripHash is working properly", function(){ same( $.mobile.path.stripHash( "#bar" ), "bar", "returns a hash without the # prefix"); }); test( "path.hasProtocol is working properly", function(){ same( $.mobile.path.hasProtocol( "tel:5559999" ), true, "value in tel protocol format has protocol" ); same( $.mobile.path.hasProtocol( location.href ), true, "location href has protocol" ); same( $.mobile.path.hasProtocol( "foo/bar/baz.html" ), false, "simple directory path has no protocol" ); same( $.mobile.path.hasProtocol( "file://foo/bar/baz.html" ), true, "simple directory path with file:// has protocol" ); }); test( "path.isRelativeUrl is working properly", function(){ same( $.mobile.path.isRelativeUrl("http://company.com/"), false, "absolute url is not relative" ); same( $.mobile.path.isRelativeUrl("//company.com/"), true, "protocol relative url is relative" ); same( $.mobile.path.isRelativeUrl("/"), true, "site relative url is relative" ); same( $.mobile.path.isRelativeUrl("http://company.com/test.php"), false, "absolute url is not relative" ); same( $.mobile.path.isRelativeUrl("//company.com/test.php"), true, "protocol relative url is relative" ); same( $.mobile.path.isRelativeUrl("/test.php"), true, "site relative url is relative" ); same( $.mobile.path.isRelativeUrl("test.php"), true, "document relative url is relative" ); same( $.mobile.path.isRelativeUrl("http://company.com/dir1/dir2/test.php?foo=1&bar=2#frag"), false, "absolute url is not relative" ); same( $.mobile.path.isRelativeUrl("//company.com/dir1/dir2/test.php?foo=1&bar=2#frag"), true, "protocol relative url is relative" ); same( $.mobile.path.isRelativeUrl("/dir1/dir2/test.php?foo=1&bar=2#frag"), true, "site relative url is relative" ); same( $.mobile.path.isRelativeUrl("dir1/dir2/test.php?foo=1&bar=2#frag"), true, "document relative path url is relative" ); same( $.mobile.path.isRelativeUrl("test.php?foo=1&bar=2#frag"), true, "document relative file url is relative" ); same( $.mobile.path.isRelativeUrl("?foo=1&bar=2#frag"), true, "query relative url is relative" ); same( $.mobile.path.isRelativeUrl("#frag"), true, "fragments are relative" ); }); test( "path.isExternal is working properly", function(){ same( $.mobile.path.isExternal( location.href ), false, "same domain is not external" ); same( $.mobile.path.isExternal( "http://example.com" ), true, "example.com is external" ); same($.mobile.path.isExternal("mailto:"), true, "mailto protocol"); same($.mobile.path.isExternal("http://foo.com"), true, "http protocol"); same($.mobile.path.isExternal("http://www.foo.com"), true, "http protocol with www"); same($.mobile.path.isExternal("tel:16178675309"), true, "tel protocol"); same($.mobile.path.isExternal("foo.html"), false, "filename"); same($.mobile.path.isExternal("foo/foo/foo.html"), false, "file path"); same($.mobile.path.isExternal("../../index.html"), false, "relative parent path"); same($.mobile.path.isExternal("/foo"), false, "root-relative path"); same($.mobile.path.isExternal("foo"), false, "simple string"); same($.mobile.path.isExternal("#foo"), false, "local id reference"); }); test( "path.cleanHash", function(){ same( $.mobile.path.cleanHash( "#anything/atall?akjfdjjf" ), "anything/atall", "removes query param"); same( $.mobile.path.cleanHash( "#nothing/atall" ), "nothing/atall", "removes query param"); }); })(jQuery);
JavaScript
/* * mobile navigation path unit tests */ (function($){ var url = $.mobile.path.parseUrl( location.href ), home = location.href.replace( url.domain, "" ); var testPageLoad = function(testPageAnchorSelector, expectedTextValue){ expect( 2 ); $.testHelper.pageSequence([ function(){ // reset before each test, all tests expect original page // for relative urls $.testHelper.openPage( "#" + home); }, // open our test page function(){ $.testHelper.openPage("#pathing-tests"); }, // navigate to the linked page function(){ var page = $.mobile.activePage; // check that the reset page isn't still open equal("", page.find(".reset-value").text()); //click he test page link to execute the path page.find("a" + testPageAnchorSelector).click(); }, // verify that the page has changed and the expected text value is present function(){ same($.mobile.activePage.find(".test-value").text(), expectedTextValue); start(); } ]); }; // all of these alterations assume location.pathname will be a directory // this is required to prevent the tests breaking in a subdirectory // TODO could potentially be fragile since the tests could be running while // the urls are being updated $(function(){ $("a.site-rel").each(function(i, elem){ var $elem = $(elem); $elem.attr("href", location.pathname + $(elem).attr("href")); }); $('a.protocol-rel').each(function(i, elem){ var $elem = $(elem); $elem.attr("href", "//" + location.host + location.pathname + $(elem).attr("href")); }); $('a.absolute').each(function(i, elem){ var $elem = $(elem); $elem.attr("href", location.protocol + "//" + location.host + location.pathname + $(elem).attr("href")); }); }); //Doc relative tests module("document relative paths"); asyncTest( "file reference no nesting", function(){ testPageLoad("#doc-rel-test-one", "doc rel test one"); }); asyncTest( "file reference with nesting", function(){ testPageLoad("#doc-rel-test-two", "doc rel test two"); }); asyncTest( "file reference with double nesting", function(){ testPageLoad("#doc-rel-test-three", "doc rel test three"); }); asyncTest( "dir refrence with nesting", function(){ testPageLoad("#doc-rel-test-four", "doc rel test four"); }); asyncTest( "file refrence with parent dir", function(){ testPageLoad("#doc-rel-test-five", "doc rel test five"); }); asyncTest( "dir refrence with parent dir", function(){ testPageLoad("#doc-rel-test-six", "doc rel test six"); }); // Site relative tests // NOTE does not test root path or non nested references module("site relative paths"); asyncTest( "file reference no nesting", function(){ testPageLoad("#site-rel-test-one", "doc rel test one"); }); asyncTest( "file reference with nesting", function(){ testPageLoad("#site-rel-test-two", "doc rel test two"); }); asyncTest( "file reference with double nesting", function(){ testPageLoad("#site-rel-test-three", "doc rel test three"); }); asyncTest( "dir refrence with nesting", function(){ testPageLoad("#site-rel-test-four", "doc rel test four"); }); asyncTest( "file refrence with parent dir", function(){ testPageLoad("#site-rel-test-five", "doc rel test five"); }); asyncTest( "dir refrence with parent dir", function(){ testPageLoad("#site-rel-test-six", "doc rel test six"); }); // Protocol relative tests // NOTE does not test root path or non nested references module("protocol relative paths"); asyncTest( "file reference no nesting", function(){ testPageLoad("#protocol-rel-test-one", "doc rel test one"); }); asyncTest( "file reference with nesting", function(){ testPageLoad("#protocol-rel-test-two", "doc rel test two"); }); asyncTest( "file reference with double nesting", function(){ testPageLoad("#protocol-rel-test-three", "doc rel test three"); }); asyncTest( "dir refrence with nesting", function(){ testPageLoad("#protocol-rel-test-four", "doc rel test four"); }); asyncTest( "file refrence with parent dir", function(){ testPageLoad("#protocol-rel-test-five", "doc rel test five"); }); asyncTest( "dir refrence with parent dir", function(){ testPageLoad("#protocol-rel-test-six", "doc rel test six"); }); // absolute tests // NOTE does not test root path or non nested references module("abolute paths"); asyncTest( "file reference no nesting", function(){ testPageLoad("#absolute-test-one", "doc rel test one"); }); asyncTest( "file reference with nesting", function(){ testPageLoad("#absolute-test-two", "doc rel test two"); }); asyncTest( "file reference with double nesting", function(){ testPageLoad("#absolute-test-three", "doc rel test three"); }); asyncTest( "dir refrence with nesting", function(){ testPageLoad("#absolute-test-four", "doc rel test four"); }); asyncTest( "file refrence with parent dir", function(){ testPageLoad("#absolute-test-five", "doc rel test five"); }); asyncTest( "dir refrence with parent dir", function(){ testPageLoad("#absolute-test-six", "doc rel test six"); }); })(jQuery);
JavaScript
(function($) { asyncTest( "dialog ui-state should be part of the hash", function(){ $.testHelper.sequence([ function() { // open the test page $.mobile.activePage.find( "a" ).click(); }, function() { // verify that the hash contains the dialogHashKey ok( location.hash.search($.mobile.dialogHashKey) >= 0 ); start(); } ]); }); })(jQuery);
JavaScript
/* * mobile navigation base tag unit tests */ (function($){ var baseDir = $.mobile.path.parseUrl($("base").attr("href")).directory, contentDir = $.mobile.path.makePathAbsolute("../content/", baseDir); module('jquery.mobile.navigation.js - base tag', { setup: function(){ if ( location.hash ) { stop(); $(document).one("pagechange", function() { start(); } ); location.hash = ""; } } }); asyncTest( "can navigate between internal and external pages", function(){ $.testHelper.pageSequence([ function(){ // Navigate from default internal page to another internal page. $.testHelper.openPage( "#internal-page-2" ); }, function(){ // Verify that we are on the 2nd internal page. $.testHelper.assertUrlLocation({ push: location.pathname + "#internal-page-2", hash: "internal-page-2", report: "navigate to internal page" }); // Navigate to a page that is in the base directory. Note that the application // document and this new page are *NOT* in the same directory. $("#internal-page-2 .bp1").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: baseDir + "base-page-1.html", report: "navigate from internal page to page in base directory" }); // Navigate to another page in the same directory as the current page. $("#base-page-1 .bp2").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: baseDir + "base-page-2.html", report: "navigate from base directory page to another base directory page" }); // Navigate to another page in a directory that is the sibling of the base. $("#base-page-2 .cp1").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-1.html", report: "navigate from base directory page to a page in a different directory hierarchy" }); // Navigate to another page in a directory that is the sibling of the base. $("#content-page-1 .cp2").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-2.html", report: "navigate to another page within the same non-base directory hierarchy" }); // Navigate to an internal page. $("#content-page-2 .ip1").click(); }, function(){ // Verify that we are on the expected page. // the hash based nav result (hash:) is dictate by the fact that #internal-page-1 // is the original root page element $.testHelper.assertUrlLocation({ hashOrPush: location.pathname + location.search, report: "navigate from a page in a non-base directory to an internal page" }); // Try calling changePage() directly with a relative path. $.mobile.changePage("base-page-1.html"); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: baseDir + "base-page-1.html", report: "call changePage() with a filename (no path)" }); // Try calling changePage() directly with a relative path. $.mobile.changePage("../content/content-page-1.html"); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-1.html", report: "call changePage() with a relative path containing up-level references" }); // Try calling changePage() with an id $.mobile.changePage("content-page-2.html"); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-2.html", report: "call changePage() with a relative path should resolve relative to current page" }); // test that an internal page works $("a.ip2").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hash: "internal-page-2", push: location.pathname + "#internal-page-2", report: "call changePage() with a page id" }); // Try calling changePage() with an id $.mobile.changePage("internal-page-1"); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hash: "internal-page-2", push: location.pathname + "#internal-page-2", report: "calling changePage() with a page id that is not prefixed with '#' should not change page" }); // Previous load should have failed and left us on internal-page-2. start(); } ]); }); asyncTest( "internal form with no action submits to document URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage( "#internal-no-action-form-page" ); }, function(){ $( "#internal-no-action-form-page form" ).eq( 0 ).submit(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: location.pathname + "?foo=1&bar=2", report: "hash should match document url and not base url" }); start(); } ]); }); asyncTest( "external page form with no action submits to external page URL", function(){ $.testHelper.pageSequence([ function(){ // Go to an external page that has a form. $("#internal-page-1 .cp1").click(); }, function(){ // Make sure we actually navigated to the external page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-1.html", report: "should be on content-page-1.html" }); // Now submit the form in the external page. $("#content-page-1 form").eq(0).submit(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-1.html?foo=1&bar=2", report: "hash should match page url and not document url" }); start(); }]); }); })(jQuery);
JavaScript
/* * mobile navigation unit tests */ (function($){ // TODO move siteDirectory over to the nav path helper var changePageFn = $.mobile.changePage, originalTitle = document.title, originalLinkBinding = $.mobile.linkBindingEnabled, siteDirectory = location.pathname.replace( /[^/]+$/, "" ), home = $.mobile.path.parseUrl(location.pathname).directory, navigateTestRoot = function(){ $.testHelper.openPage( "#" + location.pathname + location.search ); }; module('jquery.mobile.navigation.js', { setup: function(){ $.mobile.changePage = changePageFn; document.title = originalTitle; var pageReset = function( hash ) { hash = hash || ""; stop(); $(document).one( "pagechange", function() { start(); }); location.hash = "#" + hash; }; // force the page reset for hash based tests if ( location.hash && !$.support.pushState ) { pageReset(); } // force the page reset for all pushstate tests if ( $.support.pushState ) { pageReset( home ); } $.mobile.urlHistory.stack = []; $.mobile.urlHistory.activeIndex = 0; $.Event.prototype.which = undefined; $.mobile.linkBindingEnabled = originalLinkBinding; } }); asyncTest( "window.history.back() from external to internal page", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#active-state-page1"); }, function(){ ok( $.mobile.activePage[0] === $( "#active-state-page1" )[ 0 ], "successful navigation to internal page." ); //location.hash = siteDirectory + "external.html"; $.mobile.changePage("external.html"); }, function(){ ok( $.mobile.activePage[0] !== $( "#active-state-page1" )[ 0 ], "successful navigation to external page." ); window.history.back(); }, function(){ ok( $.mobile.activePage[0] === $( "#active-state-page1" )[ 0 ], "successful navigation back to internal page." ); start(); } ]); }); asyncTest( "external page is removed from the DOM after pagehide", function(){ $.testHelper.pageSequence([ navigateTestRoot, function(){ $.mobile.changePage( "external.html" ); }, // page is pulled and displayed in the dom function(){ same( $( "#external-test" ).length, 1 ); window.history.back(); }, // external-test is *NOT* cached in the dom after transitioning away function(){ same( $( "#external-test" ).length, 0 ); start(); } ]); }); asyncTest( "preventDefault on pageremove event can prevent external page from being removed from the DOM", function(){ var preventRemoval = true, removeCallback = function( e ) { if ( preventRemoval ) { e.preventDefault(); } }; $( document ).bind( "pageremove", removeCallback ); $.testHelper.pageSequence([ navigateTestRoot, function(){ $.mobile.changePage( "external.html" ); }, // page is pulled and displayed in the dom function(){ same( $( "#external-test" ).length, 1 ); window.history.back(); }, // external-test *IS* cached in the dom after transitioning away function(){ same( $( "#external-test" ).length, 1 ); // Switch back to the page again! $.mobile.changePage( "external.html" ); }, // page is still present and displayed in the dom function(){ same( $( "#external-test" ).length, 1 ); // Now turn off our removal prevention. preventRemoval = false; window.history.back(); }, // external-test is *NOT* cached in the dom after transitioning away function(){ same( $( "#external-test" ).length, 0 ); $( document ).unbind( "pageremove", removeCallback ); start(); } ]); }); asyncTest( "external page is cached in the DOM after pagehide", function(){ $.testHelper.pageSequence([ navigateTestRoot, function(){ $.mobile.changePage( "cached-external.html" ); }, // page is pulled and displayed in the dom function(){ same( $( "#external-test-cached" ).length, 1 ); window.history.back(); }, // external test page is cached in the dom after transitioning away function(){ same( $( "#external-test-cached" ).length, 1 ); start(); } ]); }); asyncTest( "external page is cached in the DOM after pagehide when option is set globally", function(){ $.testHelper.pageSequence([ navigateTestRoot, function(){ $.mobile.page.prototype.options.domCache = true; $.mobile.changePage( "external.html" ); }, // page is pulled and displayed in the dom function(){ same( $( "#external-test" ).length, 1 ); window.history.back(); }, // external test page is cached in the dom after transitioning away function(){ same( $( "#external-test" ).length, 1 ); $.mobile.page.prototype.options.domCache = false; $( "#external-test" ).remove(); start(); }]); }); asyncTest( "page last scroll distance is remembered while navigating to and from pages", function(){ $.testHelper.pageSequence([ function(){ $( "body" ).height( $( window ).height() + 500 ); $.mobile.changePage( "external.html" ); }, function(){ // wait for the initial scroll to 0 setTimeout( function() { window.scrollTo( 0, 300 ); same( $(window).scrollTop(), 300, "scrollTop is 300 after setting it" ); }, 300); // wait for the scrollstop to fire and for the scroll to be // recorded 100 ms afterward (see changes made to handle hash // scrolling in some browsers) setTimeout( navigateTestRoot, 500 ); }, function(){ history.back(); }, function(){ // Give the silentScroll function some time to kick in. setTimeout(function() { same( $(window).scrollTop(), 300, "scrollTop is 300 after returning to the page" ); $( "body" ).height( "" ); start(); }, 300 ); } ]); }); asyncTest( "forms with data attribute ajax set to false will not call changePage", function(){ var called = false; var newChangePage = function(){ called = true; }; $.testHelper.sequence([ // avoid initial page load triggering changePage early function(){ $.mobile.changePage = newChangePage; $('#non-ajax-form').one('submit', function(event){ ok(true, 'submit callbacks are fired'); event.preventDefault(); }).submit(); }, function(){ ok(!called, "change page should not be called"); start(); }], 1000); }); asyncTest( "forms with data attribute ajax not set or set to anything but false will call changePage", function(){ var called = 0, newChangePage = function(){ called++; }; $.testHelper.sequence([ // avoid initial page load triggering changePage early function(){ $.mobile.changePage = newChangePage; $('#ajax-form, #rand-ajax-form').submit(); }, function(){ ok(called >= 2, "change page should be called at least twice"); start(); }], 300); }); asyncTest( "anchors with no href attribute will do nothing when clicked", function(){ var fired = false; $(window).bind("hashchange.temp", function(){ fired = true; }); $( "<a>test</a>" ).appendTo( $.mobile.firstPage ).click(); setTimeout(function(){ same(fired, false, "hash shouldn't change after click"); $(window).unbind("hashchange.temp"); start(); }, 500); }); test( "urlHistory is working properly", function(){ //urlHistory same( $.type( $.mobile.urlHistory.stack ), "array", "urlHistory.stack is an array" ); //preload the stack $.mobile.urlHistory.stack[0] = { url: "foo", transition: "bar" }; $.mobile.urlHistory.stack[1] = { url: "baz", transition: "shizam" }; $.mobile.urlHistory.stack[2] = { url: "shizoo", transition: "shizaah" }; //active index same( $.mobile.urlHistory.activeIndex , 0, "urlHistory.activeIndex is 0" ); //getActive same( $.type( $.mobile.urlHistory.getActive() ) , "object", "active item is an object" ); same( $.mobile.urlHistory.getActive().url , "foo", "active item has url foo" ); same( $.mobile.urlHistory.getActive().transition , "bar", "active item has transition bar" ); //get prev / next same( $.mobile.urlHistory.getPrev(), undefined, "urlHistory.getPrev() is undefined when active index is 0" ); $.mobile.urlHistory.activeIndex = 1; same( $.mobile.urlHistory.getPrev().url, "foo", "urlHistory.getPrev() has url foo when active index is 1" ); $.mobile.urlHistory.activeIndex = 0; same( $.mobile.urlHistory.getNext().url, "baz", "urlHistory.getNext() has url baz when active index is 0" ); //add new $.mobile.urlHistory.activeIndex = 2; $.mobile.urlHistory.addNew("test"); same( $.mobile.urlHistory.stack.length, 4, "urlHistory.addNew() adds an item after the active index" ); same( $.mobile.urlHistory.activeIndex, 3, "urlHistory.addNew() moves the activeIndex to the newly added item" ); //clearForward $.mobile.urlHistory.activeIndex = 0; $.mobile.urlHistory.clearForward(); same( $.mobile.urlHistory.stack.length, 1, "urlHistory.clearForward() clears the url stack after the active index" ); }); //url listening function testListening( prop ){ var stillListening = false; $(document).bind("pagebeforehide", function(){ stillListening = true; }); location.hash = "foozball"; setTimeout(function(){ ok( prop == stillListening, prop + " = false disables default hashchange event handler"); location.hash = ""; prop = true; start(); }, 1000); } asyncTest( "ability to disable our hash change event listening internally", function(){ testListening( ! $.mobile.urlHistory.ignoreNextHashChange ); }); asyncTest( "ability to disable our hash change event listening globally", function(){ testListening( $.mobile.hashListeningEnabled ); }); var testDataUrlHash = function( linkSelector, matches ) { $.testHelper.pageSequence([ function(){ window.location.hash = ""; }, function(){ $(linkSelector).click(); }, function(){ $.testHelper.assertUrlLocation( $.extend(matches, { report: "url or hash should match" }) ); start(); } ]); stop(); }; test( "when loading a page where data-url is not defined on a sub element hash defaults to the url", function(){ testDataUrlHash( "#non-data-url a", {hashOrPush: siteDirectory + "data-url-tests/non-data-url.html"} ); }); test( "data url works for nested paths", function(){ var url = "foo/bar.html"; testDataUrlHash( "#nested-data-url a", {hash: url, push: home + url} ); }); test( "data url works for single quoted paths and roles", function(){ var url = "foo/bar/single.html"; testDataUrlHash( "#single-quotes-data-url a", {hash: url, push: home + url} ); }); test( "data url works when role and url are reversed on the page element", function(){ var url = "foo/bar/reverse.html"; testDataUrlHash( "#reverse-attr-data-url a", {hash: url, push: home + url} ); }); asyncTest( "last entry choosen amongst multiple identical url history stack entries on hash change", function(){ // make sure the stack is clear after initial page load an any other delayed page loads // TODO better browser state management $.mobile.urlHistory.stack = []; $.mobile.urlHistory.activeIndex = 0; $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#dup-history-first"); }, function(){ $("#dup-history-first a").click(); }, function(){ $("#dup-history-second a:first").click(); }, function(){ $("#dup-history-first a").click(); }, function(){ $("#dup-history-second a:last").click(); }, function(){ $("#dup-history-dialog a:contains('Close')").click(); }, function(){ // fourth page (third index) in the stack to account for first page being hash manipulation, // the third page is dup-history-second which has two entries in history // the test is to make sure the index isn't 1 in this case, or the first entry for dup-history-second same($.mobile.urlHistory.activeIndex, 3, "should be the fourth page in the stack"); start(); }]); }); asyncTest( "going back from a page entered from a dialog skips the dialog and goes to the previous page", function(){ $.testHelper.pageSequence([ // setup function(){ $.testHelper.openPage("#skip-dialog-first"); }, // transition to the dialog function(){ $("#skip-dialog-first a").click(); }, // transition to the second page function(){ $("#skip-dialog a").click(); }, // transition past the dialog via data-rel=back link on the second page function(){ $("#skip-dialog-second a").click(); }, // make sure we're at the first page and not the dialog function(){ $.testHelper.assertUrlLocation({ hash: "skip-dialog-first", push: home + "#skip-dialog-first", report: "should be the first page in the sequence" }); start(); }]); }); asyncTest( "going forward from a page entered from a dialog skips the dialog and goes to the next page", function(){ $.testHelper.pageSequence([ // setup function(){ $.testHelper.openPage("#skip-dialog-first"); }, // transition to the dialog function(){ $("#skip-dialog-first a").click(); }, // transition to the second page function(){ $("#skip-dialog a").click(); }, // transition to back past the dialog function(){ window.history.back(); }, // transition to the second page past the dialog through history function(){ window.history.forward(); }, // make sure we're on the second page and not the dialog function(){ $.testHelper.assertUrlLocation({ hash: "skip-dialog-second", push: home + "#skip-dialog-second", report: "should be the second page after the dialog" }); start(); }]); }); asyncTest( "going back from a dialog triggered from a dialog should result in the first dialog ", function(){ $.testHelper.pageSequence([ // setup function(){ $.testHelper.openPage("#nested-dialog-page"); }, // transition to the dialog function(){ $("#nested-dialog-page a").click(); }, // transition to the second dialog function(){ $("#nested-dialog-first a").click(); }, // transition to back to the first dialog function(){ window.history.back(); }, // make sure we're on first dialog function(){ same($(".ui-page-active")[0], $("#nested-dialog-first")[0], "should be the first dialog"); start(); }]); }); asyncTest( "loading a relative file path after an embeded page works", function(){ $.testHelper.pageSequence([ // transition second page function(){ $.testHelper.openPage("#relative-after-embeded-page-first"); }, // transition second page function(){ $("#relative-after-embeded-page-first a").click(); }, // transition to the relative ajax loaded page function(){ $("#relative-after-embeded-page-second a").click(); }, // make sure the page was loaded properly via ajax function(){ // data attribute intentionally left without namespace same($(".ui-page-active").data("other"), "for testing", "should be relative ajax loaded page"); start(); }]); }); asyncTest( "Page title updates properly when clicking back to previous page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#relative-after-embeded-page-first"); }, function(){ window.history.back(); }, function(){ same(document.title, "jQuery Mobile Navigation Test Suite"); start(); } ]); }); asyncTest( "Page title updates properly when clicking a link back to first page", function(){ var title = document.title; $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#ajax-title-page"); }, function(){ $("#titletest1").click(); }, function(){ same(document.title, "Title Tag"); $.mobile.activePage.find("#title-check-link").click(); }, function(){ same(document.title, title); start(); } ]); }); asyncTest( "Page title updates properly from title tag when loading an external page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#ajax-title-page"); }, function(){ $("#titletest1").click(); }, function(){ same(document.title, "Title Tag"); start(); } ]); }); asyncTest( "Page title updates properly from data-title attr when loading an external page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#ajax-title-page"); }, function(){ $("#titletest2").click(); }, function(){ same(document.title, "Title Attr"); start(); } ]); }); asyncTest( "Page title updates properly from heading text in header when loading an external page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#ajax-title-page"); }, function(){ $("#titletest3").click(); }, function(){ same(document.title, "Title Heading"); start(); } ]); }); asyncTest( "Page links to the current active page result in the same active page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#self-link"); }, function(){ $("a[href='#self-link']").click(); }, function(){ same($.mobile.activePage[0], $("#self-link")[0], "self-link page is still the active page" ); start(); } ]); }); asyncTest( "links on subdirectory pages with query params append the params and load the page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#data-url-tests/non-data-url.html"); }, function(){ $("#query-param-anchor").click(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "data-url-tests/non-data-url.html?foo=bar", report: "the hash or url has query params" }); ok($(".ui-page-active").jqmData("url").indexOf("?foo=bar") > -1, "the query params are in the data url"); start(); } ]); }); asyncTest( "identical query param link doesn't add additional set of query params", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#data-url-tests/non-data-url.html"); }, function(){ $("#query-param-anchor").click(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "data-url-tests/non-data-url.html?foo=bar", report: "the hash or url has query params" }); $("#query-param-anchor").click(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "data-url-tests/non-data-url.html?foo=bar", report: "the hash or url still has query params" }); start(); } ]); }); // Special handling inside navigation because query params must be applied to the hash // or absolute reference and dialogs apply extra information int the hash that must be removed asyncTest( "query param link from a dialog to itself should be a not add another dialog", function(){ var firstDialogLoc; $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#dialog-param-link"); }, // navigate to the subdirectory page with the query link function(){ $("#dialog-param-link a").click(); }, // navigate to the query param self reference link function(){ $("#dialog-param-link-page a").click(); }, // attempt to navigate to the same link function(){ // store the current hash for comparison (with one dialog hash key) firstDialogLoc = location.hash || location.href; $("#dialog-param-link-page a").click(); }, function(){ same(location.hash || location.href, firstDialogLoc, "additional dialog hash key not added"); start(); } ]); }); asyncTest( "query data passed as string to changePage is appended to URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.mobile.changePage( "form-tests/changepage-data.html", { data: "foo=1&bar=2" } ); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "form-tests/changepage-data.html?foo=1&bar=2", report: "the hash or url still has query params" }); start(); } ]); }); asyncTest( "query data passed as object to changePage is appended to URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.mobile.changePage( "form-tests/changepage-data.html", { data: { foo: 3, bar: 4 } } ); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "form-tests/changepage-data.html?foo=3&bar=4", report: "the hash or url still has query params" }); start(); } ]); }); asyncTest( "refresh of a dialog url should not duplicate page", function(){ $.testHelper.pageSequence([ // open our test page function(){ same($(".foo-class").length, 1, "should only have one instance of foo-class in the document"); location.hash = "#foo&ui-state=dialog"; }, function(){ $.testHelper.assertUrlLocation({ hash: "foo&ui-state=dialog", push: home + "#foo&ui-state=dialog", report: "hash should match what was loaded" }); same( $(".foo-class").length, 1, "should only have one instance of foo-class in the document" ); start(); } ]); }); asyncTest( "internal form with no action submits to document URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#internal-no-action-form-page"); }, function(){ $("#internal-no-action-form-page form").eq(0).submit(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "?foo=1&bar=2", report: "hash should match what was loaded" }); start(); } ]); }); asyncTest( "external page containing form with no action submits to page URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#internal-no-action-form-page"); }, function(){ $("#internal-no-action-form-page a").eq(0).click(); }, function(){ $("#external-form-no-action-page form").eq(0).submit(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "form-tests/form-no-action.html?foo=1&bar=2", report: "hash should match page url and not document url" }); start(); } ]); }); asyncTest( "handling of active button state when navigating", 1, function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#active-state-page1"); }, function(){ $("#active-state-page1 a").eq(0).click(); }, function(){ $("#active-state-page2 a").eq(0).click(); }, function(){ ok(!$("#active-state-page1 a").hasClass( $.mobile.activeBtnClass ), "No button should not have class " + $.mobile.activeBtnClass ); start(); } ]); }); // issue 2444 https://github.com/jquery/jquery-mobile/issues/2444 // results from preventing spurious hash changes asyncTest( "dialog should return to its parent page when open and closed multiple times", function() { $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#default-trans-dialog"); }, function(){ $.mobile.activePage.find( "a" ).click(); }, function(){ window.history.back(); }, function(){ same( $.mobile.activePage[0], $( "#default-trans-dialog" )[0] ); $.mobile.activePage.find( "a" ).click(); }, function(){ window.history.back(); }, function(){ same( $.mobile.activePage[0], $( "#default-trans-dialog" )[0] ); start(); } ]); }); asyncTest( "clicks with middle mouse button are ignored", function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage( "#odd-clicks-page" ); }, function() { $( "#right-or-middle-click" ).click(); }, // make sure the page is opening first without the mocked button click value // only necessary to prevent issues with test specific fixtures function() { same($.mobile.activePage[0], $("#odd-clicks-page-dest")[0]); $.testHelper.openPage( "#odd-clicks-page" ); // mock the which value to simulate a middle click $.Event.prototype.which = 2; }, function() { $( "#right-or-middle-click" ).click(); }, function( timeout ) { ok( timeout, "page event handler timed out due to ignored click" ); ok($.mobile.activePage[0] !== $("#odd-clicks-page-dest")[0], "pages are not the same"); start(); } ]); }); asyncTest( "disabling link binding disables navigation via links and highlighting", function() { $.mobile.linkBindingEnabled = false; $.testHelper.pageSequence([ function() { $.testHelper.openPage("#bar"); }, function() { $.mobile.activePage.find( "a" ).click(); }, function( timeout ) { ok( !$.mobile.activePage.find( "a" ).hasClass( $.mobile.activeBtnClass ), "vlick handler doesn't add the activebtn class" ); ok( timeout, "no page change was fired" ); start(); } ]); }); asyncTest( "handling of button active state when navigating by clicking back button", 1, function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#active-state-page1"); }, function(){ $("#active-state-page1 a").eq(0).click(); }, function(){ $("#active-state-page2 a").eq(1).click(); }, function(){ $("#active-state-page1 a").eq(0).click(); }, function(){ ok(!$("#active-state-page2 a").hasClass( $.mobile.activeBtnClass ), "No button should not have class " + $.mobile.activeBtnClass ); start(); } ]); }); asyncTest( "can navigate to dynamically injected page with dynamically injected link", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#inject-links-page"); }, function(){ var $ilpage = $( "#inject-links-page" ), $link = $( "<a href='#injected-test-page'>injected-test-page link</a>" ); // Make sure we actually navigated to the expected page. ok( $.mobile.activePage[ 0 ] == $ilpage[ 0 ], "navigated successfully to #inject-links-page" ); // Now dynamically insert a page. $ilpage.parent().append( "<div data-role='page' id='injected-test-page'>testing...</div>" ); // Now inject a link to this page dynamically and attempt to navigate // to the page we just inserted. $link.appendTo( $ilpage ).click(); }, function(){ // Make sure we actually navigated to the expected page. ok( $.mobile.activePage[ 0 ] == $( "#injected-test-page" )[ 0 ], "navigated successfully to #injected-test-page" ); start(); } ]); }); asyncTest( "application url with dialogHashKey loads application's first page", function(){ $.testHelper.pageSequence([ // open our test page function(){ // Navigate to any page except the first page of the application. $.testHelper.openPage("#foo"); }, function(){ ok( $.mobile.activePage[ 0 ] === $( "#foo" )[ 0 ], "navigated successfully to #foo" ); // Now navigate to an hash that contains just a dialogHashKey. $.mobile.changePage("#" + $.mobile.dialogHashKey); }, function(){ // Make sure we actually navigated to the first page. ok( $.mobile.activePage[ 0 ] === $.mobile.firstPage[ 0 ], "navigated successfully to first-page" ); // Now make sure opening the page didn't result in page duplication. ok( $.mobile.firstPage.hasClass( "first-page" ), "first page has expected class" ); same( $( ".first-page" ).length, 1, "first page was not duplicated" ); start(); } ]); }); asyncTest( "navigate to non-existent internal page throws pagechangefailed", function(){ var pagechangefailed = false, pageChangeFailedCB = function( e ) { pagechangefailed = true; } $( document ).bind( "pagechangefailed", pageChangeFailedCB ); $.testHelper.pageSequence([ // open our test page function(){ // Make sure there's only one copy of the first-page in the DOM to begin with. ok( $.mobile.firstPage.hasClass( "first-page" ), "first page has expected class" ); same( $( ".first-page" ).length, 1, "first page was not duplicated" ); // Navigate to any page except the first page of the application. $.testHelper.openPage("#foo"); }, function(){ var $foo = $( "#foo" ); ok( $.mobile.activePage[ 0 ] === $foo[ 0 ], "navigated successfully to #foo" ); same( pagechangefailed, false, "no page change failures" ); // Now navigate to a non-existent page. $foo.find( "#bad-internal-page-link" ).click(); }, function(){ // Make sure a pagechangefailed event was triggered. same( pagechangefailed, true, "pagechangefailed dispatched" ); // Make sure we didn't navigate away from #foo. ok( $.mobile.activePage[ 0 ] === $( "#foo" )[ 0 ], "did not navigate away from #foo" ); // Now make sure opening the page didn't result in page duplication. same( $( ".first-page" ).length, 1, "first page was not duplicated" ); $( document ).unbind( "pagechangefailed", pageChangeFailedCB ); start(); } ]); }); asyncTest( "prefetched links with data rel dialog result in a dialog", function() { $.testHelper.pageSequence([ // open our test page function(){ // Navigate to any page except the first page of the application. $.testHelper.openPage("#prefetched-dialog-page"); }, function() { $("#prefetched-dialog-link").click(); }, function() { ok( $.mobile.activePage.is(".ui-dialog"), "prefetched page is rendered as a dialog" ); start(); } ]); }); asyncTest( "first page gets reloaded if pruned from the DOM", function(){ var hideCallbackTriggered = false; function hideCallback( e, data ) { var page = e.target; ok( ( page === $.mobile.firstPage[ 0 ] ), "hide called with prevPage set to firstPage"); if ( page === $.mobile.firstPage[ 0 ] ) { $( page ).remove(); } hideCallbackTriggered = true; } $(document).bind('pagehide', hideCallback); $.testHelper.pageSequence([ function(){ // Make sure the first page is actually in the DOM. ok( $.mobile.firstPage.parent().length !== 0, "first page is currently in the DOM" ); // Make sure the first page is the active page. ok( $.mobile.activePage[ 0 ] === $.mobile.firstPage[ 0 ], "first page is the active page" ); // Now make sure the first page has an id that we can use to reload it. ok( $.mobile.firstPage[ 0 ].id, "first page has an id" ); // Make sure there is only one first page in the DOM. same( $( ".first-page" ).length, 1, "only one instance of the first page in the DOM" ); // Navigate to any page except the first page of the application. $.testHelper.openPage("#foo"); }, function(){ // Make sure the active page is #foo. ok( $.mobile.activePage[ 0 ] === $( "#foo" )[ 0 ], "navigated successfully to #foo" ); // Make sure our hide callback was triggered. ok( hideCallbackTriggered, "hide callback was triggered" ); // Make sure the first page was actually pruned from the document. ok( $.mobile.firstPage.parent().length === 0, "first page was pruned from the DOM" ); same( $( ".first-page" ).length, 0, "no instance of the first page in the DOM" ); // Remove our hideCallback. $(document).unbind('pagehide', hideCallback); // Navigate back to the first page! $.testHelper.openPage( "#" + $.mobile.firstPage[0].id ); }, function(){ var firstPage = $( ".first-page" ); // We should only have one first page in the document at any time! same( firstPage.length, 1, "single instance of first page recreated in the DOM" ); // Make sure the first page in the DOM is actually a different DOM element than the original // one we started with. ok( $.mobile.firstPage[ 0 ] !== firstPage[ 0 ], "first page is a new DOM element"); // Make sure we actually navigated to the new first page. ok( $.mobile.activePage[ 0 ] === firstPage[ 0 ], "navigated successfully to new first-page"); // Reset the $.mobile.firstPage for subsequent tests. // XXX: Should we just get rid of the new one and restore the old? $.mobile.firstPage = $.mobile.activePage; start(); } ]); }); })(jQuery);
JavaScript
/* * mobile navigation unit tests */ (function($){ var perspective = "viewport-flip", transitioning = "ui-mobile-viewport-transitioning", animationCompleteFn = $.fn.animationComplete, //TODO centralize class names? transitionTypes = "in out fade slide flip reverse pop", isTransitioning = function(page){ return $.grep(transitionTypes.split(" "), function(className, i){ return page.hasClass(className); }).length > 0; }, isTransitioningIn = function(page){ return page.hasClass("in") && isTransitioning(page); }, //animationComplete callback queue callbackQueue = [], finishPageTransition = function(){ callbackQueue.pop()(); }, clearPageTransitionStack = function(){ stop(); var checkTransitionStack = function(){ if(callbackQueue.length>0) { setTimeout(function(){ finishPageTransition(); checkTransitionStack(); },0); } else { start(); } }; checkTransitionStack(); }, //wipe all urls clearUrlHistory = function(){ $.mobile.urlHistory.stack = []; $.mobile.urlHistory.activeIndex = 0; }; module('jquery.mobile.navigation.js', { setup: function(){ //stub to prevent class removal $.fn.animationComplete = function(callback){ callbackQueue.unshift(callback); }; clearPageTransitionStack(); clearUrlHistory(); }, teardown: function(){ // unmock animation complete $.fn.animationComplete = animationCompleteFn; } }); test( "changePage applys perspective class to mobile viewport for flip", function(){ $("#foo > a").click(); ok($("body").hasClass(perspective), "has perspective class"); }); test( "changePage does not apply perspective class to mobile viewport for transitions other than flip", function(){ $("#bar > a").click(); ok(!$("body").hasClass(perspective), "doesn't have perspective class"); }); test( "changePage applys transition class to mobile viewport for default transition", function(){ $("#baz > a").click(); ok($("body").hasClass(transitioning), "has transitioning class"); }); test( "explicit transition preferred for page navigation reversal (ie back)", function(){ $("#fade-trans > a").click(); stop(); setTimeout(function(){ finishPageTransition(); $("#flip-trans > a").click(); setTimeout(function(){ finishPageTransition(); $("#fade-trans > a").click(); setTimeout(function(){ ok($("#flip-trans").hasClass("fade"), "has fade class"); start(); },0); },0); },0); }); test( "default transition is slide", function(){ $("#default-trans > a").click(); stop(); setTimeout(function(){ ok($("#no-trans").hasClass("slide"), "has slide class"); start(); },0); }); test( "changePage queues requests", function(){ var firstPage = $("#foo"), secondPage = $("#bar"); $.mobile.changePage(firstPage); $.mobile.changePage(secondPage); stop(); setTimeout(function(){ ok(isTransitioningIn(firstPage), "first page begins transition"); ok(!isTransitioningIn(secondPage), "second page doesn't transition yet"); finishPageTransition(); setTimeout(function(){ ok(!isTransitioningIn(firstPage), "first page transition should be complete"); ok(isTransitioningIn(secondPage), "second page should begin transitioning"); start(); },0); },0); }); test( "default transition is pop for a dialog", function(){ expect( 1 ); stop(); setTimeout(function(){ $("#default-trans-dialog > a").click(); ok($("#no-trans-dialog").hasClass("pop"), "expected the pop class to be present but instead was " + $("#no-trans-dialog").attr('class')); start(); }, 900); }); test( "animationComplete return value", function(){ $.fn.animationComplete = animationCompleteFn; equals($("#foo").animationComplete(function(){})[0], $("#foo")[0]); }); })(jQuery);
JavaScript
/* * mobile widget unit tests */ (function($){ module('jquery.mobile.widget.js'); test( "getting data from creation options", function(){ var expected = "bizzle"; $.mobile.widget.prototype.options = { "fooBar" : true }; $.mobile.widget.prototype.element = $("<div data-foo-bar=" + expected + ">"); same($.mobile.widget.prototype._getCreateOptions()["fooBar"], expected); }); test( "getting no data when the options are empty", function(){ var expected = {}; $.mobile.widget.prototype.options = {}; $.mobile.widget.prototype.element = $("<div data-foo-bar=" + expected + ">"); same($.mobile.widget.prototype._getCreateOptions(), expected); }); test( "getting no data when the element has none", function(){ var expected = {}; $.mobile.widget.prototype.options = { "fooBar" : true }; $.mobile.widget.prototype.element = $("<div>"); same($.mobile.widget.prototype._getCreateOptions(), expected); }); test( "elements embedded in sub page elements are excluded on create when they match the keep native selector", function() { // uses default keep native of data-role=none $("#enhance-prevented") .append('<label for="unenhanced">Text Input:</label><input type="text" name="name" id="unenhanced" value="" data-role="none" />') .trigger("create"); ok( !$("#unenhanced").hasClass( "ui-input-text" ), "doesn't have the ui input text class (unenhanced)"); }); test( "elements embedded in sub page elements are included on create when they don't match the keep native selector", function() { // uses default keep native of data-role=none $("#enhance-allowed") .append('<label for="enhanced">Text Input:</label><input type="text" name="name" id="enhanced" value=""/>') .trigger("create"); ok( $("#enhanced").hasClass( "ui-input-text" ), "has the ui input text class (unenhanced)"); }); })(jQuery);
JavaScript
/* * mobile widget unit tests */ (function($){ var widgetInitialized = false; module( 'jquery.mobile.widget.js' ); $( "#foo" ).live( 'pageinit', function(){ // ordering sensitive here, the value has to be set after the call // so that if the widget factory says that its not yet initialized, // which is an exception, the value won't be set $( "#foo-slider" ).slider( 'refresh' ); widgetInitialized = true; }); test( "page is enhanced before init is fired", function() { ok( widgetInitialized ); }); })( jQuery );
JavaScript
/* * mobile checkboxradio unit tests */ (function($){ module( 'jquery.mobile.forms.checkboxradio.js' ); test( "widget can be disabled and enabled", function(){ var input = $( "#checkbox-1" ), button = input.parent().find( ".ui-btn" ); input.checkboxradio( "disable" ); input.checkboxradio( "enable" ); ok( !input.attr( "disabled" ), "start input as enabled" ); ok( !input.parent().hasClass( "ui-disabled" ), "no disabled styles" ); ok( !input.attr( "checked" ), "not checked before click" ); button.trigger( "click" ); ok( input.attr( "checked" ), "checked after click" ); ok( button.hasClass( "ui-checkbox-on" ), "active styles after click" ); button.trigger( "click" ); input.checkboxradio( "disable" ); ok( input.attr( "disabled" ), "input disabled" ); ok( input.parent().hasClass( "ui-disabled" ), "disabled styles" ); ok( !input.attr( "checked" ), "not checked before click" ); button.trigger( "click" ); ok( !input.attr( "checked" ), "not checked after click" ); ok( !button.hasClass( "ui-checkbox-on" ), "no active styles after click" ); }); test( "clicking a checkbox within a controlgroup does not affect checkboxes with the same name in the same controlgroup", function(){ var input1 = $("#checkbox-31"); var button1 = input1.parent().find(".ui-btn"); var input2 = $("#checkbox-32"); var button2 = input2.parent().find(".ui-btn"); ok(!input1.attr("checked"), "input1 not checked before click"); ok(!input2.attr("checked"), "input2 not checked before click"); button1.trigger("click"); ok(input1.attr("checked"), "input1 checked after click on input1"); ok(!input2.attr("checked"), "input2 not checked after click on input1"); button2.trigger("click"); ok(input1.attr("checked"), "input1 not changed after click on input2"); ok(input2.attr("checked"), "input2 checked after click on input2"); }); asyncTest( "change events fired on checkbox for both check and uncheck", function(){ var $checkbox = $( "#checkbox-2" ), $checkboxLabel = $checkbox.parent().find( ".ui-btn" ); $checkbox.unbind( "change" ); expect( 1 ); $checkbox.one('change', function(){ ok( true, "change fired on click to check the box" ); }); $checkboxLabel.trigger( "click" ); //test above will be triggered twice, and the start here once $checkbox.one('change', function(){ start(); }); $checkboxLabel.trigger( "click" ); }); asyncTest( "radio button labels should update the active button class to last clicked and clear checked", function(){ var $radioBtns = $( '#radio-active-btn-test input' ), singleActiveAndChecked = function(){ same( $( "#radio-active-btn-test .ui-radio-on" ).length, 1, "there should be only one active button" ); same( $( "#radio-active-btn-test :checked" ).length, 1, "there should be only one checked" ); }; $.testHelper.sequence([ function(){ $radioBtns.last().siblings( 'label' ).click(); }, function(){ ok( $radioBtns.last().prop( 'checked' ) ); ok( $radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ), "last input label is an active button" ); ok( !$radioBtns.first().prop( 'checked' ) ); ok( !$radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ), "first input label is not active" ); singleActiveAndChecked(); $radioBtns.first().siblings( 'label' ).click(); }, function(){ ok( $radioBtns.first().prop( 'checked' )); ok( $radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ), "first input label is an active button" ); ok( !$radioBtns.last().prop( 'checked' )); ok( !$radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ), "last input label is not active" ); singleActiveAndChecked(); start(); } ], 500); }); test( "checkboxradio controls will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-checkbox").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-checkbox").length, "enhancements applied" ); }); $.mobile.page.prototype.options.keepNative = "input.should-be-native"; // not testing the positive case here since's it's obviously tested elsewhere test( "checkboxradio elements in the keepNative set shouldn't be enhanced", function() { ok( !$("input.should-be-native").parent().is("div.ui-checkbox") ); }); asyncTest( "clicking the label triggers a click on the element", function() { var clicked = false; expect( 1 ); $( "#checkbox-click-triggered" ).one('click', function() { clicked = true; }); $.testHelper.sequence([ function() { $( "[for='checkbox-click-triggered']" ).click(); }, function() { ok(clicked, "click was fired on input"); start(); } ], 2000); }); })(jQuery);
JavaScript
/* * mobile slider unit tests */ (function($){ $.mobile.page.prototype.options.keepNative = "input.should-be-native"; // not testing the positive case here since's it's obviously tested elsewhere test( "slider elements in the keepNative set shouldn't be enhanced", function() { same( $("input.should-be-native").siblings("div.ui-slider").length, 0 ); }); })( jQuery );
JavaScript
/* * mobile slider unit tests */ (function($){ var onChangeCnt = 0; window.onChangeCounter = function() { onChangeCnt++; } module('jquery.mobile.slider.js'); var keypressTest = function(opts){ var slider = $(opts.selector), val = window.parseFloat(slider.val()), handle = slider.siblings('.ui-slider').find('.ui-slider-handle'); expect( opts.keyCodes.length ); $.each(opts.keyCodes, function(i, elem){ // stub the keycode value and trigger the keypress $.Event.prototype.keyCode = $.mobile.keyCode[elem]; handle.trigger('keydown'); val += opts.increment; same(val, window.parseFloat(slider.val(), 10), "new value is " + opts.increment + " different"); }); }; test( "slider should move right with up, right, and page up keypress", function(){ keypressTest({ selector: '#range-slider-up', keyCodes: ['UP', 'RIGHT', 'PAGE_UP'], increment: 1 }); }); test( "slider should move left with down, left, and page down keypress", function(){ keypressTest({ selector: '#range-slider-down', keyCodes: ['DOWN', 'LEFT', 'PAGE_DOWN'], increment: -1 }); }); test( "slider should move to range minimum on end keypress", function(){ var selector = "#range-slider-end", initialVal = window.parseFloat($(selector).val(), 10), max = window.parseFloat($(selector).attr('max'), 10); keypressTest({ selector: selector, keyCodes: ['END'], increment: max - initialVal }); }); test( "slider should move to range minimum on end keypress", function(){ var selector = "#range-slider-home", initialVal = window.parseFloat($(selector).val(), 10); keypressTest({ selector: selector, keyCodes: ['HOME'], increment: 0 - initialVal }); }); test( "slider should move positive by steps on keypress", function(){ keypressTest({ selector: "#stepped", keyCodes: ['RIGHT'], increment: 10 }); }); test( "slider should move negative by steps on keypress", function(){ keypressTest({ selector: "#stepped", keyCodes: ['LEFT'], increment: -10 }); }); test( "slider should validate input value on blur", function(){ var slider = $("#range-slider-up"); slider.focus(); slider.val(200); same(slider.val(), "200"); slider.blur(); same(slider.val(), slider.attr('max')); }); test( "slider should not validate input on keyup", function(){ var slider = $("#range-slider-up"); slider.focus(); slider.val(200); same(slider.val(), "200"); slider.keyup(); same(slider.val(), "200"); }); test( "input type should degrade to number when slider is created", function(){ same($("#range-slider-up").attr( "type" ), "number"); }); // generic switch test function var sliderSwitchTest = function(opts){ var slider = $("#slider-switch"), handle = slider.siblings('.ui-slider').find('a'), switchValues = { 'off' : 0, 'on' : 1 }; // One for the select and one for the aria-valuenow expect( opts.keyCodes.length * 2 ); $.each(opts.keyCodes, function(i, elem){ // reset the values slider[0].selectedIndex = switchValues[opts.start]; handle.attr({'aria-valuenow' : opts.start }); // stub the keycode and trigger the event $.Event.prototype.keyCode = $.mobile.keyCode[elem]; handle.trigger('keydown'); same(handle.attr('aria-valuenow'), opts.finish, "handle value is " + opts.finish); same(slider[0].selectedIndex, switchValues[opts.finish], "select input has correct index"); }); }; test( "switch should select on with up, right, page up and end", function(){ sliderSwitchTest({ start: 'off', finish: 'on', keyCodes: ['UP', 'RIGHT', 'PAGE_UP', 'END'] }); }); test( "switch should select off with down, left, page down and home", function(){ sliderSwitchTest({ start: 'on', finish: 'off', keyCodes: ['DOWN', 'LEFT', 'PAGE_DOWN', 'HOME'] }); }); test( "onchange should not be called on create", function(){ equals(onChangeCnt, 0, "onChange should not have been called"); }); test( "onchange should be called onchange", function(){ onChangeCnt = 0; $( "#onchange" ).slider( "refresh", 50 ); equals(onChangeCnt, 1, "onChange should have been called once"); }); test( "slider controls will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-slider").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-slider").length, "enhancements applied" ); }); var createEvent = function( name, target, x, y ) { var event = $.Event( name ); event.target = target; event.pageX = x; event.pageY = y; return event; }; test( "toggle switch should fire one change event when clicked", function(){ var control = $( "#slider-switch" ), widget = control.data( "slider" ), slider = widget.slider, handle = widget.handle, changeCount = 0, changeFunc = function( e ) { ok( control[0].selectedIndex !== currentValue, "change event should only be triggered if the value changes"); ++changeCount; }, event = null, offset = handle.offset(), currentValue = control[0].selectedIndex; control.bind( "change", changeFunc ); // The toggle switch actually updates on mousedown and mouseup events, so we go through // the motions of generating all the events that happen during a click to make sure that // during all of those events, the value only changes once. slider.trigger( createEvent( "mousedown", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); slider.trigger( createEvent( "mouseup", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); slider.trigger( createEvent( "click", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); control.unbind( "change", changeFunc ); ok( control[0].selectedIndex !== currentValue, "value did change"); same( changeCount, 1, "change event should be fired once during a click" ); }); var assertLeftCSS = function( obj, opts ) { var integerLeft, compare, css, threshold; css = obj.css('left'); threshold = opts.pxThreshold || 0; if( css.indexOf( "px" ) > -1 ) { // parse the actual pixel value returned by the left css value // and the pixels passed in for comparison integerLeft = Math.round( parseFloat( css.replace("px", "") ) ), compare = parseInt( opts.pixels.replace( "px", "" ), 10 ); // check that the pixel value provided is within a given threshold; default is 0px ok( compare >= integerLeft - threshold && compare <= integerLeft + threshold, opts.message ); } else { equal( css, opts.percent, opts.message ); } }; asyncTest( "toggle switch handle should snap in the old position if dragged less than half of the slider width, in the new position if dragged more than half of the slider width", function() { var control = $( "#slider-switch" ), widget = control.data( "slider" ), slider = widget.slider, handle = widget.handle, width = handle.width(), offset = null; $.testHelper.sequence([ function() { // initialize the switch control.val('on').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css('width'), message: 'handle starts on the right side' }); // simulate dragging less than a half offset = handle.offset(); slider.trigger( createEvent( "mousedown", handle[ 0 ], offset.left + width - 10, offset.top + 10 ) ); slider.trigger( createEvent( "mousemove", handle[ 0 ], offset.left + width - 20, offset.top + 10 ) ); slider.trigger( createEvent( "mouseup", handle[ 0 ], offset.left + width - 20, offset.top + 10 ) ); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css('width'), message: 'handle ends on the right side' }); // initialize the switch control.val('on').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css('width'), message: 'handle starts on the right side' }); // simulate dragging more than a half offset = handle.offset(); slider.trigger( createEvent( "mousedown", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); slider.trigger( createEvent( "mousemove", handle[ 0 ], offset.left - ( width / 2 ), offset.top + 10 ) ); slider.trigger( createEvent( "mouseup", handle[ 0 ], offset.left - ( width / 2 ), offset.top + 10 ) ); }, function() { assertLeftCSS(handle, { percent: '0%', pixels: '0px', message: 'handle ends on the left side' }); start(); } ], 500); }); asyncTest( "toggle switch handle should not move if user is dragging and value is changed", function() { var control = $( "#slider-switch" ), widget = control.data( "slider" ), slider = widget.slider, handle = widget.handle, width = handle.width(), offset = null; $.testHelper.sequence([ function() { // initialize the switch control.val('on').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css('width'), message: 'handle starts on the right side' }); // simulate dragging more than a half offset = handle.offset(); slider.trigger( createEvent( "mousedown", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); slider.trigger( createEvent( "mousemove", handle[ 0 ], offset.left - ( width / 2 ), offset.top + 10 ) ); }, function() { var min, max; if( handle.css('left').indexOf("%") > -1 ){ min = "0%"; max = "100%"; } else { min = "0px"; max = handle.parent().css( 'width' ); } notEqual(handle.css('left'), min, 'handle is not on the left side'); notEqual(handle.css('left'), max, 'handle is not on the right side'); // reset slider state so it is ready for other tests slider.trigger( createEvent( "mouseup", handle[ 0 ], offset.left - ( width / 2 ), offset.top + 10 ) ); start(); } ], 500); }); asyncTest( "toggle switch should refresh when disabled", function() { var control = $( "#slider-switch" ), handle = control.data( "slider" ).handle; $.testHelper.sequence([ function() { // set the initial value control.val('off').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '0%', pixels: '0px', message: 'handle starts on the left side' }); // disable and change value control.slider('disable'); control.val('on').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css( 'width' ), message: 'handle ends on the right side' }); // reset slider state so it is ready for other tests control.slider('enable'); start(); } ], 500); }); })(jQuery);
JavaScript
/* * degradeInputs unit tests */ (function($){ module('jquery.mobile.slider.js'); test('keepNative elements should not be degraded', function() { same($('input#not-to-be-degraded').attr("type"), "range"); }); test('should degrade input type to a different type, as specified in page options', function(){ var degradeInputs = $.mobile.page.prototype.options.degradeInputs; expect( degradeInputs.length ); $.each(degradeInputs, function( oldType, newType ) { if (newType === false) { newType = oldType; } $('#test-container').html('<input type="' + oldType + '" />').trigger("create"); same($('#test-container input').attr("type"), newType); }); }); })(jQuery);
JavaScript
/* * mobile select unit tests */ (function($){ var resetHash; resetHash = function(timeout){ $.testHelper.openPage( location.hash.indexOf("#default") >= 0 ? "#" : "#default" ); }; // https://github.com/jquery/jquery-mobile/issues/2181 asyncTest( "dialog sized select should alter the value of its parent select", function(){ var selectButton, value; $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "cached.html" ); }, function(){ selectButton = $( "#cached-page-select" ).siblings( 'a' ); selectButton.click(); }, function(){ ok( $.mobile.activePage.hasClass('ui-dialog'), "the dialog came up" ); var option = $.mobile.activePage.find( "li a" ).not(":contains('" + selectButton.text() + "')").last(); value = option.text(); option.click(); }, function(){ same( value, selectButton.text(), "the selected value is propogated back to the button text" ); start(); } ]); }); // https://github.com/jquery/jquery-mobile/issues/2181 asyncTest( "dialog sized select should prevent the removal of its parent page from the dom", function(){ var selectButton, parentPageId; expect( 2 ); $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "cached.html" ); }, function(){ selectButton = $.mobile.activePage.find( "#cached-page-select" ).siblings( 'a' ); parentPageId = $.mobile.activePage.attr( 'id' ); same( $("#" + parentPageId).length, 1, "establish the parent page exists" ); selectButton.click(); }, function(){ same( $( "#" + parentPageId).length, 1, "make sure parent page is still there after opening the dialog" ); $.mobile.activePage.find( "li a" ).last().click(); }, start ]); }); asyncTest( "dialog sized select shouldn't rebind its parent page remove handler when closing, if the parent page domCache option is true", function(){ expect( 3 ); $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "cached-dom-cache-true.html" ); }, function(){ $.mobile.activePage.find( "#domcache-page-select" ).siblings( 'a' ).click(); }, function(){ ok( $.mobile.activePage.hasClass('ui-dialog'), "the dialog came up" ); $.mobile.activePage.find( "li a" ).last().click(); }, function(){ ok( $.mobile.activePage.is( "#dialog-select-parent-domcache-test" ), "the dialog closed" ); $.mobile.changePage( $( "#default" ) ); }, function(){ same( $("#dialog-select-parent-domcache-test").length, 1, "make sure the select parent page is still cached in the dom after changing page" ); start(); } ]); }); asyncTest( "menupage is removed when the parent page is removed", function(){ var dialogCount = $(":jqmData(role='dialog')").length; $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "uncached-dom-cached-false.html" ); }, function(){ same( $(":jqmData(role='dialog')").length, dialogCount + 1 ); window.history.back(); }, function() { same( $(":jqmData(role='dialog')").length, dialogCount ); start(); } ]); }); })(jQuery);
JavaScript
/* * mobile select unit tests */ (function($){ module("jquery.mobile.forms.select native"); test( "native menu selections alter the button text", function(){ var select = $( "#native-select-choice-few" ), setAndCheck; setAndCheck = function(key){ var text; select.val( key ).selectmenu( 'refresh' ); text = select.find( "option[value='" + key + "']" ).text(); same( select.parent().find(".ui-btn-text").text(), text ); }; setAndCheck( 'rush' ); setAndCheck( 'standard' ); }); asyncTest( "selecting a value removes the related buttons down state", function(){ var select = $( "#native-select-choice-few" ); $.testHelper.sequence([ function() { // click the native menu parent button select.parent().trigger( 'vmousedown' ); }, function() { ok( select.parent().hasClass("ui-btn-down-c"), "button down class added" ); }, function() { // trigger a change on the select select.trigger( "change" ); }, function() { ok( !select.parent().hasClass("ui-btn-down-c"), "button down class removed" ); start(); } ], 300); }); // issue https://github.com/jquery/jquery-mobile/issues/2410 test( "adding options and refreshing a native select defaults the text", function() { var select = $( "#native-refresh" ), button = select.siblings( '.ui-btn-inner' ), text = "foo"; same(button.text(), "default"); select.find( "option" ).remove(); //remove the loading message select.append('<option value="1">' + text + '</option>'); select.selectmenu('refresh'); same(button.text(), text); }); // issue 2424 test( "native selects should provide open and close as a no-op", function() { // exception will prevent test success if undef $( "#native-refresh" ).selectmenu( 'open' ); $( "#native-refresh" ).selectmenu( 'close' ); ok( true ); }); })(jQuery);
JavaScript
/* * mobile select unit tests */ (function($){ var libName = "jquery.mobile.forms.select.js", originalDefaultDialogTrans = $.mobile.defaultDialogTransition, originalDefTransitionHandler = $.mobile.defaultTransitionHandler, originalGetEncodedText = $.fn.getEncodedText, resetHash, closeDialog; resetHash = function(timeout){ $.testHelper.openPage( location.hash.indexOf("#default") >= 0 ? "#" : "#default" ); }; closeDialog = function(timeout){ $.mobile.activePage.find("li a").first().click(); }; module(libName, { teardown: function(){ $.mobile.defaultDialogTransition = originalDefaultDialogTrans; $.mobile.defaultTransitionHandler = originalDefTransitionHandler; $.fn.getEncodedText = originalGetEncodedText; window.encodedValueIsDefined = undefined; } }); asyncTest( "firing a click at least 400 ms later on the select screen overlay does close it", function(){ $.testHelper.sequence([ function(){ // bring up the smaller choice menu ok($("#select-choice-few-container a").length > 0, "there is in fact a button in the page"); $("#select-choice-few-container a").trigger("click"); }, function(){ //select the first menu item $("#select-choice-few-menu a:first").click(); }, function(){ same($("#select-choice-few-menu").parent(".ui-selectmenu-hidden").length, 1); start(); } ], 1000); }); asyncTest( "a large select menu should use the default dialog transition", function(){ var select; $.testHelper.pageSequence([ resetHash, function(timeout){ select = $("#select-choice-many-container-1 a"); //set to something else $.mobile.defaultTransitionHandler = $.testHelper.decorate({ fn: $.mobile.defaultTransitionHandler, before: function(name){ same(name, $.mobile.defaultDialogTransition); } }); // bring up the dialog select.trigger("click"); }, closeDialog, start ]); }); asyncTest( "custom select menu always renders screen from the left", function(){ var select; expect( 1 ); $.testHelper.sequence([ resetHash, function(){ select = $("ul#select-offscreen-menu"); $("#select-offscreen-container a").trigger("click"); }, function(){ ok(select.offset().left >= 30, "offset from the left is greater than or equal to 30px" ); start(); } ], 1000); }); asyncTest( "selecting an item from a dialog sized custom select menu leaves no dialog hash key", function(){ var dialogHashKey = "ui-state=dialog"; $.testHelper.pageSequence([ resetHash, function(timeout){ $("#select-choice-many-container-hash-check a").click(); }, function(){ ok(location.hash.indexOf(dialogHashKey) > -1); closeDialog(); }, function(){ same(location.hash.indexOf(dialogHashKey), -1); start(); } ]); }); asyncTest( "dialog sized select menu opened many times remains a dialog", function(){ var dialogHashKey = "ui-state=dialog", openDialogSequence = [ resetHash, function(){ $("#select-choice-many-container-many-clicks a").click(); }, function(){ ok(location.hash.indexOf(dialogHashKey) > -1, "hash should have the dialog hash key"); closeDialog(); } ], sequence = openDialogSequence.concat(openDialogSequence).concat([start]); $.testHelper.sequence(sequence, 1000); }); test( "make sure the label for the select gets the ui-select class", function(){ ok( $( "#native-select-choice-few-container label" ).hasClass( "ui-select" ), "created label has ui-select class" ); }); module("Non native menus", { setup: function() { $.mobile.selectmenu.prototype.options.nativeMenu = false; }, teardown: function() { $.mobile.selectmenu.prototype.options.nativeMenu = true; } }); asyncTest( "a large select option should not overflow", function(){ // https://github.com/jquery/jquery-mobile/issues/1338 var menu, select; $.testHelper.sequence([ resetHash, function(){ select = $("#select-long-option-label"); // bring up the dialog select.trigger("click"); }, function() { menu = $(".ui-selectmenu-list"); equal(menu.width(), menu.find("li:nth-child(2) .ui-btn-text").width(), "ui-btn-text element should not overflow"); start(); } ], 500); }); asyncTest( "using custom refocuses the button after close", function() { var select, button, triggered = false; expect( 1 ); $.testHelper.sequence([ resetHash, function() { select = $("#select-choice-focus-test"); button = select.find( "a" ); button.trigger( "click" ); }, function() { // NOTE this is called twice per triggered click button.focus(function() { triggered = true; }); $(".ui-selectmenu-screen:not(.ui-screen-hidden)").trigger("click"); }, function(){ ok(triggered, "focus is triggered"); start(); } ], 5000); }); asyncTest( "selected items are highlighted", function(){ $.testHelper.sequence([ resetHash, function(){ // bring up the smaller choice menu ok($("#select-choice-few-container a").length > 0, "there is in fact a button in the page"); $("#select-choice-few-container a").trigger("click"); }, function(){ var firstMenuChoice = $("#select-choice-few-menu li:first"); ok( firstMenuChoice.hasClass( $.mobile.activeBtnClass ), "default menu choice has the active button class" ); $("#select-choice-few-menu a:last").click(); }, function(){ // bring up the menu again $("#select-choice-few-container a").trigger("click"); }, function(){ var lastMenuChoice = $("#select-choice-few-menu li:last"); ok( lastMenuChoice.hasClass( $.mobile.activeBtnClass ), "previously slected item has the active button class" ); // close the dialog lastMenuChoice.find( "a" ).click(); }, start ], 1000); }); test( "enabling and disabling", function(){ var select = $( "select" ).first(), button; button = select.siblings( "a" ).first(); select.selectmenu( 'disable' ); same( select.attr('disabled'), "disabled", "select is disabled" ); ok( button.hasClass("ui-disabled"), "disabled class added" ); same( button.attr('aria-disabled'), "true", "select is disabled" ); same( select.selectmenu( 'option', 'disabled' ), true, "disbaled option set" ); select.selectmenu( 'enable' ); same( select.attr('disabled'), undefined, "select is disabled" ); ok( !button.hasClass("ui-disabled"), "disabled class added" ); same( button.attr('aria-disabled'), "false", "select is disabled" ); same( select.selectmenu( 'option', 'disabled' ), false, "disbaled option set" ); }); test( "adding options and refreshing a custom select defaults the text", function() { var select = $( "#custom-refresh" ), button = select.siblings( "a" ).find( ".ui-btn-inner" ), text = "foo"; same(button.text(), "default"); select.find( "option" ).remove(); //remove the loading message select.append('<option value="1">' + text + '</option>'); select.selectmenu( 'refresh' ); same(button.text(), text); }); asyncTest( "adding options and refreshing a custom select changes the options list", function(){ var select = $( "#custom-refresh-opts-list" ), button = select.siblings( "a" ).find( ".ui-btn-inner" ), text = "foo"; $.testHelper.sequence([ // bring up the dialog function() { button.click(); }, function() { same( $( ".ui-selectmenu.in ul" ).text(), "default" ); $( ".ui-selectmenu-screen" ).click(); }, function() { select.find( "option" ).remove(); //remove the loading message select.append('<option value="1">' + text + '</option>'); select.selectmenu( 'refresh' ); }, function() { button.click(); }, function() { same( $( ".ui-selectmenu.in ul" ).text(), text ); $( ".ui-selectmenu-screen" ).click(); }, start ], 500); }); test( "theme defined on select is used", function(){ var select = $("select#non-parent-themed"); ok( select.siblings( "a" ).hasClass("ui-btn-up-" + select.jqmData('theme'))); }); test( "select without theme defined inherits theme from parent", function() { var select = $("select#parent-themed"); ok( select .siblings( "a" ) .hasClass("ui-btn-up-" + select.parents(":jqmData(role='page')").jqmData('theme'))); }); // issue #2547 test( "custom select list item links have encoded option text values", function() { $( "#encoded-option" ).data( 'selectmenu' )._buildList(); same(window.encodedValueIsDefined, undefined); }); // issue #2547 test( "custom select list item links have unencoded option text values when using vanilla $.fn.text", function() { // undo our changes, undone in teardown $.fn.getEncodedText = $.fn.text; $( "#encoded-option" ).data( 'selectmenu' )._buildList(); same(window.encodedValueIsDefined, true); }); $.mobile.page.prototype.options.keepNative = "select.should-be-native"; // not testing the positive case here since's it's obviously tested elsewhere test( "select elements in the keepNative set shouldn't be enhanced", function() { ok( !$("#keep-native").parent().is("div.ui-btn") ); }); asyncTest( "dialog size select title should match the label", function() { var $select = $( "#select-choice-many-1" ), $label = $select.parent().siblings( "label" ), $button = $select.siblings( "a" ); $.testHelper.pageSequence([ function() { $button.click(); }, function() { same($.mobile.activePage.find( ".ui-title" ).text(), $label.text()); window.history.back(); }, start ]); }); asyncTest( "dialog size select title should match the label when changed after the dialog markup is added to the DOM", function() { var $select = $( "#select-choice-many-1" ), $label = $select.parent().siblings( "label" ), $button = $select.siblings( "a" ); $label.text( "foo" ); $.testHelper.pageSequence([ function() { $label.text( "foo" ); $button.click(); }, function() { same($.mobile.activePage.find( ".ui-title" ).text(), $label.text()); window.history.back(); }, start ]); }); })(jQuery);
JavaScript
/* * mobile select unit tests */ (function($){ var libName = "jquery.mobile.forms.select.js"; $(document).bind('mobileinit', function(){ $.mobile.selectmenu.prototype.options.nativeMenu = false; }); module(libName,{ setup: function(){ $.testHelper.openPage( location.hash.indexOf("#default") >= 0 ? "#" : "#default" ); } }); test( "selects marked with data-native-menu=true should use a div as their button", function(){ same($("#select-choice-native-container div.ui-btn").length, 1); }); test( "selects marked with data-native-menu=true should not have a custom menu", function(){ same($("#select-choice-native-container ul").length, 0); }); test( "selects marked with data-native-menu=true should sit inside the button", function(){ same($("#select-choice-native-container div.ui-btn select").length, 1); }); test( "select controls will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-select").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-select").length, "enhancements applied" ); }); })(jQuery);
JavaScript
/* * mobile checkboxradio unit tests */ (function($){ module( 'vertical controlgroup, no refresh' , { setup: function() { this.vcontrolgroup = $( "#vertical-controlgroup" ); } }); test( "vertical controlgroup classes", function() { var buttons = this.vcontrolgroup.find( ".ui-btn" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( !buttons.hasClass( "ui-btn-corner-all" ), "no button should have class 'ui-btn-corner-all'"); ok( buttons.first().hasClass( "ui-corner-top" ), "first button should have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-top" ), "middle buttons should not have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-bottom" ), "middle buttons should not have class 'ui-corner-bottom'" ); ok( buttons.last().hasClass( "ui-corner-bottom"), "last button should have class 'ui-corner-bottom'" ); }); module( 'vertical controlgroup, refresh', { setup: function() { this.vcontrolgroup = $( "#vertical-controlgroup" ); this.vcontrolgroup.find( ".ui-btn" ).show(); this.vcontrolgroup.controlgroup(); } }); test( "vertical controlgroup after first button was hidden", function() { //https://github.com/jquery/jquery-mobile/issues/1929 //We hide the first button and refresh this.vcontrolgroup.find( ".ui-btn" ).first().hide(); this.vcontrolgroup.controlgroup(); var buttons = this.vcontrolgroup.find( ".ui-btn" ).filter( ":visible" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( buttons.first().hasClass( "ui-corner-top" ), "first visible button should have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-top" ), "middle buttons should not have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-bottom" ), "middle buttons should not have class 'ui-corner-bottom'" ); ok( buttons.last().hasClass( "ui-corner-bottom"), "last visible button should have class 'ui-corner-bottom'" ); }); test( "vertical controlgroup after last button was hidden", function() { //https://github.com/jquery/jquery-mobile/issues/1929 //We hide the last button and refresh this.vcontrolgroup.find( ".ui-btn" ).last().hide(); this.vcontrolgroup.controlgroup(); var buttons = this.vcontrolgroup.find( ".ui-btn" ).filter( ":visible" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( buttons.first().hasClass( "ui-corner-top" ), "first visible button should have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-top" ), "middle buttons should not have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-bottom" ), "middle buttons should not have class 'ui-corner-bottom'" ); ok( buttons.last().hasClass( "ui-corner-bottom"), "last visible button should have class 'ui-corner-bottom'" ); }); module( 'horizontal controlgroup, no refresh', { setup: function() { this.hcontrolgroup = $( "#horizontal-controlgroup" ); } }); test( "horizontal controlgroup classes", function() { var buttons = this.hcontrolgroup.find( ".ui-btn" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( !buttons.hasClass( "ui-btn-corner-all" ), "no button should have class 'ui-btn-corner-all'"); ok( buttons.first().hasClass( "ui-corner-left" ), "first button should have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-left" ), "middle buttons should not have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-right" ), "middle buttons should not have class 'ui-corner-right'" ); ok( buttons.last().hasClass( "ui-corner-right"), "last button should have class 'ui-corner-right'" ); }); module( 'horizontal controlgroup, refresh', { setup: function() { this.hcontrolgroup = $( "#horizontal-controlgroup" ); this.hcontrolgroup.find( ".ui-btn" ).show(); this.hcontrolgroup.controlgroup(); } }); test( "horizontal controlgroup after first button was hidden", function() { //We hide the first button and refresh this.hcontrolgroup.find( ".ui-btn" ).first().hide(); this.hcontrolgroup.controlgroup(); var buttons = this.hcontrolgroup.find( ".ui-btn" ).filter( ":visible" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( buttons.first().hasClass( "ui-corner-left" ), "first visible button should have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-left" ), "middle buttons should not have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-right" ), "middle buttons should not have class 'ui-corner-right'" ); ok( buttons.last().hasClass( "ui-corner-right"), "last visible button should have class 'ui-corner-right'" ); }); test( "horizontal controlgroup after last button was hidden", function() { //We hide the last button and refresh this.hcontrolgroup.find( ".ui-btn" ).last().hide(); this.hcontrolgroup.controlgroup(); var buttons = this.hcontrolgroup.find( ".ui-btn" ).filter( ":visible" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( buttons.first().hasClass( "ui-corner-left" ), "first visible button should have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-left" ), "middle buttons should not have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-right" ), "middle buttons should not have class 'ui-corner-right'" ); ok( buttons.last().hasClass( "ui-corner-right"), "last visible button should have class 'ui-corner-right'" ); }); test( "controlgroups will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-controlgroup").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-controlgroup").length, "enhancements applied" ); }); })(jQuery);
JavaScript
(function(Perf) { var $listPage = $( "#list-page" ), firstCounter = 0; Perf.setCurrentRev(); Perf.pageLoadStart = Date.now(); $listPage.live( "pagebeforecreate", function() { if( firstCounter == 0 ) { Perf.pageCreateStart = Date.now(); firstCounter++; } }); $listPage.live( "pageinit", function( event ) { // if a child page init is fired ignore it, we only // want the top level page init event if( event.target !== $("#list-page")[0] ){ return; } Perf.pageLoadEnd = Date.now(); // report the time taken for a full app boot Perf.report({ datapoint: "fullboot", value: Perf.pageLoadEnd - Perf.pageLoadStart }); // record the time taken to load and enhance the page // start polling for a new revision Perf.report({ datapoint: "pageload", value: Perf.pageCreateStart - Perf.pageLoadStart, after: function() { Perf.poll(); } }); }); })(window.Perf);
JavaScript
window.Perf = (function($, Perf) { $.extend(Perf, { reportUrl: 'stats/', revUrl: 'stats/rev.php', // should be defined before report or poll are run currentRev: undefined, report: function( data, after ) { $.extend(data, { pathname: location.pathname, agent: this.agent(), agentFull: window.navigator.userAgent, agentVersion: this.agentVersion() }); $.post( this.reportUrl, data, after ); }, poll: function() { var self = this; setInterval(function() { $.get( self.revUrl, function( data ) { // if there's a new revision refresh or currentRev isn't being set if( self.currentRev && self.currentRev !== data ){ location.href = location.href; } }); }, 60000); }, setCurrentRev: function() { var self = this; $.get( self.revUrl, function( data ) { self.currentRev = data; }); }, agent: function() { var agent = window.navigator.userAgent; for( name in this.agents ) { if( agent.indexOf( this.agents[name] ) > -1 ) { return this.agents[name]; } } return agent; }, agentVersion: function() { var agent = window.navigator.userAgent; agent.search(this.vRegexs[this.agent()] || ""); return RegExp.$1 ? RegExp.$1 : "0.0"; }, agents: { ANDROID: "Android", WP: "Windows Phone OS", IPHONE: "iPhone OS", IPAD: "iPad; U; CPU OS", BLACKBERRY: "BlackBerry" }, vRegexs: {} }); Perf.vRegexs[Perf.agents.ANDROID] = /([0-9].[0-9])(.[0-9])?/; Perf.vRegexs[Perf.agents.WP] = /Windows Phone OS ([0-9].[0-9]);/; Perf.vRegexs[Perf.agents.IPHONE] = /iPhone OS ([0-9]_[0-9])/; Perf.vRegexs[Perf.agents.IPAD] = /iPad; U; CPU OS ([0-9]_[0-9])/; Perf.vRegexs[Perf.agents.BLACKBERRY] = /BlackBerry ([0-9]{4})/; return Perf; })(jQuery, window.Perf || {});
JavaScript
(function($) { // TODO this is entire thing sucks $(function() { var searchMap = (function() { var searchSplit, searchMap = {}; if ( !location.search ){ return searchMap; } searchSplit = location.search.replace(/^\?/, "").split( /&|;/ ); for( var i = 0; i < searchSplit.length; i++ ) { var kv = searchSplit[i].split(/=/); searchMap[ kv[0] ] = kv[1]; } return searchMap; })(); $.get("../", searchMap, function(data) { $.each(data, function( i, avg ) { var tablename = avg.point + " " + avg.agent + " " + avg.agent_version + " " + avg.pathname, $table = $( "table > caption:contains(" + tablename + ")").parent(); if( !$table.length ) { $table = $( "<table></table>", { "data-pathname": avg.pathname, "data-point": avg.point, "data-agent": avg.agent, "data-agent-version": avg.agent_version }); $table.append( "<caption>" + tablename + "</caption>"); $table.append( "<thead><tr></tr></thead>" ); $table.append( "<tbody><tr></tr></tbody>" ); } // TODO assume time ordering in the data set var $heading = $table.find("thead > tr > th:contains(" + avg.day + ")"); if( !$heading.length ) { $heading = $("<th></th>", { text: avg.day, scope: "column" }); $table.find("thead > tr").append($heading); } var $rowHeading = $table.find("tbody > tr > th:contains(" + avg.point + ")" ), $row = $table.find( "tbody > tr" ); if( !$rowHeading.length ) { $rowHeading = $("<th></th>", { text: avg.point, scope: "row" }); $row.append( $rowHeading ); } $row.append( "<td>" + avg.avg_value + "</td>" ); $("#tables").append($table); }); $("#tables table").visualize({ type: "bar", width: 400, height: 400 }).appendTo("#graphs"); }); }); })(jQuery);
JavaScript
/* * mobile support unit tests */ (function( $ ) { $.testHelper = { excludeFileProtocol: function(callback){ var message = "Tests require script reload and cannot be run via file: protocol"; if (location.protocol == "file:") { test(message, function(){ ok(false, message); }); } else { callback(); } }, // TODO prevent test suite loads when the browser doesn't support push state // and push-state false is defined. setPushStateFor: function( libs ) { if( $.support.pushState && location.search.indexOf( "push-state" ) >= 0 ) { $.support.pushState = false; } $.each(libs, function(i, l) { $( "<script>", { src: l }).appendTo("head"); }); }, reloads: {}, reloadLib: function(libName){ if(this.reloads[libName] === undefined) { this.reloads[libName] = { lib: $("script[src$='" + libName + "']"), count: 0 }; } var lib = this.reloads[libName].lib.clone(), src = lib.attr('src'); //NOTE append "cache breaker" to force reload lib.attr('src', src + "?" + this.reloads[libName].count++); $("body").append(lib); }, rerunQunit: function(){ var self = this; QUnit.init(); $("script:not([src*='.\/'])").each(function(i, elem){ var src = elem.src.split("/"); self.reloadLib(src[src.length - 1]); }); QUnit.start(); }, alterExtend: function(extraExtension){ var extendFn = $.extend; $.extend = function(object, extension){ // NOTE extend the object as normal var result = extendFn.apply(this, arguments); // NOTE add custom extensions result = extendFn(result, extraExtension); return result; }; }, hideActivePageWhenComplete: function() { if( $('#qunit-testresult').length > 0 ) { $('.ui-page-active').css('display', 'none'); } else { setTimeout($.testHelper.hideActivePageWhenComplete, 500); } }, openPage: function(hash){ location.href = location.href.split('#')[0] + hash; }, sequence: function(fns, interval){ $.each(fns, function(i, fn){ setTimeout(fn, i * interval); }); }, pageSequence: function(fns){ this.eventSequence("pagechange", fns); }, eventSequence: function(event, fns, timedOut){ var fn = fns.shift(), self = this; if( fn === undefined ) return; // if a pagechange or defined event is never triggered // continue in the sequence to alert possible failures var warnTimer = setTimeout(function(){ self.eventSequence(event, fns, true); }, 2000); // bind the recursive call to the event $.mobile.pageContainer.one(event, function(){ clearTimeout(warnTimer); // Let the current stack unwind before we fire off the next item in the sequence. // TODO setTimeout(self.pageSequence, 0, [fns, event]); setTimeout(function(){ self.eventSequence(event, fns); }, 0); }); // invoke the function which should, in some fashion, // trigger the defined event fn(timedOut); }, decorate: function(opts){ var thisVal = opts.self || window; return function(){ var returnVal; opts.before && opts.before.apply(thisVal, arguments); returnVal = opts.fn.apply(thisVal, arguments); opts.after && opts.after.apply(thisVal, arguments); return returnVal; }; }, assertUrlLocation: function( args ) { var parts = $.mobile.path.parseUrl( location.href ), pathnameOnward = location.href.replace( parts.domain, "" ); if( $.support.pushState ) { same( pathnameOnward, args.hashOrPush || args.push, args.report ); } else { same( parts.hash, "#" + (args.hashOrPush || args.hash), args.report ); } } }; })(jQuery);
JavaScript
//quick & dirty theme switcher, written to potentially work as a bookmarklet (function($){ $.themeswitcher = function(){ if( $('[data-'+ $.mobile.ns +'-url=themeswitcher]').length ){ return; } var themesDir = 'http://jquerymobile.com/test/css/themes/', themes = ['default','valencia'], currentPage = $.mobile.activePage, menuPage = $( '<div data-'+ $.mobile.ns +'url="themeswitcher" data-'+ $.mobile.ns +'role=\'dialog\' data-'+ $.mobile.ns +'theme=\'a\'>' + '<div data-'+ $.mobile.ns +'role=\'header\' data-'+ $.mobile.ns +'theme=\'b\'>' + '<div class=\'ui-title\'>Switch Theme:</div>'+ '</div>'+ '<div data-'+ $.mobile.ns +'role=\'content\' data-'+ $.mobile.ns +'theme=\'c\'><ul data-'+ $.mobile.ns +'role=\'listview\' data-'+ $.mobile.ns +'inset=\'true\'></ul></div>'+ '</div>' ) .appendTo( $.mobile.pageContainer ), menu = menuPage.find('ul'); //menu items $.each(themes, function( i ){ $('<li><a href="#" data-'+ $.mobile.ns +'rel="back">' + themes[ i ].charAt(0).toUpperCase() + themes[ i ].substr(1) + '</a></li>') .bind("vclick", function(){ addTheme( themes[i] ); menuPage.dialog( "close" ); return false; }) .appendTo(menu); }); //remover, adder function addTheme(theme){ $('head').append( '<link rel=\'stylesheet\' href=\''+ themesDir + theme +'/\' />' ); } //create page, listview menuPage.page(); }; })(jQuery);
JavaScript
//thx @elroyjetson for the code example // When map page opens get location and display map $('.page-map').live("pagecreate", function() { //boston :) var lat = 42.35843, lng = -71.059773; //try to get GPS coords if( navigator.geolocation ) { //redirect function for successful location function gpsSuccess(pos){ if( pos.coords ){ lat = pos.coords.latitude; lng = pos.coords.longitude; } else{ lat = pos.latitude; lng = pos.longitude; } } function gpsFail(){ //Geo-location is supported, but we failed to get your coordinates. Workaround here perhaps? } navigator.geolocation.getCurrentPosition(gpsSuccess, gpsFail, {enableHighAccuracy:true, maximumAge: 300000}); } /* if not supported, you might attempt to use google loader for lat,long $.getScript('http://www.google.com/jsapi?key=YOURAPIKEY',function(){ lat = google.loader.ClientLocation.latitude; lng = google.loader.ClientLocation.longitude; }); */ var latlng = new google.maps.LatLng(lat, lng); var myOptions = { zoom: 10, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map-canvas"),myOptions); });
JavaScript
/* * jQuery Mobile Framework : scrollview plugin * Copyright (c) 2010 Adobe Systems Incorporated - Kin Blas (jblas@adobe.com) * Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses. * Note: Code is in draft form and is subject to change */ (function($,window,document,undefined){ jQuery.widget( "mobile.scrollview", jQuery.mobile.widget, { options: { fps: 60, // Frames per second in msecs. direction: null, // "x", "y", or null for both. scrollDuration: 2000, // Duration of the scrolling animation in msecs. overshootDuration: 250, // Duration of the overshoot animation in msecs. snapbackDuration: 500, // Duration of the snapback animation in msecs. moveThreshold: 10, // User must move this many pixels in any direction to trigger a scroll. moveIntervalThreshold: 150, // Time between mousemoves must not exceed this threshold. scrollMethod: "translate", // "translate", "position", "scroll" startEventName: "scrollstart", updateEventName: "scrollupdate", stopEventName: "scrollstop", eventType: $.support.touch ? "touch" : "mouse", showScrollBars: true, pagingEnabled: false, delayedClickSelector: "a,input,textarea,select,button,.ui-btn", delayedClickEnabled: false }, _makePositioned: function($ele) { if ($ele.css("position") == "static") $ele.css("position", "relative"); }, _create: function() { this._$clip = $(this.element).addClass("ui-scrollview-clip"); var $child = this._$clip.children(); if ($child.length > 1) { $child = this._$clip.wrapInner("<div></div>").children(); } this._$view = $child.addClass("ui-scrollview-view"); this._$clip.css("overflow", this.options.scrollMethod === "scroll" ? "scroll" : "hidden"); this._makePositioned(this._$clip); this._$view.css("overflow", "hidden"); // Turn off our faux scrollbars if we are using native scrolling // to position the view. this.options.showScrollBars = this.options.scrollMethod === "scroll" ? false : this.options.showScrollBars; // We really don't need this if we are using a translate transformation // for scrolling. We set it just in case the user wants to switch methods // on the fly. this._makePositioned(this._$view); this._$view.css({ left: 0, top: 0 }); this._sx = 0; this._sy = 0; var direction = this.options.direction; this._hTracker = (direction !== "y") ? new MomentumTracker(this.options) : null; this._vTracker = (direction !== "x") ? new MomentumTracker(this.options) : null; this._timerInterval = 1000/this.options.fps; this._timerID = 0; var self = this; this._timerCB = function(){ self._handleMomentumScroll(); }; this._addBehaviors(); }, _startMScroll: function(speedX, speedY) { this._stopMScroll(); this._showScrollBars(); var keepGoing = false; var duration = this.options.scrollDuration; this._$clip.trigger(this.options.startEventName); var ht = this._hTracker; if (ht) { var c = this._$clip.width(); var v = this._$view.width(); ht.start(this._sx, speedX, duration, (v > c) ? -(v - c) : 0, 0); keepGoing = !ht.done(); } var vt = this._vTracker; if (vt) { var c = this._$clip.height(); var v = this._$view.height(); vt.start(this._sy, speedY, duration, (v > c) ? -(v - c) : 0, 0); keepGoing = keepGoing || !vt.done(); } if (keepGoing) this._timerID = setTimeout(this._timerCB, this._timerInterval); else this._stopMScroll(); }, _stopMScroll: function() { if (this._timerID) { this._$clip.trigger(this.options.stopEventName); clearTimeout(this._timerID); } this._timerID = 0; if (this._vTracker) this._vTracker.reset(); if (this._hTracker) this._hTracker.reset(); this._hideScrollBars(); }, _handleMomentumScroll: function() { var keepGoing = false; var v = this._$view; var x = 0, y = 0; var vt = this._vTracker; if (vt) { vt.update(); y = vt.getPosition(); keepGoing = !vt.done(); } var ht = this._hTracker; if (ht) { ht.update(); x = ht.getPosition(); keepGoing = keepGoing || !ht.done(); } this._setScrollPosition(x, y); this._$clip.trigger(this.options.updateEventName, [ { x: x, y: y } ]); if (keepGoing) this._timerID = setTimeout(this._timerCB, this._timerInterval); else this._stopMScroll(); }, _setScrollPosition: function(x, y) { this._sx = x; this._sy = y; var $v = this._$view; var sm = this.options.scrollMethod; switch (sm) { case "translate": setElementTransform($v, x + "px", y + "px"); break; case "position": $v.css({left: x + "px", top: y + "px"}); break; case "scroll": var c = this._$clip[0]; c.scrollLeft = -x; c.scrollTop = -y; break; } var $vsb = this._$vScrollBar; var $hsb = this._$hScrollBar; if ($vsb) { var $sbt = $vsb.find(".ui-scrollbar-thumb"); if (sm === "translate") setElementTransform($sbt, "0px", -y/$v.height() * $sbt.parent().height() + "px"); else $sbt.css("top", -y/$v.height()*100 + "%"); } if ($hsb) { var $sbt = $hsb.find(".ui-scrollbar-thumb"); if (sm === "translate") setElementTransform($sbt, -x/$v.width() * $sbt.parent().width() + "px", "0px"); else $sbt.css("left", -x/$v.width()*100 + "%"); } }, scrollTo: function(x, y, duration) { this._stopMScroll(); if (!duration) return this._setScrollPosition(x, y); x = -x; y = -y; var self = this; var start = getCurrentTime(); var efunc = $.easing["easeOutQuad"]; var sx = this._sx; var sy = this._sy; var dx = x - sx; var dy = y - sy; var tfunc = function(){ var elapsed = getCurrentTime() - start; if (elapsed >= duration) { self._timerID = 0; self._setScrollPosition(x, y); } else { var ec = efunc(elapsed/duration, elapsed, 0, 1, duration); self._setScrollPosition(sx + (dx * ec), sy + (dy * ec)); self._timerID = setTimeout(tfunc, self._timerInterval); } }; this._timerID = setTimeout(tfunc, this._timerInterval); }, getScrollPosition: function() { return { x: -this._sx, y: -this._sy }; }, _getScrollHierarchy: function() { var svh = []; this._$clip.parents(".ui-scrollview-clip").each(function(){ var d = $(this).jqmData("scrollview"); if (d) svh.unshift(d); }); return svh; }, _getAncestorByDirection: function(dir) { var svh = this._getScrollHierarchy(); var n = svh.length; while (0 < n--) { var sv = svh[n]; var svdir = sv.options.direction; if (!svdir || svdir == dir) return sv; } return null; }, _handleDragStart: function(e, ex, ey) { // Stop any scrolling of elements in our parent hierarcy. $.each(this._getScrollHierarchy(),function(i,sv){ sv._stopMScroll(); }); this._stopMScroll(); var c = this._$clip; var v = this._$view; if (this.options.delayedClickEnabled) { this._$clickEle = $(e.target).closest(this.options.delayedClickSelector); } this._lastX = ex; this._lastY = ey; this._doSnapBackX = false; this._doSnapBackY = false; this._speedX = 0; this._speedY = 0; this._directionLock = ""; this._didDrag = false; if (this._hTracker) { var cw = parseInt(c.css("width"), 10); var vw = parseInt(v.css("width"), 10); this._maxX = cw - vw; if (this._maxX > 0) this._maxX = 0; if (this._$hScrollBar) this._$hScrollBar.find(".ui-scrollbar-thumb").css("width", (cw >= vw ? "100%" : Math.floor(cw/vw*100)+ "%")); } if (this._vTracker) { var ch = parseInt(c.css("height"), 10); var vh = parseInt(v.css("height"), 10); this._maxY = ch - vh; if (this._maxY > 0) this._maxY = 0; if (this._$vScrollBar) this._$vScrollBar.find(".ui-scrollbar-thumb").css("height", (ch >= vh ? "100%" : Math.floor(ch/vh*100)+ "%")); } var svdir = this.options.direction; this._pageDelta = 0; this._pageSize = 0; this._pagePos = 0; if (this.options.pagingEnabled && (svdir === "x" || svdir === "y")) { this._pageSize = svdir === "x" ? cw : ch; this._pagePos = svdir === "x" ? this._sx : this._sy; this._pagePos -= this._pagePos % this._pageSize; } this._lastMove = 0; this._enableTracking(); // If we're using mouse events, we need to prevent the default // behavior to suppress accidental selection of text, etc. We // can't do this on touch devices because it will disable the // generation of "click" events. // // XXX: We should test if this has an effect on links! - kin if (this.options.eventType == "mouse" || this.options.delayedClickEnabled) e.preventDefault(); e.stopPropagation(); }, _propagateDragMove: function(sv, e, ex, ey, dir) { this._hideScrollBars(); this._disableTracking(); sv._handleDragStart(e,ex,ey); sv._directionLock = dir; sv._didDrag = this._didDrag; }, _handleDragMove: function(e, ex, ey) { this._lastMove = getCurrentTime(); var v = this._$view; var dx = ex - this._lastX; var dy = ey - this._lastY; var svdir = this.options.direction; if (!this._directionLock) { var x = Math.abs(dx); var y = Math.abs(dy); var mt = this.options.moveThreshold; if (x < mt && y < mt) { return false; } var dir = null; var r = 0; if (x < y && (x/y) < 0.5) { dir = "y"; } else if (x > y && (y/x) < 0.5) { dir = "x"; } if (svdir && dir && svdir != dir) { // This scrollview can't handle the direction the user // is attempting to scroll. Find an ancestor scrollview // that can handle the request. var sv = this._getAncestorByDirection(dir); if (sv) { this._propagateDragMove(sv, e, ex, ey, dir); return false; } } this._directionLock = svdir ? svdir : (dir ? dir : "none"); } var newX = this._sx; var newY = this._sy; if (this._directionLock !== "y" && this._hTracker) { var x = this._sx; this._speedX = dx; newX = x + dx; // Simulate resistance. this._doSnapBackX = false; if (newX > 0 || newX < this._maxX) { if (this._directionLock === "x") { var sv = this._getAncestorByDirection("x"); if (sv) { this._setScrollPosition(newX > 0 ? 0 : this._maxX, newY); this._propagateDragMove(sv, e, ex, ey, dir); return false; } } newX = x + (dx/2); this._doSnapBackX = true; } } if (this._directionLock !== "x" && this._vTracker) { var y = this._sy; this._speedY = dy; newY = y + dy; // Simulate resistance. this._doSnapBackY = false; if (newY > 0 || newY < this._maxY) { if (this._directionLock === "y") { var sv = this._getAncestorByDirection("y"); if (sv) { this._setScrollPosition(newX, newY > 0 ? 0 : this._maxY); this._propagateDragMove(sv, e, ex, ey, dir); return false; } } newY = y + (dy/2); this._doSnapBackY = true; } } if (this.options.pagingEnabled && (svdir === "x" || svdir === "y")) { if (this._doSnapBackX || this._doSnapBackY) this._pageDelta = 0; else { var opos = this._pagePos; var cpos = svdir === "x" ? newX : newY; var delta = svdir === "x" ? dx : dy; this._pageDelta = (opos > cpos && delta < 0) ? this._pageSize : ((opos < cpos && delta > 0) ? -this._pageSize : 0); } } this._didDrag = true; this._lastX = ex; this._lastY = ey; this._setScrollPosition(newX, newY); this._showScrollBars(); // Call preventDefault() to prevent touch devices from // scrolling the main window. // e.preventDefault(); return false; }, _handleDragStop: function(e) { var l = this._lastMove; var t = getCurrentTime(); var doScroll = l && (t - l) <= this.options.moveIntervalThreshold; var sx = (this._hTracker && this._speedX && doScroll) ? this._speedX : (this._doSnapBackX ? 1 : 0); var sy = (this._vTracker && this._speedY && doScroll) ? this._speedY : (this._doSnapBackY ? 1 : 0); var svdir = this.options.direction; if (this.options.pagingEnabled && (svdir === "x" || svdir === "y") && !this._doSnapBackX && !this._doSnapBackY) { var x = this._sx; var y = this._sy; if (svdir === "x") x = -this._pagePos + this._pageDelta; else y = -this._pagePos + this._pageDelta; this.scrollTo(x, y, this.options.snapbackDuration); } else if (sx || sy) this._startMScroll(sx, sy); else this._hideScrollBars(); this._disableTracking(); if (!this._didDrag && this.options.delayedClickEnabled && this._$clickEle.length) { this._$clickEle .trigger("mousedown") //.trigger("focus") .trigger("mouseup") .trigger("click"); } // If a view scrolled, then we need to absorb // the event so that links etc, underneath our // cursor/finger don't fire. return this._didDrag ? false : undefined; }, _enableTracking: function() { $(document).bind(this._dragMoveEvt, this._dragMoveCB); $(document).bind(this._dragStopEvt, this._dragStopCB); }, _disableTracking: function() { $(document).unbind(this._dragMoveEvt, this._dragMoveCB); $(document).unbind(this._dragStopEvt, this._dragStopCB); }, _showScrollBars: function() { var vclass = "ui-scrollbar-visible"; if (this._$vScrollBar) this._$vScrollBar.addClass(vclass); if (this._$hScrollBar) this._$hScrollBar.addClass(vclass); }, _hideScrollBars: function() { var vclass = "ui-scrollbar-visible"; if (this._$vScrollBar) this._$vScrollBar.removeClass(vclass); if (this._$hScrollBar) this._$hScrollBar.removeClass(vclass); }, _addBehaviors: function() { var self = this; if (this.options.eventType === "mouse") { this._dragStartEvt = "mousedown"; this._dragStartCB = function(e){ return self._handleDragStart(e, e.clientX, e.clientY); }; this._dragMoveEvt = "mousemove"; this._dragMoveCB = function(e){ return self._handleDragMove(e, e.clientX, e.clientY); }; this._dragStopEvt = "mouseup"; this._dragStopCB = function(e){ return self._handleDragStop(e); }; } else // "touch" { this._dragStartEvt = "touchstart"; this._dragStartCB = function(e) { var t = e.originalEvent.targetTouches[0]; return self._handleDragStart(e, t.pageX, t.pageY); }; this._dragMoveEvt = "touchmove"; this._dragMoveCB = function(e) { var t = e.originalEvent.targetTouches[0]; return self._handleDragMove(e, t.pageX, t.pageY); }; this._dragStopEvt = "touchend"; this._dragStopCB = function(e){ return self._handleDragStop(e); }; } this._$view.bind(this._dragStartEvt, this._dragStartCB); if (this.options.showScrollBars) { var $c = this._$clip; var prefix = "<div class=\"ui-scrollbar ui-scrollbar-"; var suffix = "\"><div class=\"ui-scrollbar-track\"><div class=\"ui-scrollbar-thumb\"></div></div></div>"; if (this._vTracker) { $c.append(prefix + "y" + suffix); this._$vScrollBar = $c.children(".ui-scrollbar-y"); } if (this._hTracker) { $c.append(prefix + "x" + suffix); this._$hScrollBar = $c.children(".ui-scrollbar-x"); } } } }); function setElementTransform($ele, x, y) { var v = "translate3d(" + x + "," + y + ", 0px)"; $ele.css({ "-moz-transform": v, "-webkit-transform": v, "transform": v }); } function MomentumTracker(options) { this.options = $.extend({}, options); this.easing = "easeOutQuad"; this.reset(); } var tstates = { scrolling: 0, overshot: 1, snapback: 2, done: 3 }; function getCurrentTime() { return (new Date()).getTime(); } $.extend(MomentumTracker.prototype, { start: function(pos, speed, duration, minPos, maxPos) { this.state = (speed != 0) ? ((pos < minPos || pos > maxPos) ? tstates.snapback : tstates.scrolling) : tstates.done; this.pos = pos; this.speed = speed; this.duration = (this.state == tstates.snapback) ? this.options.snapbackDuration : duration; this.minPos = minPos; this.maxPos = maxPos; this.fromPos = (this.state == tstates.snapback) ? this.pos : 0; this.toPos = (this.state == tstates.snapback) ? ((this.pos < this.minPos) ? this.minPos : this.maxPos) : 0; this.startTime = getCurrentTime(); }, reset: function() { this.state = tstates.done; this.pos = 0; this.speed = 0; this.minPos = 0; this.maxPos = 0; this.duration = 0; }, update: function() { var state = this.state; if (state == tstates.done) return this.pos; var duration = this.duration; var elapsed = getCurrentTime() - this.startTime; elapsed = elapsed > duration ? duration : elapsed; if (state == tstates.scrolling || state == tstates.overshot) { var dx = this.speed * (1 - $.easing[this.easing](elapsed/duration, elapsed, 0, 1, duration)); var x = this.pos + dx; var didOverShoot = (state == tstates.scrolling) && (x < this.minPos || x > this.maxPos); if (didOverShoot) x = (x < this.minPos) ? this.minPos : this.maxPos; this.pos = x; if (state == tstates.overshot) { if (elapsed >= duration) { this.state = tstates.snapback; this.fromPos = this.pos; this.toPos = (x < this.minPos) ? this.minPos : this.maxPos; this.duration = this.options.snapbackDuration; this.startTime = getCurrentTime(); elapsed = 0; } } else if (state == tstates.scrolling) { if (didOverShoot) { this.state = tstates.overshot; this.speed = dx / 2; this.duration = this.options.overshootDuration; this.startTime = getCurrentTime(); } else if (elapsed >= duration) this.state = tstates.done; } } else if (state == tstates.snapback) { if (elapsed >= duration) { this.pos = this.toPos; this.state = tstates.done; } else this.pos = this.fromPos + ((this.toPos - this.fromPos) * $.easing[this.easing](elapsed/duration, elapsed, 0, 1, duration)); } return this.pos; }, done: function() { return this.state == tstates.done; }, getPosition: function(){ return this.pos; } }); jQuery.widget( "mobile.scrolllistview", jQuery.mobile.scrollview, { options: { direction: "y" }, _create: function() { $.mobile.scrollview.prototype._create.call(this); // Cache the dividers so we don't have to search for them everytime the // view is scrolled. // // XXX: Note that we need to update this cache if we ever support lists // that can dynamically update their content. this._$dividers = this._$view.find(":jqmData(role='list-divider')"); this._lastDivider = null; }, _setScrollPosition: function(x, y) { // Let the view scroll like it normally does. $.mobile.scrollview.prototype._setScrollPosition.call(this, x, y); y = -y; // Find the dividers for the list. var $divs = this._$dividers; var cnt = $divs.length; var d = null; var dy = 0; var nd = null; for (var i = 0; i < cnt; i++) { nd = $divs.get(i); var t = nd.offsetTop; if (y >= t) { d = nd; dy = t; } else if (d) break; } // If we found a divider to move position it at the top of the // clip view. if (d) { var h = d.offsetHeight; var mxy = (d != nd) ? nd.offsetTop : (this._$view.get(0).offsetHeight); if (y + h >= mxy) y = (mxy - h) - dy; else y = y - dy; // XXX: Need to convert this over to using $().css() and supporting the non-transform case. var ld = this._lastDivider; if (ld && d != ld) { setElementTransform($(ld), 0, 0); } setElementTransform($(d), 0, y + "px"); this._lastDivider = d; } } }); })(jQuery,window,document); // End Component
JavaScript
function ResizePageContentHeight(page) { var $page = $(page), $content = $page.children( ".ui-content" ), hh = $page.children( ".ui-header" ).outerHeight() || 0, fh = $page.children( ".ui-footer" ).outerHeight() || 0, pt = parseFloat($content.css( "padding-top" )), pb = parseFloat($content.css( "padding-bottom" )), wh = window.innerHeight; $content.height(wh - (hh + fh) - (pt + pb)); } $( ":jqmData(role='page')" ).live( "pageshow", function(event) { var $page = $( this ); // For the demos that use this script, we want the content area of each // page to be scrollable in the 'y' direction. $page.find( ".ui-content" ).attr( "data-" + $.mobile.ns + "scroll", "y" ); // This code that looks for [data-scroll] will eventually be folded // into the jqm page processing code when scrollview support is "official" // instead of "experimental". $page.find( ":jqmData(scroll):not(.ui-scrollview-clip)" ).each(function () { var $this = $( this ); // XXX: Remove this check for ui-scrolllistview once we've // integrated list divider support into the main scrollview class. if ( $this.hasClass( "ui-scrolllistview" ) ) { $this.scrolllistview(); } else { var st = $this.jqmData( "scroll" ) + "", paging = st && st.search(/^[xy]p$/) != -1, dir = st && st.search(/^[xy]/) != -1 ? st.charAt(0) : null, opts = { direction: dir || undefined, paging: paging || undefined, scrollMethod: $this.jqmData("scroll-method") || undefined }; $this.scrollview( opts ); } }); // For the demos, we want to make sure the page being shown has a content // area that is sized to fit completely within the viewport. This should // also handle the case where pages are loaded dynamically. ResizePageContentHeight( event.target ); }); $( window ).bind( "orientationchange", function( event ) { ResizePageContentHeight( $( ".ui-page" ) ); });
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, 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; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, 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; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, 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; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, 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; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, 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; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; 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; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; 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; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); 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; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) 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; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, 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; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }); /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */
JavaScript
/* * Copy of http://github.com/nje/jquery-tmpl/raw/master/jquery.tmpl.js at f827fb68417bc14ab9f6ae889421d5fea4cb2859 * jQuery Templating Plugin * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. */ (function( jQuery, undefined ){ var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = []; function newTmplItem( options, parentItem, fn, data ) { // Returns a template item data structure for a new rendered instance of a template (a 'template item'). // The content field is a hierarchical array of strings and nested items (to be // removed and replaced by nodes field of dom elements, once inserted in DOM). var newItem = { data: data || (parentItem ? parentItem.data : {}), _wrap: parentItem ? parentItem._wrap : null, tmpl: null, parent: parentItem || null, nodes: [], calls: tiCalls, nest: tiNest, wrap: tiWrap, html: tiHtml, update: tiUpdate }; if ( options ) { jQuery.extend( newItem, options, { nodes: [], parent: parentItem } ); } if ( fn ) { // Build the hierarchical content to be used during insertion into DOM newItem.tmpl = fn; newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem ); newItem.key = ++itemKey; // Keep track of new template item, until it is stored as jQuery Data on DOM element (stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem; } return newItem; } // Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core). jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems, parent = this.length === 1 && this[0].parentNode; appendToTmplItems = newTmplItems || {}; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); ret = this; } else { for ( i = 0, l = insert.length; i < l; i++ ) { cloneIndex = i; elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ original ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } cloneIndex = 0; ret = this.pushStack( ret, name, insert.selector ); } tmplItems = appendToTmplItems; appendToTmplItems = null; jQuery.tmpl.complete( tmplItems ); return ret; }; }); jQuery.fn.extend({ // Use first wrapped element as template markup. // Return wrapped set of template items, obtained by rendering template against data. tmpl: function( data, options, parentItem ) { return jQuery.tmpl( this[0], data, options, parentItem ); }, // Find which rendered template item the first wrapped DOM element belongs to tmplItem: function() { return jQuery.tmplItem( this[0] ); }, // Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template. template: function( name ) { return jQuery.template( name, this[0] ); }, domManip: function( args, table, callback, options ) { // This appears to be a bug in the appendTo, etc. implementation // it should be doing .call() instead of .apply(). See #6227 if ( args[0] && args[0].nodeType ) { var dmArgs = jQuery.makeArray( arguments ), argsLength = args.length, i = 0, tmplItem; while ( i < argsLength && !(tmplItem = jQuery.data( args[i++], "tmplItem" ))) {} if ( argsLength > 1 ) { dmArgs[0] = [jQuery.makeArray( args )]; } if ( tmplItem && cloneIndex ) { dmArgs[2] = function( fragClone ) { // Handler called by oldManip when rendered template has been inserted into DOM. jQuery.tmpl.afterManip( this, fragClone, callback ); }; } oldManip.apply( this, dmArgs ); } else { oldManip.apply( this, arguments ); } cloneIndex = 0; if ( !appendToTmplItems ) { jQuery.tmpl.complete( newTmplItems ); } return this; } }); jQuery.extend({ // Return wrapped set of template items, obtained by rendering template against data. tmpl: function( tmpl, data, options, parentItem ) { var ret, topLevel = !parentItem; if ( topLevel ) { // This is a top-level tmpl call (not from a nested template using {{tmpl}}) parentItem = topTmplItem; tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl ); wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level } else if ( !tmpl ) { // The template item is already associated with DOM - this is a refresh. // Re-evaluate rendered template for the parentItem tmpl = parentItem.tmpl; newTmplItems[parentItem.key] = parentItem; parentItem.nodes = []; if ( parentItem.wrapped ) { updateWrapped( parentItem, parentItem.wrapped ); } // Rebuild, without creating a new template item return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) )); } if ( !tmpl ) { return []; // Could throw... } if ( typeof data === "function" ) { data = data.call( parentItem || {} ); } if ( options && options.wrapped ) { updateWrapped( options, options.wrapped ); } ret = jQuery.isArray( data ) ? jQuery.map( data, function( dataItem ) { return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null; }) : [ newTmplItem( options, parentItem, tmpl, data ) ]; return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret; }, // Return rendered template item for an element. tmplItem: function( elem ) { var tmplItem; if ( elem instanceof jQuery ) { elem = elem[0]; } while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {} return tmplItem || topTmplItem; }, // Set: // Use $.template( name, tmpl ) to cache a named template, // where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc. // Use $( "selector" ).template( name ) to provide access by name to a script block template declaration. // Get: // Use $.template( name ) to access a cached template. // Also $( selectorToScriptBlock ).template(), or $.template( null, templateString ) // will return the compiled template, without adding a name reference. // If templateString includes at least one HTML tag, $.template( templateString ) is equivalent // to $.template( null, templateString ) template: function( name, tmpl ) { if (tmpl) { // Compile template and associate with name if ( typeof tmpl === "string" ) { // This is an HTML string being passed directly in. tmpl = buildTmplFn( tmpl ) } else if ( tmpl instanceof jQuery ) { tmpl = tmpl[0] || {}; } if ( tmpl.nodeType ) { // If this is a template block, use cached copy, or generate tmpl function and cache. tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML )); } return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl; } // Return named compiled template return name ? (typeof name !== "string" ? jQuery.template( null, name ): (jQuery.template[name] || // If not in map, treat as a selector. (If integrated with core, use quickExpr.exec) jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null; }, encode: function( text ) { // Do HTML encoding replacing < > & and ' and " by corresponding entities. return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;"); } }); jQuery.extend( jQuery.tmpl, { tag: { "tmpl": { _default: { $2: "null" }, open: "if($notnull_1){_=_.concat($item.nest($1,$2));}" // tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions) // This means that {{tmpl foo}} treats foo as a template (which IS a function). // Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}. }, "wrap": { _default: { $2: "null" }, open: "$item.calls(_,$1,$2);_=[];", close: "call=$item.calls();_=call._.concat($item.wrap(call,_));" }, "each": { _default: { $2: "$index, $value" }, open: "if($notnull_1){$.each($1a,function($2){with(this){", close: "}});}" }, "if": { open: "if(($notnull_1) && $1a){", close: "}" }, "else": { _default: { $1: "true" }, open: "}else if(($notnull_1) && $1a){" }, "html": { // Unecoded expression evaluation. open: "if($notnull_1){_.push($1a);}" }, "=": { // Encoded expression evaluation. Abbreviated form is ${}. _default: { $1: "$data" }, open: "if($notnull_1){_.push($.encode($1a));}" }, "!": { // Comment tag. Skipped by parser open: "" } }, // This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events complete: function( items ) { newTmplItems = {}; }, // Call this from code which overrides domManip, or equivalent // Manage cloning/storing template items etc. afterManip: function afterManip( elem, fragClone, callback ) { // Provides cloned fragment ready for fixup prior to and after insertion into DOM var content = fragClone.nodeType === 11 ? jQuery.makeArray(fragClone.childNodes) : fragClone.nodeType === 1 ? [fragClone] : []; // Return fragment to original caller (e.g. append) for DOM insertion callback.call( elem, fragClone ); // Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data. storeTmplItems( content ); cloneIndex++; } }); //========================== Private helper functions, used by code above ========================== function build( tmplItem, nested, content ) { // Convert hierarchical content into flat string array // and finally return array of fragments ready for DOM insertion var frag, ret = content ? jQuery.map( content, function( item ) { return (typeof item === "string") ? // Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM. (tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) : // This is a child template item. Build nested template. build( item, tmplItem, item._ctnt ); }) : // If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}. tmplItem; if ( nested ) { return ret; } // top-level template ret = ret.join(""); // Support templates which have initial or final text nodes, or consist only of text // Also support HTML entities within the HTML markup. ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) { frag = jQuery( middle ).get(); storeTmplItems( frag ); if ( before ) { frag = unencode( before ).concat(frag); } if ( after ) { frag = frag.concat(unencode( after )); } }); return frag ? frag : unencode( ret ); } function unencode( text ) { // Use createElement, since createTextNode will not render HTML entities correctly var el = document.createElement( "div" ); el.innerHTML = text; return jQuery.makeArray(el.childNodes); } // Generate a reusable function that will serve to render a template against data function buildTmplFn( markup ) { return new Function("jQuery","$item", "var $=jQuery,call,_=[],$data=$item.data;" + // Introduce the data as local variables using with(){} "with($data){_.push('" + // Convert the template into pure JavaScript jQuery.trim(markup) .replace( /([\\'])/g, "\\$1" ) .replace( /[\r\t\n]/g, " " ) .replace( /\$\{([^\}]*)\}/g, "{{= $1}}" ) .replace( /\{\{(\/?)(\w+|.)(?:\(((?:.(?!\}\}))*?)?\))?(?:\s+(.*?)?)?(\((.*?)\))?\s*\}\}/g, function( all, slash, type, fnargs, target, parens, args ) { var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect; if ( !tag ) { throw "Template command not found: " + type; } def = tag._default || []; if ( parens && !/\w$/.test(target)) { target += parens; parens = ""; } if ( target ) { target = unescape( target ); args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : ""); // Support for target being things like a.toLowerCase(); // In that case don't call with template item as 'this' pointer. Just evaluate... expr = parens ? (target.indexOf(".") > -1 ? target + parens : ("(" + target + ").call($item" + args)) : target; exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))"; } else { exprAutoFnDetect = expr = def.$1 || "null"; } fnargs = unescape( fnargs ); return "');" + tag[ slash ? "close" : "open" ] .split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" ) .split( "$1a" ).join( exprAutoFnDetect ) .split( "$1" ).join( expr ) .split( "$2" ).join( fnargs ? fnargs.replace( /\s*([^\(]+)\s*(\((.*?)\))?/g, function( all, name, parens, params ) { params = params ? ("," + params + ")") : (parens ? ")" : ""); return params ? ("(" + name + ").call($item" + params) : all; }) : (def.$2||"") ) + "_.push('"; }) + "');}return _;" ); } function updateWrapped( options, wrapped ) { // Build the wrapped content. options._wrap = build( options, true, // Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string. jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()] ).join(""); } function unescape( args ) { return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null; } function outerHtml( elem ) { var div = document.createElement("div"); div.appendChild( elem.cloneNode(true) ); return div.innerHTML; } // Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance. function storeTmplItems( content ) { var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m; for ( i = 0, l = content.length; i < l; i++ ) { if ( (elem = content[i]).nodeType !== 1 ) { continue; } elems = elem.getElementsByTagName("*"); for ( m = elems.length - 1; m >= 0; m-- ) { processItemKey( elems[m] ); } processItemKey( elem ); } function processItemKey( el ) { var pntKey, pntNode = el, pntItem, tmplItem, key; // Ensure that each rendered template inserted into the DOM has its own template item, if ( (key = el.getAttribute( tmplItmAtt ))) { while ((pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { } if ( pntKey !== key ) { // The next ancestor with a _tmplitem expando is on a different key than this one. // So this is a top-level element within this template item pntNode = pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0); if ( !(tmplItem = newTmplItems[key]) ) { // The item is for wrapped content, and was copied from the temporary parent wrappedItem. tmplItem = wrappedItems[key]; tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode], null, true ); tmplItem.key = ++itemKey; newTmplItems[itemKey] = tmplItem; } if ( cloneIndex ) { cloneTmplItem( key ); } } el.removeAttribute( tmplItmAtt ); } else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) { // This was a rendered element, cloned during append or appendTo etc. // TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem. cloneTmplItem( tmplItem.key ); newTmplItems[tmplItem.key] = tmplItem; pntNode = jQuery.data( el.parentNode, "tmplItem" ); pntNode = pntNode ? pntNode.key : 0; } if ( tmplItem ) { pntItem = tmplItem; // Find the template item of the parent element. // (Using !=, not !==, since pntItem.key is number, and pntNode may be a string) while ( pntItem && pntItem.key != pntNode ) { // Add this element as a top-level node for this rendered template item, as well as for any // ancestor items between this item and the item of its parent element pntItem.nodes.push( el ); pntItem = pntItem.parent; } // Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering... delete tmplItem._ctnt; delete tmplItem._wrap; // Store template item as jQuery data on the element jQuery.data( el, "tmplItem", tmplItem ); } function cloneTmplItem( key ) { key = key + keySuffix; tmplItem = newClonedItems[key] = (newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent, null, true )); } } } //---- Helper functions for template item ---- function tiCalls( content, tmpl, data, options ) { if ( !content ) { return stack.pop(); } stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options }); } function tiNest( tmpl, data, options ) { // nested template, using {{tmpl}} tag return jQuery.tmpl( jQuery.template( tmpl ), data, options, this ); } function tiWrap( call, wrapped ) { // nested template, using {{wrap}} tag var options = call.options || {}; options.wrapped = wrapped; // Apply the template, which may incorporate wrapped content, return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item ); } function tiHtml( filter, textOnly ) { var wrapped = this._wrap; return jQuery.map( jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ), function(e) { return textOnly ? e.innerText || e.textContent : e.outerHTML || outerHtml(e); }); } function tiUpdate() { var coll = this.nodes; jQuery.tmpl( null, null, null, this).insertBefore( coll[0] ); jQuery( coll ).remove(); } })( jQuery );
JavaScript
$(function() { var symbols = { "USD": "$", "EUR": "&euro;", "GBP": "&pound;", "Miles": "m", "Kilometer": "km", "inch": "\"", "centimeter": "cm" }; function list() { var ul = $( "#conversions" ).empty(), ulEdit = $( "#edit-conversions" ).empty(); $.each( all, function( index, conversion ) { // if last update was less then a minute ago, don't update if ( conversion.type === "currency" && !conversion.rate || conversion.updated && conversion.updated + 60000 < +new Date) { var self = conversion; var url = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + conversion.from + conversion.to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&diagnostics=true&callback=?"; $.getJSON( url, function( result ) { self.rate = parseFloat( result.query.results.row.rate ); $( "#term" ).keyup(); self.updated = +new Date; conversions.store(); }); } $( "#conversion-field" ).tmpl( conversion, { symbols: symbols }).appendTo( ul ); $( "#conversion-edit-field" ).tmpl( conversion, { symbols: symbols }).appendTo( ulEdit ); }); ul.add(ulEdit).listview("refresh"); $( "#term" ).keyup(); } var all = conversions.all(); $( "#term" ).keyup(function() { var value = this.value; $.each( all, function( index, conversion ) { $( "#" + conversion.from + conversion.to ).text( conversion.rate ? Math.ceil( value * conversion.rate * 100 ) / 100 : "Rate not available, yet." ); }); }).focus(); list(); $( "form" ).submit(function() { $( "#term" ).blur(); return false; }); $( "#add" ).click(function() { all.push({ type: "currency", from: $( "#currency-options-from" ).val(), to: $( "#currency-options-to" ).val() }); conversions.store(); list(); }); $( "#clear" ).click(function() { conversions.clear(); list(); return false; }); $( "#restore" ).click(function() { conversions.restore(); list(); return false; }); $( "#edit-conversions" ).click(function( event ) { var target = $( event.target ).closest( ".deletebutton" ); if ( target.length ) { conversions.remove( target.prev( "label" ).attr( "for" ) ); list(); } return false; }); });
JavaScript
(function() { var defaults = [ { type: "currency", from: "USD", to: "EUR" }, { type: "currency", from: "GBP", to: "EUR" } // TODO add back in as defaults once its possible to add other conversions, not just currencies /*, { type: "distance", from: "Miles", to: "Kilometer", rate: 1.609344 }, { type: "distance", from: "inch", to: "centimeter", rate: 2.54 }*/ ]; // TODO fallback to whatever else when localStorage isn't available function get() { return JSON.parse( localStorage.getItem( "conversions" ) ); } function set( value ) { localStorage.setItem( "conversions", JSON.stringify( value ) ); } var conversions = get( "conversions" ); if ( !conversions ) { conversions = defaults.slice(); set( conversions ); } window.conversions = { store: function() { set( conversions ); }, all: function() { return conversions; }, clear: function() { conversions.length = 0; this.store(); }, restore: function() { conversions.length = 0; $.extend( conversions, defaults ); this.store(); }, remove: function( tofrom ) { $.each( conversions, function( index, conversion ) { if ( ( conversion.from + conversion.to ) === tofrom ) { conversions.splice( index, 1 ); return false; } }); this.store(); } }; })();
JavaScript
/* * StringBuffer class */ function StringBuffer() { this.buffer = []; } StringBuffer.prototype.append = function append (string) { this.buffer.push(string); return this; }; StringBuffer.prototype.toString = function toString () { return this.buffer.join(""); }; /* * Strip html tags */ function stripTags (str) { return str.replace(/<[^>].*?>/g,""); } /* * Display json with better look */ function formatJson (str) { var tab = 0; var buf = new StringBuffer(); for (var i = 0; i < str.length; i++) { var char = str.charAt(i); if (char == '{' || char == '[') { tab++; char = char + "\n"; for (var j = 0; j < tab; j++) char = char + "\t"; } if (char == '}' || char == ']') { tab--; for (var j = 0; j < tab; j++) char = "\t" + char; char = "\n" + char; } if (char == ',') { char = char + "\n"; for (var j = 0; j < tab; j++) char = char + "\t"; } buf.append(char); } return buf.toString(); }
JavaScript
/*! * jQuery Mobile v1.0b2 * http://jquerymobile.com/ * * Copyright 2010, jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ /*! * jQuery UI Widget @VERSION * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Widget */ (function( $, undefined ) { // jQuery 1.4+ if ( $.cleanData ) { var _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { $( elem ).triggerHandler( "remove" ); } _cleanData( elems ); }; } else { var _remove = $.fn.remove; $.fn.remove = function( selector, keepData ) { return this.each(function() { if ( !keepData ) { if ( !selector || $.filter( selector, [ this ] ).length ) { $( "*", this ).add( [ this ] ).each(function() { $( this ).triggerHandler( "remove" ); }); } } return _remove.call( $(this), selector, keepData ); }); }; } $.widget = function( name, base, prototype ) { var namespace = name.split( "." )[ 0 ], fullName; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName ] = function( elem ) { return !!$.data( elem, name ); }; $[ namespace ] = $[ namespace ] || {}; $[ namespace ][ name ] = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this._createWidget( options, element ); } }; var basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from // $.each( basePrototype, function( key, val ) { // if ( $.isPlainObject(val) ) { // basePrototype[ key ] = $.extend( {}, val ); // } // }); basePrototype.options = $.extend( true, {}, basePrototype.options ); $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { namespace: namespace, widgetName: name, widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, widgetBaseClass: fullName }, prototype ); $.widget.bridge( name, $[ namespace ][ name ] ); }; $.widget.bridge = function( name, object ) { $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = Array.prototype.slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.extend.apply( null, [ true, options ].concat(args) ) : options; // prevent calls to internal methods if ( isMethodCall && options.charAt( 0 ) === "_" ) { return returnValue; } if ( isMethodCall ) { this.each(function() { var instance = $.data( this, name ); if ( !instance ) { throw "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'"; } if ( !$.isFunction( instance[options] ) ) { throw "no such method '" + options + "' for " + name + " widget instance"; } var methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, name ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, name, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this._createWidget( options, element ); } }; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", options: { disabled: false }, _createWidget: function( options, element ) { // $.widget.bridge stores the plugin instance, but we do it anyway // so that it's stored even before the _create function runs $.data( element, this.widgetName, this ); this.element = $( element ); this.options = $.extend( true, {}, this.options, this._getCreateOptions(), options ); var self = this; this.element.bind( "remove." + this.widgetName, function() { self.destroy(); }); this._create(); this._trigger( "create" ); this._init(); }, _getCreateOptions: function() { var options = {}; if ( $.metadata ) { options = $.metadata.get( element )[ this.widgetName ]; } return options; }, _create: function() {}, _init: function() {}, destroy: function() { this.element .unbind( "." + this.widgetName ) .removeData( this.widgetName ); this.widget() .unbind( "." + this.widgetName ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetBaseClass + "-disabled " + "ui-state-disabled" ); }, widget: function() { return this.element; }, option: function( key, value ) { var options = key; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.extend( {}, this.options ); } if (typeof key === "string" ) { if ( value === undefined ) { return this.options[ key ]; } options = {}; options[ key ] = value; } this._setOptions( options ); return this; }, _setOptions: function( options ) { var self = this; $.each( options, function( key, value ) { self._setOption( key, value ); }); return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() [ value ? "addClass" : "removeClass"]( this.widgetBaseClass + "-disabled" + " " + "ui-state-disabled" ) .attr( "aria-disabled", value ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _trigger: function( type, event, data ) { var callback = this.options[ type ]; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); data = data || {}; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( event.originalEvent ) { for ( var i = $.event.props.length, prop; i; ) { prop = $.event.props[ --i ]; event[ prop ] = event.originalEvent[ prop ]; } } this.element.trigger( event, data ); return !( $.isFunction(callback) && callback.call( this.element[0], event, data ) === false || event.isDefaultPrevented() ); } }; })( jQuery ); /* * jQuery Mobile Framework : widget factory extentions for mobile * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.widget", { _getCreateOptions: function() { var elem = this.element, options = {}; $.each( this.options, function( option ) { var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) { return "-" + c.toLowerCase(); }) ); if ( value !== undefined ) { options[ option ] = value; } }); return options; } }); })( jQuery ); /* * jQuery Mobile Framework : resolution and CSS media query related helpers and behavior * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { var $window = $( window ), $html = $( "html" ); /* $.mobile.media method: pass a CSS media type or query and get a bool return note: this feature relies on actual media query support for media queries, though types will work most anywhere examples: $.mobile.media('screen') //>> tests for screen media type $.mobile.media('screen and (min-width: 480px)') //>> tests for screen media type with window width > 480px $.mobile.media('@media screen and (-webkit-min-device-pixel-ratio: 2)') //>> tests for webkit 2x pixel ratio (iPhone 4) */ $.mobile.media = (function() { // TODO: use window.matchMedia once at least one UA implements it var cache = {}, testDiv = $( "<div id='jquery-mediatest'>" ), fakeBody = $( "<body>" ).append( testDiv ); return function( query ) { if ( !( query in cache ) ) { var styleBlock = document.createElement( "style" ), cssrule = "@media " + query + " { #jquery-mediatest { position:absolute; } }"; //must set type for IE! styleBlock.type = "text/css"; if ( styleBlock.styleSheet ){ styleBlock.styleSheet.cssText = cssrule; } else { styleBlock.appendChild( document.createTextNode(cssrule) ); } $html.prepend( fakeBody ).prepend( styleBlock ); cache[ query ] = testDiv.css( "position" ) === "absolute"; fakeBody.add( styleBlock ).remove(); } return cache[ query ]; }; })(); })(jQuery);/* * jQuery Mobile Framework : support tests * Copyright (c) jQuery Project * Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses. */ (function( $, undefined ) { var fakeBody = $( "<body>" ).prependTo( "html" ), fbCSS = fakeBody[ 0 ].style, vendors = [ "webkit", "moz", "o" ], webos = "palmGetResource" in window, //only used to rule out scrollTop bb = window.blackberry; //only used to rule out box shadow, as it's filled opaque on BB // thx Modernizr function propExists( prop ) { var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ), props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " ); for ( var v in props ){ if ( fbCSS[ v ] !== undefined ) { return true; } } } // Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting ) function baseTagTest() { var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/", base = $( "head base" ), fauxEle = null, href = "", link, rebase; if ( !base.length ) { base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" ); } else { href = base.attr( "href" ); } link = $( "<a href='testurl'></a>" ).prependTo( fakeBody ); rebase = link[ 0 ].href; base[ 0 ].href = href ? href : location.pathname; if ( fauxEle ) { fauxEle.remove(); } return rebase.indexOf( fauxBase ) === 0; } // non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683 // allows for inclusion of IE 6+, including Windows Mobile 7 $.mobile.browser = {}; $.mobile.browser.ie = (function() { var v = 3, div = document.createElement( "div" ), a = div.all || []; while ( div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->", a[ 0 ] ); return v > 4 ? v : !v; })(); $.extend( $.support, { orientation: "orientation" in window, touch: "ontouchend" in document, cssTransitions: "WebKitTransitionEvent" in window, pushState: !!history.pushState, mediaquery: $.mobile.media( "only all" ), cssPseudoElement: !!propExists( "content" ), boxShadow: !!propExists( "boxShadow" ) && !bb, scrollTop: ( "pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[ 0 ] ) && !webos, dynamicBaseTag: baseTagTest(), // TODO: This is a weak test. We may want to beef this up later. eventCapture: "addEventListener" in document }); fakeBody.remove(); // $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian) // or that generally work better browsing in regular http for full page refreshes (Opera Mini) // Note: This detection below is used as a last resort. // We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible var nokiaLTE7_3 = (function(){ var ua = window.navigator.userAgent; //The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older return ua.indexOf( "Nokia" ) > -1 && ( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) && ua.indexOf( "AppleWebKit" ) > -1 && ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ ); })(); $.mobile.ajaxBlacklist = // BlackBerry browsers, pre-webkit window.blackberry && !window.WebKitPoint || // Opera Mini window.operamini && Object.prototype.toString.call( window.operamini ) === "[object OperaMini]" || // Symbian webkits pre 7.3 nokiaLTE7_3; // Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices // to render the stylesheets when they're referenced before this script, as we'd recommend doing. // This simply reappends the CSS in place, which for some reason makes it apply if ( nokiaLTE7_3 ) { $(function() { $( "head link[rel=stylesheet]" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" ); }); } // For ruling out shadows via css if ( !$.support.boxShadow ) { $( "html" ).addClass( "ui-mobile-nosupport-boxshadow" ); } })( jQuery );/* * jQuery Mobile Framework : "mouse" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ // This plugin is an experiment for abstracting away the touch and mouse // events so that developers don't have to worry about which method of input // the device their document is loaded on supports. // // The idea here is to allow the developer to register listeners for the // basic mouse events, such as mousedown, mousemove, mouseup, and click, // and the plugin will take care of registering the correct listeners // behind the scenes to invoke the listener at the fastest possible time // for that device, while still retaining the order of event firing in // the traditional mouse environment, should multiple handlers be registered // on the same element for different events. // // The current version exposes the following virtual events to jQuery bind methods: // "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel" (function( $, window, document, undefined ) { var dataPropertyName = "virtualMouseBindings", touchTargetPropertyName = "virtualTouchID", virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ), touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ), activeDocHandlers = {}, resetTimerID = 0, startX = 0, startY = 0, didScroll = false, clickBlockList = [], blockMouseTriggers = false, blockTouchTriggers = false, eventCaptureSupported = $.support.eventCapture, $document = $( document ), nextTouchID = 1, lastTouchID = 0; $.vmouse = { moveDistanceThreshold: 10, clickDistanceThreshold: 10, resetTimerDuration: 1500 }; function getNativeEvent( event ) { while ( event && typeof event.originalEvent !== "undefined" ) { event = event.originalEvent; } return event; } function createVirtualEvent( event, eventType ) { var t = event.type, oe, props, ne, prop, ct, touch, i, j; event = $.Event(event); event.type = eventType; oe = event.originalEvent; props = $.event.props; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( oe ) { for ( i = props.length, prop; i; ) { prop = props[ --i ]; event[ prop ] = oe[ prop ]; } } if ( t.search(/^touch/) !== -1 ) { ne = getNativeEvent( oe ); t = ne.touches; ct = ne.changedTouches; touch = ( t && t.length ) ? t[0] : ( (ct && ct.length) ? ct[ 0 ] : undefined ); if ( touch ) { for ( j = 0, len = touchEventProps.length; j < len; j++){ prop = touchEventProps[ j ]; event[ prop ] = touch[ prop ]; } } } return event; } function getVirtualBindingFlags( element ) { var flags = {}, b, k; while ( element ) { b = $.data( element, dataPropertyName ); for ( k in b ) { if ( b[ k ] ) { flags[ k ] = flags.hasVirtualBinding = true; } } element = element.parentNode; } return flags; } function getClosestElementWithVirtualBinding( element, eventType ) { var b; while ( element ) { b = $.data( element, dataPropertyName ); if ( b && ( !eventType || b[ eventType ] ) ) { return element; } element = element.parentNode; } return null; } function enableTouchBindings() { blockTouchTriggers = false; } function disableTouchBindings() { blockTouchTriggers = true; } function enableMouseBindings() { lastTouchID = 0; clickBlockList.length = 0; blockMouseTriggers = false; // When mouse bindings are enabled, our // touch bindings are disabled. disableTouchBindings(); } function disableMouseBindings() { // When mouse bindings are disabled, our // touch bindings are enabled. enableTouchBindings(); } function startResetTimer() { clearResetTimer(); resetTimerID = setTimeout(function(){ resetTimerID = 0; enableMouseBindings(); }, $.vmouse.resetTimerDuration ); } function clearResetTimer() { if ( resetTimerID ){ clearTimeout( resetTimerID ); resetTimerID = 0; } } function triggerVirtualEvent( eventType, event, flags ) { var defaultPrevented = false, ve; if ( ( flags && flags[ eventType ] ) || ( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) { ve = createVirtualEvent( event, eventType ); $( event.target).trigger( ve ); defaultPrevented = ve.isDefaultPrevented(); } return defaultPrevented; } function mouseEventCallback( event ) { var touchID = $.data(event.target, touchTargetPropertyName); if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ){ triggerVirtualEvent( "v" + event.type, event ); } } function handleTouchStart( event ) { var touches = getNativeEvent( event ).touches, target, flags; if ( touches && touches.length === 1 ) { target = event.target; flags = getVirtualBindingFlags( target ); if ( flags.hasVirtualBinding ) { lastTouchID = nextTouchID++; $.data( target, touchTargetPropertyName, lastTouchID ); clearResetTimer(); disableMouseBindings(); didScroll = false; var t = getNativeEvent( event ).touches[ 0 ]; startX = t.pageX; startY = t.pageY; triggerVirtualEvent( "vmouseover", event, flags ); triggerVirtualEvent( "vmousedown", event, flags ); } } } function handleScroll( event ) { if ( blockTouchTriggers ) { return; } if ( !didScroll ) { triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) ); } didScroll = true; startResetTimer(); } function handleTouchMove( event ) { if ( blockTouchTriggers ) { return; } var t = getNativeEvent( event ).touches[ 0 ], didCancel = didScroll, moveThreshold = $.vmouse.moveDistanceThreshold; didScroll = didScroll || ( Math.abs(t.pageX - startX) > moveThreshold || Math.abs(t.pageY - startY) > moveThreshold ), flags = getVirtualBindingFlags( event.target ); if ( didScroll && !didCancel ) { triggerVirtualEvent( "vmousecancel", event, flags ); } triggerVirtualEvent( "vmousemove", event, flags ); startResetTimer(); } function handleTouchEnd( event ) { if ( blockTouchTriggers ) { return; } disableTouchBindings(); var flags = getVirtualBindingFlags( event.target ), t; triggerVirtualEvent( "vmouseup", event, flags ); if ( !didScroll ) { if ( triggerVirtualEvent( "vclick", event, flags ) ) { // The target of the mouse events that follow the touchend // event don't necessarily match the target used during the // touch. This means we need to rely on coordinates for blocking // any click that is generated. t = getNativeEvent( event ).changedTouches[ 0 ]; clickBlockList.push({ touchID: lastTouchID, x: t.clientX, y: t.clientY }); // Prevent any mouse events that follow from triggering // virtual event notifications. blockMouseTriggers = true; } } triggerVirtualEvent( "vmouseout", event, flags); didScroll = false; startResetTimer(); } function hasVirtualBindings( ele ) { var bindings = $.data( ele, dataPropertyName ), k; if ( bindings ) { for ( k in bindings ) { if ( bindings[ k ] ) { return true; } } } return false; } function dummyMouseHandler(){} function getSpecialEventObject( eventType ) { var realType = eventType.substr( 1 ); return { setup: function( data, namespace ) { // If this is the first virtual mouse binding for this element, // add a bindings object to its data. if ( !hasVirtualBindings( this ) ) { $.data( this, dataPropertyName, {}); } // If setup is called, we know it is the first binding for this // eventType, so initialize the count for the eventType to zero. var bindings = $.data( this, dataPropertyName ); bindings[ eventType ] = true; // If this is the first virtual mouse event for this type, // register a global handler on the document. activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1; if ( activeDocHandlers[ eventType ] === 1 ) { $document.bind( realType, mouseEventCallback ); } // Some browsers, like Opera Mini, won't dispatch mouse/click events // for elements unless they actually have handlers registered on them. // To get around this, we register dummy handlers on the elements. $( this ).bind( realType, dummyMouseHandler ); // For now, if event capture is not supported, we rely on mouse handlers. if ( eventCaptureSupported ) { // If this is the first virtual mouse binding for the document, // register our touchstart handler on the document. activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1; if (activeDocHandlers[ "touchstart" ] === 1) { $document.bind( "touchstart", handleTouchStart ) .bind( "touchend", handleTouchEnd ) // On touch platforms, touching the screen and then dragging your finger // causes the window content to scroll after some distance threshold is // exceeded. On these platforms, a scroll prevents a click event from being // dispatched, and on some platforms, even the touchend is suppressed. To // mimic the suppression of the click event, we need to watch for a scroll // event. Unfortunately, some platforms like iOS don't dispatch scroll // events until *AFTER* the user lifts their finger (touchend). This means // we need to watch both scroll and touchmove events to figure out whether // or not a scroll happenens before the touchend event is fired. .bind( "touchmove", handleTouchMove ) .bind( "scroll", handleScroll ); } } }, teardown: function( data, namespace ) { // If this is the last virtual binding for this eventType, // remove its global handler from the document. --activeDocHandlers[ eventType ]; if ( !activeDocHandlers[ eventType ] ) { $document.unbind( realType, mouseEventCallback ); } if ( eventCaptureSupported ) { // If this is the last virtual mouse binding in existence, // remove our document touchstart listener. --activeDocHandlers[ "touchstart" ]; if ( !activeDocHandlers[ "touchstart" ] ) { $document.unbind( "touchstart", handleTouchStart ) .unbind( "touchmove", handleTouchMove ) .unbind( "touchend", handleTouchEnd ) .unbind( "scroll", handleScroll ); } } var $this = $( this ), bindings = $.data( this, dataPropertyName ); // teardown may be called when an element was // removed from the DOM. If this is the case, // jQuery core may have already stripped the element // of any data bindings so we need to check it before // using it. if ( bindings ) { bindings[ eventType ] = false; } // Unregister the dummy event handler. $this.unbind( realType, dummyMouseHandler ); // If this is the last virtual mouse binding on the // element, remove the binding data from the element. if ( !hasVirtualBindings( this ) ) { $this.removeData( dataPropertyName ); } } }; } // Expose our custom events to the jQuery bind/unbind mechanism. for ( var i = 0; i < virtualEventNames.length; i++ ){ $.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] ); } // Add a capture click handler to block clicks. // Note that we require event capture support for this so if the device // doesn't support it, we punt for now and rely solely on mouse events. if ( eventCaptureSupported ) { document.addEventListener( "click", function( e ){ var cnt = clickBlockList.length, target = e.target, x, y, ele, i, o, touchID; if ( cnt ) { x = e.clientX; y = e.clientY; threshold = $.vmouse.clickDistanceThreshold; // The idea here is to run through the clickBlockList to see if // the current click event is in the proximity of one of our // vclick events that had preventDefault() called on it. If we find // one, then we block the click. // // Why do we have to rely on proximity? // // Because the target of the touch event that triggered the vclick // can be different from the target of the click event synthesized // by the browser. The target of a mouse/click event that is syntehsized // from a touch event seems to be implementation specific. For example, // some browsers will fire mouse/click events for a link that is near // a touch event, even though the target of the touchstart/touchend event // says the user touched outside the link. Also, it seems that with most // browsers, the target of the mouse/click event is not calculated until the // time it is dispatched, so if you replace an element that you touched // with another element, the target of the mouse/click will be the new // element underneath that point. // // Aside from proximity, we also check to see if the target and any // of its ancestors were the ones that blocked a click. This is necessary // because of the strange mouse/click target calculation done in the // Android 2.1 browser, where if you click on an element, and there is a // mouse/click handler on one of its ancestors, the target will be the // innermost child of the touched element, even if that child is no where // near the point of touch. ele = target; while ( ele ) { for ( i = 0; i < cnt; i++ ) { o = clickBlockList[ i ]; touchID = 0; if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) || $.data( ele, touchTargetPropertyName ) === o.touchID ) { // XXX: We may want to consider removing matches from the block list // instead of waiting for the reset timer to fire. e.preventDefault(); e.stopPropagation(); return; } } ele = ele.parentNode; } } }, true); } })( jQuery, window, document ); /* * jQuery Mobile Framework : events * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, window, undefined ) { // add new event shortcuts $.each( ( "touchstart touchmove touchend orientationchange throttledresize " + "tap taphold swipe swipeleft swiperight scrollstart scrollstop" ).split( " " ), function( i, name ) { $.fn[ name ] = function( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; $.attrFn[ name ] = true; }); var supportTouch = $.support.touch, scrollEvent = "touchmove scroll", touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", touchMoveEvent = supportTouch ? "touchmove" : "mousemove"; function triggerCustomEvent( obj, eventType, event ) { var originalType = event.type; event.type = eventType; $.event.handle.call( obj, event ); event.type = originalType; } // also handles scrollstop $.event.special.scrollstart = { enabled: true, setup: function() { var thisObject = this, $this = $( thisObject ), scrolling, timer; function trigger( event, state ) { scrolling = state; triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event ); } // iPhone triggers scroll after a small delay; use touchmove instead $this.bind( scrollEvent, function( event ) { if ( !$.event.special.scrollstart.enabled ) { return; } if ( !scrolling ) { trigger( event, true ); } clearTimeout( timer ); timer = setTimeout(function() { trigger( event, false ); }, 50 ); }); } }; // also handles taphold $.event.special.tap = { setup: function() { var thisObject = this, $this = $( thisObject ); $this.bind( "vmousedown", function( event ) { if ( event.which && event.which !== 1 ) { return false; } var touching = true, origTarget = event.target, origEvent = event.originalEvent, timer; function clearTapHandlers() { touching = false; clearTimeout(timer); $this.unbind( "vclick", clickHandler ) .unbind( "vmousecancel", clearTapHandlers ); } function clickHandler(event) { clearTapHandlers(); // ONLY trigger a 'tap' event if the start target is // the same as the stop target. if ( origTarget == event.target ) { triggerCustomEvent( thisObject, "tap", event ); } } $this.bind( "vmousecancel", clearTapHandlers ) .bind( "vclick", clickHandler ); timer = setTimeout(function() { if ( touching ) { triggerCustomEvent( thisObject, "taphold", event ); } }, 750 ); }); } }; // also handles swipeleft, swiperight $.event.special.swipe = { scrollSupressionThreshold: 10, // More than this horizontal displacement, and we will suppress scrolling. durationThreshold: 1000, // More time than this, and it isn't a swipe. horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this. verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this. setup: function() { var thisObject = this, $this = $( thisObject ); $this.bind( touchStartEvent, function( event ) { var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event, start = { time: ( new Date() ).getTime(), coords: [ data.pageX, data.pageY ], origin: $( event.target ) }, stop; function moveHandler( event ) { if ( !start ) { return; } var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event; stop = { time: ( new Date() ).getTime(), coords: [ data.pageX, data.pageY ] }; // prevent scrolling if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) { event.preventDefault(); } } $this.bind( touchMoveEvent, moveHandler ) .one( touchStopEvent, function( event ) { $this.unbind( touchMoveEvent, moveHandler ); if ( start && stop ) { if ( stop.time - start.time < $.event.special.swipe.durationThreshold && Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold && Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) { start.origin.trigger( "swipe" ) .trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" ); } } start = stop = undefined; }); }); } }; (function( $, window ) { // "Cowboy" Ben Alman var win = $( window ), special_event, get_orientation, last_orientation; $.event.special.orientationchange = special_event = { setup: function() { // If the event is supported natively, return false so that jQuery // will bind to the event using DOM methods. if ( $.support.orientation ) { return false; } // Get the current orientation to avoid initial double-triggering. last_orientation = get_orientation(); // Because the orientationchange event doesn't exist, simulate the // event by testing window dimensions on resize. win.bind( "throttledresize", handler ); }, teardown: function(){ // If the event is not supported natively, return false so that // jQuery will unbind the event using DOM methods. if ( $.support.orientation ) { return false; } // Because the orientationchange event doesn't exist, unbind the // resize event handler. win.unbind( "throttledresize", handler ); }, add: function( handleObj ) { // Save a reference to the bound event handler. var old_handler = handleObj.handler; handleObj.handler = function( event ) { // Modify event object, adding the .orientation property. event.orientation = get_orientation(); // Call the originally-bound event handler and return its result. return old_handler.apply( this, arguments ); }; } }; // If the event is not supported natively, this handler will be bound to // the window resize event to simulate the orientationchange event. function handler() { // Get the current orientation. var orientation = get_orientation(); if ( orientation !== last_orientation ) { // The orientation has changed, so trigger the orientationchange event. last_orientation = orientation; win.trigger( "orientationchange" ); } }; // Get the current page orientation. This method is exposed publicly, should it // be needed, as jQuery.event.special.orientationchange.orientation() $.event.special.orientationchange.orientation = get_orientation = function() { var elem = document.documentElement; return elem && elem.clientWidth / elem.clientHeight < 1.1 ? "portrait" : "landscape"; }; })( jQuery, window ); // throttled resize event (function() { $.event.special.throttledresize = { setup: function() { $( this ).bind( "resize", handler ); }, teardown: function(){ $( this ).unbind( "resize", handler ); } }; var throttle = 250, handler = function() { curr = ( new Date() ).getTime(); diff = curr - lastCall; if ( diff >= throttle ) { lastCall = curr; $( this ).trigger( "throttledresize" ); } else { if ( heldCall ) { clearTimeout( heldCall ); } // Promise a held call will still execute heldCall = setTimeout( handler, throttle - diff ); } }, lastCall = 0, heldCall, curr, diff; })(); $.each({ scrollstop: "scrollstart", taphold: "tap", swipeleft: "swipe", swiperight: "swipe" }, function( event, sourceEvent ) { $.event.special[ event ] = { setup: function() { $( this ).bind( sourceEvent, $.noop ); } }; }); })( jQuery, this ); /*! * jQuery hashchange event - v1.3 - 7/21/2010 * http://benalman.com/projects/jquery-hashchange-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery hashchange event // // *Version: 1.3, Last updated: 7/21/2010* // // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/ // GitHub - http://github.com/cowboy/jquery-hashchange/ // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/ // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5, // Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5. // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/ // // About: Known issues // // While this jQuery hashchange event implementation is quite stable and // robust, there are a few unfortunate browser bugs surrounding expected // hashchange event-based behaviors, independent of any JavaScript // window.onhashchange abstraction. See the following examples for more // information: // // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/ // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/ // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/ // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/ // // Also note that should a browser natively support the window.onhashchange // event, but not report that it does, the fallback polling loop will be used. // // About: Release History // // 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more // "removable" for mobile-only development. Added IE6/7 document.title // support. Attempted to make Iframe as hidden as possible by using // techniques from http://www.paciellogroup.com/blog/?p=604. Added // support for the "shortcut" format $(window).hashchange( fn ) and // $(window).hashchange() like jQuery provides for built-in events. // Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and // lowered its default value to 50. Added <jQuery.fn.hashchange.domain> // and <jQuery.fn.hashchange.src> properties plus document-domain.html // file to address access denied issues when setting document.domain in // IE6/7. // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin // from a page on another domain would cause an error in Safari 4. Also, // IE6/7 Iframe is now inserted after the body (this actually works), // which prevents the page from scrolling when the event is first bound. // Event can also now be bound before DOM ready, but it won't be usable // before then in IE6/7. // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug // where browser version is incorrectly reported as 8.0, despite // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag. // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special // window.onhashchange functionality into a separate plugin for users // who want just the basic event & back button support, without all the // extra awesomeness that BBQ provides. This plugin will be included as // part of jQuery BBQ, but also be available separately. (function($,window,undefined){ '$:nomunge'; // Used by YUI compressor. // Reused string. var str_hashchange = 'hashchange', // Method / object references. doc = document, fake_onhashchange, special = $.event.special, // Does the browser support window.onhashchange? Note that IE8 running in // IE7 compatibility mode reports true for 'onhashchange' in window, even // though the event isn't supported, so also test document.documentMode. doc_mode = doc.documentMode, supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 ); // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { url = url || location.href; return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Method: jQuery.fn.hashchange // // Bind a handler to the window.onhashchange event or trigger all bound // window.onhashchange event handlers. This behavior is consistent with // jQuery's built-in event handlers. // // Usage: // // > jQuery(window).hashchange( [ handler ] ); // // Arguments: // // handler - (Function) Optional handler to be bound to the hashchange // event. This is a "shortcut" for the more verbose form: // jQuery(window).bind( 'hashchange', handler ). If handler is omitted, // all bound window.onhashchange event handlers will be triggered. This // is a shortcut for the more verbose // jQuery(window).trigger( 'hashchange' ). These forms are described in // the <hashchange event> section. // // Returns: // // (jQuery) The initial jQuery collection of elements. // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and // $(elem).hashchange() for triggering, like jQuery does for built-in events. $.fn[ str_hashchange ] = function( fn ) { return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange ); }; // Property: jQuery.fn.hashchange.delay // // The numeric interval (in milliseconds) at which the <hashchange event> // polling loop executes. Defaults to 50. // Property: jQuery.fn.hashchange.domain // // If you're setting document.domain in your JavaScript, and you want hash // history to work in IE6/7, not only must this property be set, but you must // also set document.domain BEFORE jQuery is loaded into the page. This // property is only applicable if you are supporting IE6/7 (or IE8 operating // in "IE7 compatibility" mode). // // In addition, the <jQuery.fn.hashchange.src> property must be set to the // path of the included "document-domain.html" file, which can be renamed or // modified if necessary (note that the document.domain specified must be the // same in both your main JavaScript as well as in this file). // // Usage: // // jQuery.fn.hashchange.domain = document.domain; // Property: jQuery.fn.hashchange.src // // If, for some reason, you need to specify an Iframe src file (for example, // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can // do so using this property. Note that when using this property, history // won't be recorded in IE6/7 until the Iframe src file loads. This property // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7 // compatibility" mode). // // Usage: // // jQuery.fn.hashchange.src = 'path/to/file.html'; $.fn[ str_hashchange ].delay = 50; /* $.fn[ str_hashchange ].domain = null; $.fn[ str_hashchange ].src = null; */ // Event: hashchange event // // Fired when location.hash changes. In browsers that support it, the native // HTML5 window.onhashchange event is used, otherwise a polling loop is // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7 // compatibility" mode), a hidden Iframe is created to allow the back button // and hash-based history to work. // // Usage as described in <jQuery.fn.hashchange>: // // > // Bind an event handler. // > jQuery(window).hashchange( function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).hashchange(); // // A more verbose usage that allows for event namespacing: // // > // Bind an event handler. // > jQuery(window).bind( 'hashchange', function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).trigger( 'hashchange' ); // // Additional Notes: // // * The polling loop and Iframe are not created until at least one handler // is actually bound to the 'hashchange' event. // * If you need the bound handler(s) to execute immediately, in cases where // a location.hash exists on page load, via bookmark or page refresh for // example, use jQuery(window).hashchange() or the more verbose // jQuery(window).trigger( 'hashchange' ). // * The event can be bound before DOM ready, but since it won't be usable // before then in IE6/7 (due to the necessary Iframe), recommended usage is // to bind it inside a DOM ready handler. // Override existing $.event.special.hashchange methods (allowing this plugin // to be defined after jQuery BBQ in BBQ's source code). special[ str_hashchange ] = $.extend( special[ str_hashchange ], { // Called only when the first 'hashchange' event is bound to window. setup: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to create our own. And we don't want to call this // until the user binds to the event, just in case they never do, since it // will create a polling loop and possibly even a hidden Iframe. $( fake_onhashchange.start ); }, // Called only when the last 'hashchange' event is unbound from window. teardown: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to stop ours (if possible). $( fake_onhashchange.stop ); } }); // fake_onhashchange does all the work of triggering the window.onhashchange // event for browsers that don't natively support it, including creating a // polling loop to watch for hash changes and in IE 6/7 creating a hidden // Iframe to enable back and forward. fake_onhashchange = (function(){ var self = {}, timeout_id, // Remember the initial hash so it doesn't get triggered immediately. last_hash = get_fragment(), fn_retval = function(val){ return val; }, history_set = fn_retval, history_get = fn_retval; // Start the polling loop. self.start = function() { timeout_id || poll(); }; // Stop the polling loop. self.stop = function() { timeout_id && clearTimeout( timeout_id ); timeout_id = undefined; }; // This polling loop checks every $.fn.hashchange.delay milliseconds to see // if location.hash has changed, and triggers the 'hashchange' event on // window when necessary. function poll() { var hash = get_fragment(), history_hash = history_get( last_hash ); if ( hash !== last_hash ) { history_set( last_hash = hash, history_hash ); $(window).trigger( str_hashchange ); } else if ( history_hash !== last_hash ) { location.href = location.href.replace( /#.*/, '' ) + history_hash; } timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay ); }; // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv $.browser.msie && !supports_onhashchange && (function(){ // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8 // when running in "IE7 compatibility" mode. var iframe, iframe_src; // When the event is bound and polling starts in IE 6/7, create a hidden // Iframe for history handling. self.start = function(){ if ( !iframe ) { iframe_src = $.fn[ str_hashchange ].src; iframe_src = iframe_src && iframe_src + get_fragment(); // Create hidden Iframe. Attempt to make Iframe as hidden as possible // by using techniques from http://www.paciellogroup.com/blog/?p=604. iframe = $('<iframe tabindex="-1" title="empty"/>').hide() // When Iframe has completely loaded, initialize the history and // start polling. .one( 'load', function(){ iframe_src || history_set( get_fragment() ); poll(); }) // Load Iframe src if specified, otherwise nothing. .attr( 'src', iframe_src || 'javascript:0' ) // Append Iframe after the end of the body to prevent unnecessary // initial page scrolling (yes, this works). .insertAfter( 'body' )[0].contentWindow; // Whenever `document.title` changes, update the Iframe's title to // prettify the back/next history menu entries. Since IE sometimes // errors with "Unspecified error" the very first time this is set // (yes, very useful) wrap this with a try/catch block. doc.onpropertychange = function(){ try { if ( event.propertyName === 'title' ) { iframe.document.title = doc.title; } } catch(e) {} }; } }; // Override the "stop" method since an IE6/7 Iframe was created. Even // if there are no longer any bound event handlers, the polling loop // is still necessary for back/next to work at all! self.stop = fn_retval; // Get history by looking at the hidden Iframe's location.hash. history_get = function() { return get_fragment( iframe.location.href ); }; // Set a new history item by opening and then closing the Iframe // document, *then* setting its location.hash. If document.domain has // been set, update that as well. history_set = function( hash, history_hash ) { var iframe_doc = iframe.document, domain = $.fn[ str_hashchange ].domain; if ( hash !== history_hash ) { // Update Iframe with any initial `document.title` that might be set. iframe_doc.title = doc.title; // Opening the Iframe's document after it has been closed is what // actually adds a history entry. iframe_doc.open(); // Set document.domain for the Iframe document as well, if necessary. domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' ); iframe_doc.close(); // Update the Iframe's hash, for great justice. iframe.location.hash = hash; } }; })(); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return self; })(); })(jQuery,this); /* * jQuery Mobile Framework : "page" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.page", $.mobile.widget, { options: { theme: "c", domCache: false }, _create: function() { var $elem = this.element, o = this.options; if ( this._trigger( "beforeCreate" ) === false ) { return; } $elem.addClass( "ui-page ui-body-" + o.theme ); } }); })( jQuery ); /*! * jQuery Mobile v@VERSION * http://jquerymobile.com/ * * Copyright 2010, jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, window, undefined ) { // jQuery.mobile configurable options $.extend( $.mobile, { // Namespace used framework-wide for data-attrs. Default is no namespace ns: "", // Define the url parameter used for referencing widget-generated sub-pages. // Translates to to example.html&ui-page=subpageIdentifier // hash segment before &ui-page= is used to make Ajax request subPageUrlKey: "ui-page", // Class assigned to page currently in view, and during transitions activePageClass: "ui-page-active", // Class used for "active" button state, from CSS framework activeBtnClass: "ui-btn-active", // Automatically handle clicks and form submissions through Ajax, when same-domain ajaxEnabled: true, // Automatically load and show pages based on location.hash hashListeningEnabled: true, // Set default page transition - 'none' for no transitions defaultPageTransition: "slide", // Minimum scroll distance that will be remembered when returning to a page minScrollBack: screen.height / 2, // Set default dialog transition - 'none' for no transitions defaultDialogTransition: "pop", // Show loading message during Ajax requests // if false, message will not appear, but loading classes will still be toggled on html el loadingMessage: "loading", // Error response message - appears when an Ajax page request fails pageLoadErrorMessage: "Error Loading Page", //automatically initialize the DOM when it's ready autoInitializePage: true, // Support conditions that must be met in order to proceed // default enhanced qualifications are media query support OR IE 7+ gradeA: function(){ return $.support.mediaquery || $.mobile.browser.ie && $.mobile.browser.ie >= 7; }, // TODO might be useful upstream in jquery itself ? keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, // COMMAND COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, // COMMAND_RIGHT NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91 // COMMAND }, // Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value silentScroll: function( ypos ) { if ( $.type( ypos ) !== "number" ) { ypos = $.mobile.defaultHomeScroll; } // prevent scrollstart and scrollstop events $.event.special.scrollstart.enabled = false; setTimeout(function() { window.scrollTo( 0, ypos ); $( document ).trigger( "silentscroll", { x: 0, y: ypos }); }, 20 ); setTimeout(function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, // Take a data attribute property, prepend the namespace // and then camel case the attribute string nsNormalize: function( prop ) { if ( !prop ) { return; } return $.camelCase( $.mobile.ns + prop ); } }); // Mobile version of data and removeData and hasData methods // ensures all data is set and retrieved using jQuery Mobile's data namespace $.fn.jqmData = function( prop, value ) { return this.data( prop ? $.mobile.nsNormalize( prop ) : prop, value ); }; $.jqmData = function( elem, prop, value ) { return $.data( elem, $.mobile.nsNormalize( prop ), value ); }; $.fn.jqmRemoveData = function( prop ) { return this.removeData( $.mobile.nsNormalize( prop ) ); }; $.jqmRemoveData = function( elem, prop ) { return $.removeData( elem, $.mobile.nsNormalize( prop ) ); }; $.jqmHasData = function( elem, prop ) { return $.hasData( elem, $.mobile.nsNormalize( prop ) ); }; // Monkey-patching Sizzle to filter the :jqmData selector var oldFind = $.find; $.find = function( selector, context, ret, extra ) { selector = selector.replace(/:jqmData\(([^)]*)\)/g, "[data-" + ( $.mobile.ns || "" ) + "$1]"); return oldFind.call( this, selector, context, ret, extra ); }; $.extend( $.find, oldFind ); $.find.matches = function( expr, set ) { return $.find( expr, null, null, set ); }; $.find.matchesSelector = function( node, expr ) { return $.find( expr, null, null, [ node ] ).length > 0; }; })( jQuery, this ); /* * jQuery Mobile Framework : core utilities for auto ajax navigation, base tag mgmt, * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ ( function( $, undefined ) { //define vars for interal use var $window = $( window ), $html = $( 'html' ), $head = $( 'head' ), //url path helpers for use in relative url management path = { // This scary looking regular expression parses an absolute URL or its relative // variants (protocol, site, document, query, and hash), into the various // components (protocol, host, path, query, fragment, etc that make up the // URL as well as some other commonly used sub-parts. When used with RegExp.exec() // or String.match, it parses the URL into a results array that looks like this: // // [0]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread#msg-content // [1]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread // [2]: http://jblas:password@mycompany.com:8080/mail/inbox // [3]: http://jblas:password@mycompany.com:8080 // [4]: http: // [5]: jblas:password@mycompany.com:8080 // [6]: jblas:password // [7]: jblas // [8]: password // [9]: mycompany.com:8080 // [10]: mycompany.com // [11]: 8080 // [12]: /mail/inbox // [13]: /mail/ // [14]: inbox // [15]: ?msg=1234&type=unread // [16]: #msg-content // urlParseRE: /^(((([^:\/#\?]+:)?(?:\/\/((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?]+)(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/, //Parse a URL into a structure that allows easy access to //all of the URL components by name. parseUrl: function( url ) { // If we're passed an object, we'll assume that it is // a parsed url object and just return it back to the caller. if ( $.type( url ) === "object" ) { return url; } var u = url || "", matches = path.urlParseRE.exec( url ), results; if ( matches ) { // Create an object that allows the caller to access the sub-matches // by name. Note that IE returns an empty string instead of undefined, // like all other browsers do, so we normalize everything so its consistent // no matter what browser we're running on. results = { href: matches[0] || "", hrefNoHash: matches[1] || "", hrefNoSearch: matches[2] || "", domain: matches[3] || "", protocol: matches[4] || "", authority: matches[5] || "", username: matches[7] || "", password: matches[8] || "", host: matches[9] || "", hostname: matches[10] || "", port: matches[11] || "", pathname: matches[12] || "", directory: matches[13] || "", filename: matches[14] || "", search: matches[15] || "", hash: matches[16] || "" }; } return results || {}; }, //Turn relPath into an asbolute path. absPath is //an optional absolute path which describes what //relPath is relative to. makePathAbsolute: function( relPath, absPath ) { if ( relPath && relPath.charAt( 0 ) === "/" ) { return relPath; } relPath = relPath || ""; absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : ""; var absStack = absPath ? absPath.split( "/" ) : [], relStack = relPath.split( "/" ); for ( var i = 0; i < relStack.length; i++ ) { var d = relStack[ i ]; switch ( d ) { case ".": break; case "..": if ( absStack.length ) { absStack.pop(); } break; default: absStack.push( d ); break; } } return "/" + absStack.join( "/" ); }, //Returns true if both urls have the same domain. isSameDomain: function( absUrl1, absUrl2 ) { return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain; }, //Returns true for any relative variant. isRelativeUrl: function( url ) { // All relative Url variants have one thing in common, no protocol. return path.parseUrl( url ).protocol === ""; }, //Returns true for an absolute url. isAbsoluteUrl: function( url ) { return path.parseUrl( url ).protocol !== ""; }, //Turn the specified realtive URL into an absolute one. This function //can handle all relative variants (protocol, site, document, query, fragment). makeUrlAbsolute: function( relUrl, absUrl ) { if ( !path.isRelativeUrl( relUrl ) ) { return relUrl; } var relObj = path.parseUrl( relUrl ), absObj = path.parseUrl( absUrl ), protocol = relObj.protocol || absObj.protocol, authority = relObj.authority || absObj.authority, hasPath = relObj.pathname !== "", pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ), search = relObj.search || ( !hasPath && absObj.search ) || "", hash = relObj.hash; return protocol + "//" + authority + pathname + search + hash; }, //Add search (aka query) params to the specified url. addSearchParams: function( url, params ) { var u = path.parseUrl( url ), p = ( typeof params === "object" ) ? $.param( params ) : params, s = u.search || "?"; return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" ); }, convertUrlToDataUrl: function( absUrl ) { var u = path.parseUrl( absUrl ); if ( path.isEmbeddedPage( u ) ) { // For embedded pages, remove the dialog hash key as in getFilePath(), // otherwise the Data Url won't match the id of the embedded Page. return u.hash.split( dialogHashKey )[0].replace( /^#/, "" ); } else if ( path.isSameDomain( u, documentBase ) ) { return u.hrefNoHash.replace( documentBase.domain, "" ); } return absUrl; }, //get path from current hash, or from a file path get: function( newPath ) { if( newPath === undefined ) { newPath = location.hash; } return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' ); }, //return the substring of a filepath before the sub-page key, for making a server request getFilePath: function( path ) { var splitkey = '&' + $.mobile.subPageUrlKey; return path && path.split( splitkey )[0].split( dialogHashKey )[0]; }, //set location hash to path set: function( path ) { location.hash = path; }, //test if a given url (string) is a path //NOTE might be exceptionally naive isPath: function( url ) { return ( /\// ).test( url ); }, //return a url path with the window's location protocol/hostname/pathname removed clean: function( url ) { return url.replace( documentBase.domain, "" ); }, //just return the url without an initial # stripHash: function( url ) { return url.replace( /^#/, "" ); }, //remove the preceding hash, any query params, and dialog notations cleanHash: function( hash ) { return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) ); }, //check whether a url is referencing the same domain, or an external domain or different protocol //could be mailto, etc isExternal: function( url ) { var u = path.parseUrl( url ); return u.protocol && u.domain !== documentUrl.domain ? true : false; }, hasProtocol: function( url ) { return ( /^(:?\w+:)/ ).test( url ); }, isEmbeddedPage: function( url ) { var u = path.parseUrl( url ); //if the path is absolute, then we need to compare the url against //both the documentUrl and the documentBase. The main reason for this //is that links embedded within external documents will refer to the //application document, whereas links embedded within the application //document will be resolved against the document base. if ( u.protocol !== "" ) { return ( u.hash && ( u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ) ) ); } return (/^#/).test( u.href ); } }, //will be defined when a link is clicked and given an active class $activeClickedLink = null, //urlHistory is purely here to make guesses at whether the back or forward button was clicked //and provide an appropriate transition urlHistory = { // Array of pages that are visited during a single page load. // Each has a url and optional transition, title, and pageUrl (which represents the file path, in cases where URL is obscured, such as dialogs) stack: [], //maintain an index number for the active page in the stack activeIndex: 0, //get active getActive: function() { return urlHistory.stack[ urlHistory.activeIndex ]; }, getPrev: function() { return urlHistory.stack[ urlHistory.activeIndex - 1 ]; }, getNext: function() { return urlHistory.stack[ urlHistory.activeIndex + 1 ]; }, // addNew is used whenever a new page is added addNew: function( url, transition, title, pageUrl ) { //if there's forward history, wipe it if( urlHistory.getNext() ) { urlHistory.clearForward(); } urlHistory.stack.push( {url : url, transition: transition, title: title, pageUrl: pageUrl } ); urlHistory.activeIndex = urlHistory.stack.length - 1; }, //wipe urls ahead of active index clearForward: function() { urlHistory.stack = urlHistory.stack.slice( 0, urlHistory.activeIndex + 1 ); }, directHashChange: function( opts ) { var back , forward, newActiveIndex; // check if url isp in history and if it's ahead or behind current page $.each( urlHistory.stack, function( i, historyEntry ) { //if the url is in the stack, it's a forward or a back if( opts.currentUrl === historyEntry.url ) { //define back and forward by whether url is older or newer than current page back = i < urlHistory.activeIndex; forward = !back; newActiveIndex = i; } }); // save new page index, null check to prevent falsey 0 result this.activeIndex = newActiveIndex !== undefined ? newActiveIndex : this.activeIndex; if( back ) { opts.isBack(); } else if( forward ) { opts.isForward(); } }, //disable hashchange event listener internally to ignore one change //toggled internally when location.hash is updated to match the url of a successful page load ignoreNextHashChange: false }, //define first selector to receive focus when a page is shown focusable = "[tabindex],a,button:visible,select:visible,input", //queue to hold simultanious page transitions pageTransitionQueue = [], //indicates whether or not page is in process of transitioning isPageTransitioning = false, //nonsense hash change key for dialogs, so they create a history entry dialogHashKey = "&ui-state=dialog", //existing base tag? $base = $head.children( "base" ), //tuck away the original document URL minus any fragment. documentUrl = path.parseUrl( location.href ), //if the document has an embedded base tag, documentBase is set to its //initial value. If a base tag does not exist, then we default to the documentUrl. documentBase = $base.length ? path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), documentUrl.href ) ) : documentUrl, //cache the comparison once. documentBaseDiffers = ( documentUrl.hrefNoHash !== documentBase.hrefNoHash ); //base element management, defined depending on dynamic base tag support var base = $.support.dynamicBaseTag ? { //define base element, for use in routing asset urls that are referenced in Ajax-requested markup element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ), //set the generated BASE element's href attribute to a new page's base path set: function( href ) { base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) ); }, //set the generated BASE element's href attribute to a new page's base path reset: function() { base.element.attr( "href", documentBase.hrefNoHash ); } } : undefined; /* internal utility functions --------------------------------------*/ //direct focus to the page title, or otherwise first focusable element function reFocus( page ) { var lastClicked = page.jqmData( "lastClicked" ); if( lastClicked && lastClicked.length ) { lastClicked.focus(); } else { var pageTitle = page.find( ".ui-title:eq(0)" ); if( pageTitle.length ) { pageTitle.focus(); } else{ page.find( focusable ).eq( 0 ).focus(); } } } //remove active classes after page transition or error function removeActiveLinkClass( forceRemoval ) { if( !!$activeClickedLink && ( !$activeClickedLink.closest( '.ui-page-active' ).length || forceRemoval ) ) { $activeClickedLink.removeClass( $.mobile.activeBtnClass ); } $activeClickedLink = null; } function releasePageTransitionLock() { isPageTransitioning = false; if( pageTransitionQueue.length > 0 ) { $.mobile.changePage.apply( null, pageTransitionQueue.pop() ); } } //function for transitioning between two existing pages function transitionPages( toPage, fromPage, transition, reverse ) { //get current scroll distance var currScroll = $.support.scrollTop ? $window.scrollTop() : true, toScroll = toPage.data( "lastScroll" ) || $.mobile.defaultHomeScroll, screenHeight = getScreenHeight(); //if scrolled down, scroll to top if( currScroll ){ window.scrollTo( 0, $.mobile.defaultHomeScroll ); } //if the Y location we're scrolling to is less than 10px, let it go for sake of smoothness if( toScroll < $.mobile.minScrollBack ){ toScroll = 0; } if( fromPage ) { //set as data for returning to that spot fromPage .height( screenHeight + currScroll ) .jqmData( "lastScroll", currScroll ) .jqmData( "lastClicked", $activeClickedLink ); //trigger before show/hide events fromPage.data( "page" )._trigger( "beforehide", null, { nextPage: toPage } ); } toPage .height( screenHeight + toScroll ) .data( "page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } ); //clear page loader $.mobile.hidePageLoadingMsg(); //find the transition handler for the specified transition. If there //isn't one in our transitionHandlers dictionary, use the default one. //call the handler immediately to kick-off the transition. var th = $.mobile.transitionHandlers[transition || "none"] || $.mobile.defaultTransitionHandler, promise = th( transition, reverse, toPage, fromPage ); promise.done(function() { //reset toPage height bac toPage.height( "" ); //jump to top or prev scroll, sometimes on iOS the page has not rendered yet. if( toScroll ){ $.mobile.silentScroll( toScroll ); $( document ).one( "silentscroll", function() { reFocus( toPage ); } ); } else{ reFocus( toPage ); } //trigger show/hide events if( fromPage ) { fromPage.height("").data( "page" )._trigger( "hide", null, { nextPage: toPage } ); } //trigger pageshow, define prevPage as either fromPage or empty jQuery obj toPage.data( "page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } ); }); return promise; } //simply set the active page's minimum height to screen height, depending on orientation function getScreenHeight(){ var orientation = jQuery.event.special.orientationchange.orientation(), port = orientation === "portrait", winMin = port ? 480 : 320, screenHeight = port ? screen.availHeight : screen.availWidth, winHeight = Math.max( winMin, $( window ).height() ), pageMin = Math.min( screenHeight, winHeight ); return pageMin; } //simply set the active page's minimum height to screen height, depending on orientation function resetActivePageHeight(){ $( "." + $.mobile.activePageClass ).css( "min-height", getScreenHeight() ); } //shared page enhancements function enhancePage( $page, role ) { // If a role was specified, make sure the data-role attribute // on the page element is in sync. if( role ) { $page.attr( "data-" + $.mobile.ns + "role", role ); } //run page plugin $page.page(); } /* exposed $.mobile methods */ //animation complete callback $.fn.animationComplete = function( callback ) { if( $.support.cssTransitions ) { return $( this ).one( 'webkitAnimationEnd', callback ); } else{ // defer execution for consistency between webkit/non webkit setTimeout( callback, 0 ); return $( this ); } }; //update location.hash, with or without triggering hashchange event //TODO - deprecate this one at 1.0 $.mobile.updateHash = path.set; //expose path object on $.mobile $.mobile.path = path; //expose base object on $.mobile $.mobile.base = base; //url stack, useful when plugins need to be aware of previous pages viewed //TODO: deprecate this one at 1.0 $.mobile.urlstack = urlHistory.stack; //history stack $.mobile.urlHistory = urlHistory; //default non-animation transition handler $.mobile.noneTransitionHandler = function( name, reverse, $toPage, $fromPage ) { if ( $fromPage ) { $fromPage.removeClass( $.mobile.activePageClass ); } $toPage.addClass( $.mobile.activePageClass ); return $.Deferred().resolve( name, reverse, $toPage, $fromPage ).promise(); }; //default handler for unknown transitions $.mobile.defaultTransitionHandler = $.mobile.noneTransitionHandler; //transition handler dictionary for 3rd party transitions $.mobile.transitionHandlers = { none: $.mobile.defaultTransitionHandler }; //enable cross-domain page support $.mobile.allowCrossDomainPages = false; //return the original document url $.mobile.getDocumentUrl = function(asParsedObject) { return asParsedObject ? $.extend( {}, documentUrl ) : documentUrl.href; }; //return the original document base url $.mobile.getDocumentBase = function(asParsedObject) { return asParsedObject ? $.extend( {}, documentBase ) : documentBase.href; }; // Load a page into the DOM. $.mobile.loadPage = function( url, options ) { // This function uses deferred notifications to let callers // know when the page is done loading, or if an error has occurred. var deferred = $.Deferred(), // The default loadPage options with overrides specified by // the caller. settings = $.extend( {}, $.mobile.loadPage.defaults, options ), // The DOM element for the page after it has been loaded. page = null, // If the reloadPage option is true, and the page is already // in the DOM, dupCachedPage will be set to the page element // so that it can be removed after the new version of the // page is loaded off the network. dupCachedPage = null, // determine the current base url findBaseWithDefault = function(){ var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) ); return closestBase || documentBase.hrefNoHash; }, // The absolute version of the URL passed into the function. This // version of the URL may contain dialog/subpage params in it. absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() ); // If the caller provided data, and we're using "get" request, // append the data to the URL. if ( settings.data && settings.type === "get" ) { absUrl = path.addSearchParams( absUrl, settings.data ); settings.data = undefined; } // The absolute version of the URL minus any dialog/subpage params. // In otherwords the real URL of the page to be loaded. var fileUrl = path.getFilePath( absUrl ), // The version of the Url actually stored in the data-url attribute of // the page. For embedded pages, it is just the id of the page. For pages // within the same domain as the document base, it is the site relative // path. For cross-domain pages (Phone Gap only) the entire absolute Url // used to load the page. dataUrl = path.convertUrlToDataUrl( absUrl ); // Make sure we have a pageContainer to work with. settings.pageContainer = settings.pageContainer || $.mobile.pageContainer; // Check to see if the page already exists in the DOM. page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" ); // Reset base to the default document base. if ( base ) { base.reset(); } // If the page we are interested in is already in the DOM, // and the caller did not indicate that we should force a // reload of the file, we are done. Otherwise, track the // existing page as a duplicated. if ( page.length ) { if ( !settings.reloadPage ) { enhancePage( page, settings.role ); deferred.resolve( absUrl, options, page ); return deferred.promise(); } dupCachedPage = page; } if ( settings.showLoadMsg ) { // This configurable timeout allows cached pages a brief delay to load without showing a message var loadMsgDelay = setTimeout(function(){ $.mobile.showPageLoadingMsg(); }, settings.loadMsgDelay ), // Shared logic for clearing timeout and removing message. hideMsg = function(){ // Stop message show timer clearTimeout( loadMsgDelay ); // Hide loading message $.mobile.hidePageLoadingMsg(); }; } if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) { deferred.reject( absUrl, options ); } else { // Load the new page. $.ajax({ url: fileUrl, type: settings.type, data: settings.data, dataType: "html", success: function( html ) { //pre-parse html to check for a data-url, //use it as the new fileUrl, base path, etc var all = $( "<div></div>" ), //page title regexp newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1, // TODO handle dialogs again pageElemRegex = new RegExp( ".*(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>).*" ), dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" ); // data-url must be provided for the base tag so resource requests can be directed to the // correct url. loading into a temprorary element makes these requests immediately if( pageElemRegex.test( html ) && RegExp.$1 && dataUrlRegex.test( RegExp.$1 ) && RegExp.$1 ) { url = fileUrl = path.getFilePath( RegExp.$1 ); } else{ } if ( base ) { base.set( fileUrl ); } //workaround to allow scripts to execute when included in page divs all.get( 0 ).innerHTML = html; page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first(); //if page elem couldn't be found, create one and insert the body element's contents if( !page.length ){ page = $( "<div data-" + $.mobile.ns + "role='page'>" + html.split( /<\/?body[^>]*>/gmi )[1] + "</div>" ); } if ( newPageTitle && !page.jqmData( "title" ) ) { page.jqmData( "title", newPageTitle ); } //rewrite src and href attrs to use a base url if( !$.support.dynamicBaseTag ) { var newPath = path.get( fileUrl ); page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() { var thisAttr = $( this ).is( '[href]' ) ? 'href' : $(this).is('[src]') ? 'src' : 'action', thisUrl = $( this ).attr( thisAttr ); // XXX_jblas: We need to fix this so that it removes the document // base URL, and then prepends with the new page URL. //if full path exists and is same, chop it - helps IE out thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' ); if( !/^(\w+:|#|\/)/.test( thisUrl ) ) { $( this ).attr( thisAttr, newPath + thisUrl ); } }); } //append to page and enhance page .attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) ) .appendTo( settings.pageContainer ); // wait for page creation to leverage options defined on widget page.one('pagecreate', function(){ // when dom caching is not enabled bind to remove the page on hide if( !page.data("page").options.domCache ){ page.bind( "pagehide.remove", function(){ $(this).remove(); }); } }); enhancePage( page, settings.role ); // Enhancing the page may result in new dialogs/sub pages being inserted // into the DOM. If the original absUrl refers to a sub-page, that is the // real page we are interested in. if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) { page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" ); } //bind pageHide to removePage after it's hidden, if the page options specify to do so // Remove loading message. if ( settings.showLoadMsg ) { hideMsg(); } deferred.resolve( absUrl, options, page, dupCachedPage ); }, error: function() { //set base back to current path if( base ) { base.set( path.get() ); } // Remove loading message. if ( settings.showLoadMsg ) { // Remove loading message. hideMsg(); //show error message $( "<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>"+ $.mobile.pageLoadErrorMessage +"</h1></div>" ) .css({ "display": "block", "opacity": 0.96, "top": $window.scrollTop() + 100 }) .appendTo( settings.pageContainer ) .delay( 800 ) .fadeOut( 400, function() { $( this ).remove(); }); } deferred.reject( absUrl, options ); } }); } return deferred.promise(); }; $.mobile.loadPage.defaults = { type: "get", data: undefined, reloadPage: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. showLoadMsg: false, pageContainer: undefined, loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message. }; // Show a specific page in the page container. $.mobile.changePage = function( toPage, options ) { // XXX: REMOVE_BEFORE_SHIPPING_1.0 // This is temporary code that makes changePage() compatible with previous alpha versions. if ( typeof options !== "object" ) { var opts = null; // Map old-style call signature for form submit to the new options object format. if ( typeof toPage === "object" && toPage.url && toPage.type ) { opts = { type: toPage.type, data: toPage.data, forcePageLoad: true }; toPage = toPage.url; } // The arguments passed into the function need to be re-mapped // to the new options object format. var len = arguments.length; if ( len > 1 ) { var argNames = [ "transition", "reverse", "changeHash", "fromHashChange" ], i; for ( i = 1; i < len; i++ ) { var a = arguments[ i ]; if ( typeof a !== "undefined" ) { opts = opts || {}; opts[ argNames[ i - 1 ] ] = a; } } } // If an options object was created, then we know changePage() was called // with an old signature. if ( opts ) { return $.mobile.changePage( toPage, opts ); } } // XXX: REMOVE_BEFORE_SHIPPING_1.0 // If we are in the midst of a transition, queue the current request. // We'll call changePage() once we're done with the current transition to // service the request. if( isPageTransitioning ) { pageTransitionQueue.unshift( arguments ); return; } // Set the isPageTransitioning flag to prevent any requests from // entering this method while we are in the midst of loading a page // or transitioning. isPageTransitioning = true; var settings = $.extend( {}, $.mobile.changePage.defaults, options ); // Make sure we have a pageContainer to work with. settings.pageContainer = settings.pageContainer || $.mobile.pageContainer; // If the caller passed us a url, call loadPage() // to make sure it is loaded into the DOM. We'll listen // to the promise object it returns so we know when // it is done loading or if an error ocurred. if ( typeof toPage == "string" ) { $.mobile.loadPage( toPage, settings ) .done(function( url, options, newPage, dupCachedPage ) { isPageTransitioning = false; options.duplicateCachedPage = dupCachedPage; $.mobile.changePage( newPage, options ); }) .fail(function( url, options ) { // XXX_jblas: Fire off changepagefailed notificaiton. isPageTransitioning = false; //clear out the active button state removeActiveLinkClass( true ); //release transition lock so navigation is free again releasePageTransitionLock(); settings.pageContainer.trigger("changepagefailed"); }); return; } // The caller passed us a real page DOM element. Update our // internal state and then trigger a transition to the page. var mpc = settings.pageContainer, fromPage = $.mobile.activePage, url = toPage.jqmData( "url" ), // The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path pageUrl = url, fileUrl = path.getFilePath( url ), active = urlHistory.getActive(), activeIsInitialPage = urlHistory.activeIndex === 0, historyDir = 0, pageTitle = document.title, isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog"; // Let listeners know we're about to change the current page. mpc.trigger( "beforechangepage" ); // If we are trying to transition to the same page that we are currently on ignore the request. // an illegal same page request is defined by the current page being the same as the url, as long as there's history // and toPage is not an array or object (those are allowed to be "same") // // XXX_jblas: We need to remove this at some point when we allow for transitions // to the same page. if( fromPage && fromPage[0] === toPage[0] ) { isPageTransitioning = false; mpc.trigger( "changepage" ); return; } // We need to make sure the page we are given has already been enhanced. enhancePage( toPage, settings.role ); // If the changePage request was sent from a hashChange event, check to see if the // page is already within the urlHistory stack. If so, we'll assume the user hit // the forward/back button and will try to match the transition accordingly. if( settings.fromHashChange ) { urlHistory.directHashChange({ currentUrl: url, isBack: function() { historyDir = -1; }, isForward: function() { historyDir = 1; } }); } // Kill the keyboard. // XXX_jblas: We need to stop crawling the entire document to kill focus. Instead, // we should be tracking focus with a live() handler so we already have // the element in hand at this point. // Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement // is undefined when we are in an IFrame. try { $( document.activeElement || "" ).add( "input:focus, textarea:focus, select:focus" ).blur(); } catch(e) {} // If we're displaying the page as a dialog, we don't want the url // for the dialog content to be used in the hash. Instead, we want // to append the dialogHashKey to the url of the current page. if ( isDialog && active ) { url = active.url + dialogHashKey; } // Set the location hash. if( settings.changeHash !== false && url ) { //disable hash listening temporarily urlHistory.ignoreNextHashChange = true; //update hash and history path.set( url ); } //if title element wasn't found, try the page div data attr too var newPageTitle = toPage.jqmData( "title" ) || toPage.children(":jqmData(role='header')").find(".ui-title" ).text(); if( !!newPageTitle && pageTitle == document.title ) { pageTitle = newPageTitle; } //add page to history stack if it's not back or forward if( !historyDir ) { urlHistory.addNew( url, settings.transition, pageTitle, pageUrl ); } //set page title document.title = urlHistory.getActive().title; //set "toPage" as activePage $.mobile.activePage = toPage; // Make sure we have a transition defined. settings.transition = settings.transition || ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) || ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition ); // If we're navigating back in the URL history, set reverse accordingly. settings.reverse = settings.reverse || historyDir < 0; transitionPages( toPage, fromPage, settings.transition, settings.reverse ) .done(function() { removeActiveLinkClass(); //if there's a duplicateCachedPage, remove it from the DOM now that it's hidden if ( settings.duplicateCachedPage ) { settings.duplicateCachedPage.remove(); } //remove initial build class (only present on first pageshow) $html.removeClass( "ui-mobile-rendering" ); releasePageTransitionLock(); // Let listeners know we're all done changing the current page. mpc.trigger( "changepage" ); }); }; $.mobile.changePage.defaults = { transition: undefined, reverse: false, changeHash: true, fromHashChange: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. duplicateCachedPage: undefined, pageContainer: undefined, showLoadMsg: true //loading message shows by default when pages are being fetched during changePage }; /* Event Bindings - hashchange, submit, and click */ function findClosestLink( ele ) { while ( ele ) { if ( ele.nodeName.toLowerCase() == "a" ) { break; } ele = ele.parentNode; } return ele; } // The base URL for any given element depends on the page it resides in. function getClosestBaseUrl( ele ) { // Find the closest page and extract out its url. var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ), base = documentBase.hrefNoHash; if ( !url || !path.isPath( url ) ) { url = base; } return path.makeUrlAbsolute( url, base); } //The following event bindings should be bound after mobileinit has been triggered //the following function is called in the init file $.mobile._registerInternalEvents = function(){ //bind to form submit events, handle with Ajax $( "form" ).live('submit', function( event ) { var $this = $( this ); if( !$.mobile.ajaxEnabled || $this.is( ":jqmData(ajax='false')" ) ) { return; } var type = $this.attr( "method" ), target = $this.attr( "target" ), url = $this.attr( "action" ); // If no action is specified, browsers default to using the // URL of the document containing the form. Since we dynamically // pull in pages from external documents, the form should submit // to the URL for the source document of the page containing // the form. if ( !url ) { // Get the @data-url for the page containing the form. url = getClosestBaseUrl( $this ); if ( url === documentBase.hrefNoHash ) { // The url we got back matches the document base, // which means the page must be an internal/embedded page, // so default to using the actual document url as a browser // would. url = documentUrl.hrefNoSearch; } } url = path.makeUrlAbsolute( url, getClosestBaseUrl($this) ); //external submits use regular HTTP if( path.isExternal( url ) || target ) { return; } $.mobile.changePage( url, { type: type && type.length && type.toLowerCase() || "get", data: $this.serialize(), transition: $this.jqmData( "transition" ), direction: $this.jqmData( "direction" ), reloadPage: true } ); event.preventDefault(); }); //add active state on vclick $( document ).bind( "vclick", function( event ) { var link = findClosestLink( event.target ); if ( link ) { if ( path.parseUrl( link.getAttribute( "href" ) || "#" ).hash !== "#" ) { $( link ).closest( ".ui-btn" ).not( ".ui-disabled" ).addClass( $.mobile.activeBtnClass ); $( "." + $.mobile.activePageClass + " .ui-btn" ).not( link ).blur(); } } }); // click routing - direct to HTTP or Ajax, accordingly $( document ).bind( "click", function( event ) { var link = findClosestLink( event.target ); if ( !link ) { return; } var $link = $( link ), //remove active link class if external (then it won't be there if you come back) httpCleanup = function(){ window.setTimeout( function() { removeActiveLinkClass( true ); }, 200 ); }; //if there's a data-rel=back attr, go back in history if( $link.is( ":jqmData(rel='back')" ) ) { window.history.back(); return false; } //if ajax is disabled, exit early if( !$.mobile.ajaxEnabled ){ httpCleanup(); //use default click handling return; } var baseUrl = getClosestBaseUrl( $link ), //get href, if defined, otherwise default to empty hash href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl ); // XXX_jblas: Ideally links to application pages should be specified as // an url to the application document with a hash that is either // the site relative path or id to the page. But some of the // internal code that dynamically generates sub-pages for nested // lists and select dialogs, just write a hash in the link they // create. This means the actual URL path is based on whatever // the current value of the base tag is at the time this code // is called. For now we are just assuming that any url with a // hash in it is an application page reference. if ( href.search( "#" ) != -1 ) { href = href.replace( /[^#]*#/, "" ); if ( !href ) { //link was an empty hash meant purely //for interaction, so we ignore it. event.preventDefault(); return; } else if ( path.isPath( href ) ) { //we have apath so make it the href we want to load. href = path.makeUrlAbsolute( href, baseUrl ); } else { //we have a simple id so use the documentUrl as its base. href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash ); } } // Should we handle this link, or let the browser deal with it? var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ), // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR // requests if the document doing the request was loaded via the file:// protocol. // This is usually to allow the application to "phone home" and fetch app specific // data. We normally let the browser handle external/cross-domain urls, but if the // allowCrossDomainPages option is true, we will allow cross-domain http/https // requests to go through our page loading logic. isCrossDomainPageLoad = ( $.mobile.allowCrossDomainPages && documentUrl.protocol === "file:" && href.search( /^https?:/ ) != -1 ), //check for protocol or rel and its not an embedded page //TODO overlap in logic from isExternal, rel=external check should be // moved into more comprehensive isExternalLink isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !isCrossDomainPageLoad ); $activeClickedLink = $link.closest( ".ui-btn" ); if( isExternal ) { httpCleanup(); //use default click handling return; } //use ajax var transition = $link.jqmData( "transition" ), direction = $link.jqmData( "direction" ), reverse = ( direction && direction === "reverse" ) || // deprecated - remove by 1.0 $link.jqmData( "back" ), //this may need to be more specific as we use data-rel more role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined; $.mobile.changePage( href, { transition: transition, reverse: reverse, role: role } ); event.preventDefault(); }); //prefetch pages when anchors with data-prefetch are encountered $( ".ui-page" ).live( "pageshow.prefetch", function(){ var urls = []; $( this ).find( "a:jqmData(prefetch)" ).each(function(){ var url = $( this ).attr( "href" ); if ( url && $.inArray( url, urls ) === -1 ) { urls.push( url ); $.mobile.loadPage( url ); } }); } ); //hashchange event handler $window.bind( "hashchange", function( e, triggered ) { //find first page via hash var to = path.stripHash( location.hash ), //transition is false if it's the first page, undefined otherwise (and may be overridden by default) transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined; //if listening is disabled (either globally or temporarily), or it's a dialog hash if( !$.mobile.hashListeningEnabled || urlHistory.ignoreNextHashChange ) { urlHistory.ignoreNextHashChange = false; return; } // special case for dialogs if( urlHistory.stack.length > 1 && to.indexOf( dialogHashKey ) > -1 ) { // If current active page is not a dialog skip the dialog and continue // in the same direction if(!$.mobile.activePage.is( ".ui-dialog" )) { //determine if we're heading forward or backward and continue accordingly past //the current dialog urlHistory.directHashChange({ currentUrl: to, isBack: function() { window.history.back(); }, isForward: function() { window.history.forward(); } }); // prevent changepage return; } else { var setTo = function() { to = $.mobile.urlHistory.getActive().pageUrl; }; // if the current active page is a dialog and we're navigating // to a dialog use the dialog objected saved in the stack urlHistory.directHashChange({ currentUrl: to, isBack: setTo, isForward: setTo }); } } //if to is defined, load it if ( to ) { to = ( typeof to === "string" && !path.isPath( to ) ) ? ( '#' + to ) : to; $.mobile.changePage( to, { transition: transition, changeHash: false, fromHashChange: true } ); } //there's no hash, go to the first page in the dom else { $.mobile.changePage( $.mobile.firstPage, { transition: transition, changeHash: false, fromHashChange: true } ); } }); //set page min-heights to be device specific $( document ).bind( "pageshow", resetActivePageHeight ); $( window ).bind( "throttledresize", resetActivePageHeight ); };//_registerInternalEvents callback })( jQuery ); /*! * jQuery Mobile v@VERSION * http://jquerymobile.com/ * * Copyright 2010, jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, window, undefined ) { function css3TransitionHandler( name, reverse, $to, $from ) { var deferred = new $.Deferred(), reverseClass = reverse ? " reverse" : "", viewportClass = "ui-mobile-viewport-transitioning viewport-" + name, doneFunc = function() { $to.add( $from ).removeClass( "out in reverse " + name ); if ( $from ) { $from.removeClass( $.mobile.activePageClass ); } $to.parent().removeClass( viewportClass ); deferred.resolve( name, reverse, $to, $from ); }; $to.animationComplete( doneFunc ); $to.parent().addClass( viewportClass ); if ( $from ) { $from.addClass( name + " out" + reverseClass ); } $to.addClass( $.mobile.activePageClass + " " + name + " in" + reverseClass ); return deferred.promise(); } // Make our transition handler public. $.mobile.css3TransitionHandler = css3TransitionHandler; // If the default transition handler is the 'none' handler, replace it with our handler. if ( $.mobile.defaultTransitionHandler === $.mobile.noneTransitionHandler ) { $.mobile.defaultTransitionHandler = css3TransitionHandler; } })( jQuery, this ); /* * jQuery Mobile Framework : "degradeInputs" plugin - degrades inputs to another type after custom enhancements are made. * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.mobile.page.prototype.options.degradeInputs = { color: false, date: false, datetime: false, "datetime-local": false, email: false, month: false, number: false, range: "number", search: true, tel: false, time: false, url: false, week: false }; $.mobile.page.prototype.options.keepNative = ":jqmData(role='none'), :jqmData(role='nojs')"; //auto self-init widgets $( document ).bind( "pagecreate enhance", function( e ){ var page = $( e.target ).data( "page" ), o = page.options; // degrade inputs to avoid poorly implemented native functionality $( e.target ).find( "input" ).not( o.keepNative ).each(function() { var $this = $( this ), type = this.getAttribute( "type" ), optType = o.degradeInputs[ type ] || "text"; if ( o.degradeInputs[ type ] ) { $this.replaceWith( $( "<div>" ).html( $this.clone() ).html() .replace( /\s+type=["']?\w+['"]?/, " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\" " ) ); } }); }); })( jQuery );/* * jQuery Mobile Framework : "dialog" plugin. * Copyright (c) jQuery Project * Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses. */ (function( $, window, undefined ) { $.widget( "mobile.dialog", $.mobile.widget, { options: { closeBtnText : "Close", theme : "a", initSelector : ":jqmData(role='dialog')" }, _create: function() { var $el = this.element, pageTheme = $el.attr( "class" ).match( /ui-body-[a-z]/ ); if( pageTheme.length ){ $el.removeClass( pageTheme[ 0 ] ); } $el.addClass( "ui-body-" + this.options.theme ); // Class the markup for dialog styling // Set aria role $el.attr( "role", "dialog" ) .addClass( "ui-dialog" ) .find( ":jqmData(role='header')" ) .addClass( "ui-corner-top ui-overlay-shadow" ) .prepend( "<a href='#' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "rel='back' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" ) .end() .find( ":jqmData(role='content'),:jqmData(role='footer')" ) .last() .addClass( "ui-corner-bottom ui-overlay-shadow" ); /* bind events - clicks and submits should use the closing transition that the dialog opened with unless a data-transition is specified on the link/form - if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally */ $el.bind( "vclick submit", function( event ) { var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ), active; if ( $target.length && !$target.jqmData( "transition" ) ) { active = $.mobile.urlHistory.getActive() || {}; $target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) ) .attr( "data-" + $.mobile.ns + "direction", "reverse" ); } }) .bind( "pagehide", function() { $( this ).find( "." + $.mobile.activeBtnClass ).removeClass( $.mobile.activeBtnClass ); }); }, // Close method goes back in history close: function() { window.history.back(); } }); //auto self-init widgets $( $.mobile.dialog.prototype.options.initSelector ).live( "pagecreate", function(){ $( this ).dialog(); }); })( jQuery, this ); /* * jQuery Mobile Framework : This plugin handles theming and layout of headers, footers, and content areas * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.mobile.page.prototype.options.backBtnText = "Back"; $.mobile.page.prototype.options.addBackBtn = false; $.mobile.page.prototype.options.backBtnTheme = null; $.mobile.page.prototype.options.headerTheme = "a"; $.mobile.page.prototype.options.footerTheme = "a"; $.mobile.page.prototype.options.contentTheme = null; $( ":jqmData(role='page'), :jqmData(role='dialog')" ).live( "pagecreate", function( e ) { var $page = $( this ), o = $page.data( "page" ).options, pageTheme = o.theme; $( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", this ).each(function() { var $this = $( this ), role = $this.jqmData( "role" ), theme = $this.jqmData( "theme" ), $headeranchors, leftbtn, rightbtn, backBtn; $this.addClass( "ui-" + role ); //apply theming and markup modifications to page,header,content,footer if ( role === "header" || role === "footer" ) { var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme; //add theme class $this.addClass( "ui-bar-" + thisTheme ); // Add ARIA role $this.attr( "role", role === "header" ? "banner" : "contentinfo" ); // Right,left buttons $headeranchors = $this.children( "a" ); leftbtn = $headeranchors.hasClass( "ui-btn-left" ); rightbtn = $headeranchors.hasClass( "ui-btn-right" ); if ( !leftbtn ) { leftbtn = $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length; } if ( !rightbtn ) { rightbtn = $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length; } // Auto-add back btn on pages beyond first view if ( o.addBackBtn && role === "header" && $( ".ui-page" ).length > 1 && $this.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) && !leftbtn ) { backBtn = $( "<a href='#' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" ).prependTo( $this ); // If theme is provided, override default inheritance backBtn.attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme ); } // Page title $this.children( "h1, h2, h3, h4, h5, h6" ) .addClass( "ui-title" ) // Regardless of h element number in src, it becomes h1 for the enhanced page .attr({ "tabindex": "0", "role": "heading", "aria-level": "1" }); } else if ( role === "content" ) { $this.addClass( "ui-body-" + ( theme || pageTheme || o.contentTheme ) ); // Add ARIA role $this.attr( "role", "main" ); } }); }); })( jQuery );/* * jQuery Mobile Framework : "collapsible" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.collapsible", $.mobile.widget, { options: { expandCueText: " click to expand contents", collapseCueText: " click to collapse contents", collapsed: false, heading: ">:header,>legend", theme: null, iconTheme: "d", initSelector: ":jqmData(role='collapsible')" }, _create: function() { var $el = this.element, o = this.options, collapsibleContain = $el.addClass( "ui-collapsible-contain" ), collapsibleHeading = $el.find( o.heading ).eq( 0 ), collapsibleContent = collapsibleContain.wrapInner( "<div class='ui-collapsible-content'></div>" ).find( ".ui-collapsible-content" ), collapsibleParent = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" ); // Replace collapsibleHeading if it's a legend if ( collapsibleHeading.is( "legend" ) ) { collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading ); collapsibleHeading.next().remove(); } collapsibleHeading //drop heading in before content .insertBefore( collapsibleContent ) //modify markup & attributes .addClass( "ui-collapsible-heading" ) .append( "<span class='ui-collapsible-heading-status'></span>" ) .wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" ) .find( "a:eq(0)" ) .buttonMarkup({ shadow: !collapsibleParent.length, corners: false, iconPos: "left", icon: "plus", theme: o.theme }) .find( ".ui-icon" ) .removeAttr( "class" ) .buttonMarkup({ shadow: true, corners: true, iconPos: "notext", icon: "plus", theme: o.iconTheme }); if ( !collapsibleParent.length ) { collapsibleHeading .find( "a:eq(0)" ) .addClass( "ui-corner-all" ) .find( ".ui-btn-inner" ) .addClass( "ui-corner-all" ); } else { if ( collapsibleContain.jqmData( "collapsible-last" ) ) { collapsibleHeading .find( "a:eq(0), .ui-btn-inner" ) .addClass( "ui-corner-bottom" ); } } //events collapsibleContain .bind( "collapse", function( event ) { if ( ! event.isDefaultPrevented() && $( event.target ).closest( ".ui-collapsible-contain" ).is( collapsibleContain ) ) { event.preventDefault(); collapsibleHeading .addClass( "ui-collapsible-heading-collapsed" ) .find( ".ui-collapsible-heading-status" ) .text( o.expandCueText ) .end() .find( ".ui-icon" ) .removeClass( "ui-icon-minus" ) .addClass( "ui-icon-plus" ); collapsibleContent.addClass( "ui-collapsible-content-collapsed" ).attr( "aria-hidden", true ); if ( collapsibleContain.jqmData( "collapsible-last" ) ) { collapsibleHeading .find( "a:eq(0), .ui-btn-inner" ) .addClass( "ui-corner-bottom" ); } } }) .bind( "expand", function( event ) { if ( !event.isDefaultPrevented() ) { event.preventDefault(); collapsibleHeading .removeClass( "ui-collapsible-heading-collapsed" ) .find( ".ui-collapsible-heading-status" ).text( o.collapseCueText ); collapsibleHeading.find( ".ui-icon" ).removeClass( "ui-icon-plus" ).addClass( "ui-icon-minus" ); collapsibleContent.removeClass( "ui-collapsible-content-collapsed" ).attr( "aria-hidden", false ); if ( collapsibleContain.jqmData( "collapsible-last" ) ) { collapsibleHeading .find( "a:eq(0), .ui-btn-inner" ) .removeClass( "ui-corner-bottom" ); } } }) .trigger( o.collapsed ? "collapse" : "expand" ); // Close others in a set if ( collapsibleParent.length && !collapsibleParent.jqmData( "collapsiblebound" ) ) { collapsibleParent .jqmData( "collapsiblebound", true ) .bind( "expand", function( event ) { $( event.target ) .closest( ".ui-collapsible-contain" ) .siblings( ".ui-collapsible-contain" ) .trigger( "collapse" ); }); var set = collapsibleParent.children( ":jqmData(role='collapsible')" ); set.first() .find( "a:eq(0)" ) .addClass( "ui-corner-top" ) .find( ".ui-btn-inner" ) .addClass( "ui-corner-top" ); set.last().jqmData( "collapsible-last", true ); } collapsibleHeading .bind( "vclick", function( event ) { var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ? "expand" : "collapse"; collapsibleContain.trigger( type ); event.preventDefault(); }); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.collapsible.prototype.options.initSelector, e.target ).collapsible(); }); })( jQuery ); /* * jQuery Mobile Framework : "fieldcontain" plugin - simple class additions to make form row separators * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.fn.fieldcontain = function( options ) { return this.addClass( "ui-field-contain ui-body ui-br" ); }; //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='fieldcontain')", e.target ).fieldcontain(); }); })( jQuery );/* * jQuery Mobile Framework : plugin for creating CSS grids * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.fn.grid = function( options ) { return this.each(function() { var $this = $( this ), o = $.extend({ grid: null },options), $kids = $this.children(), gridCols = {solo:1, a:2, b:3, c:4, d:5}, grid = o.grid, iterator; if ( !grid ) { if ( $kids.length <= 5 ) { for ( var letter in gridCols ) { if ( gridCols[ letter ] === $kids.length ) { grid = letter; } } } else { grid = "a"; } } iterator = gridCols[grid]; $this.addClass( "ui-grid-" + grid ); $kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" ); if ( iterator > 1 ) { $kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" ); } if ( iterator > 2 ) { $kids.filter( ":nth-child(3n+3)" ).addClass( "ui-block-c" ); } if ( iterator > 3 ) { $kids.filter( ":nth-child(4n+4)" ).addClass( "ui-block-d" ); } if ( iterator > 4 ) { $kids.filter( ":nth-child(5n+5)" ).addClass( "ui-block-e" ); } }); }; })( jQuery );/* * jQuery Mobile Framework : "navbar" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.navbar", $.mobile.widget, { options: { iconpos: "top", grid: null, initSelector: ":jqmData(role='navbar')" }, _create: function(){ var $navbar = this.element, $navbtns = $navbar.find( "a" ), iconpos = $navbtns.filter( ":jqmData(icon)" ).length ? this.options.iconpos : undefined; $navbar.addClass( "ui-navbar" ) .attr( "role","navigation" ) .find( "ul" ) .grid({ grid: this.options.grid }); if ( !iconpos ) { $navbar.addClass( "ui-navbar-noicons" ); } $navbtns.buttonMarkup({ corners: false, shadow: false, iconpos: iconpos }); $navbar.delegate( "a", "vclick", function( event ) { $navbtns.not( ".ui-state-persist" ).removeClass( $.mobile.activeBtnClass ); $( this ).addClass( $.mobile.activeBtnClass ); }); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.navbar.prototype.options.initSelector, e.target ).navbar(); }); })( jQuery ); /* * jQuery Mobile Framework : "listview" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { //Keeps track of the number of lists per page UID //This allows support for multiple nested list in the same page //https://github.com/jquery/jquery-mobile/issues/1617 var listCountPerPage = {}; $.widget( "mobile.listview", $.mobile.widget, { options: { theme: "c", countTheme: "c", headerTheme: "b", dividerTheme: "b", splitIcon: "arrow-r", splitTheme: "b", inset: false, initSelector: ":jqmData(role='listview')" }, _create: function() { var t = this; // create listview markup t.element.addClass(function( i, orig ) { return orig + " ui-listview " + ( t.options.inset ? " ui-listview-inset ui-corner-all ui-shadow " : "" ); }); t.refresh(); }, _itemApply: function( $list, item ) { // TODO class has to be defined in markup item.find( ".ui-li-count" ) .addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme ) + " ui-btn-corner-all" ).end() .find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" ).end() .find( "p, dl" ).addClass( "ui-li-desc" ).end() .find( ">img:eq(0), .ui-link-inherit>img:eq(0)" ).addClass( "ui-li-thumb" ).each(function() { item.addClass( $(this).is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" ); }).end() .find( ".ui-li-aside" ).each(function() { var $this = $(this); $this.prependTo( $this.parent() ); //shift aside to front for css float }); }, _removeCorners: function( li, which ) { var top = "ui-corner-top ui-corner-tr ui-corner-tl", bot = "ui-corner-bottom ui-corner-br ui-corner-bl"; li = li.add( li.find( ".ui-btn-inner, .ui-li-link-alt, .ui-li-thumb" ) ); if ( which === "top" ) { li.removeClass( top ); } else if ( which === "bottom" ) { li.removeClass( bot ); } else { li.removeClass( top + " " + bot ); } }, refresh: function( create ) { this.parentPage = this.element.closest( ".ui-page" ); this._createSubPages(); var o = this.options, $list = this.element, self = this, dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme, listsplittheme = $list.jqmData( "splittheme" ), listspliticon = $list.jqmData( "spliticon" ), li = $list.children( "li" ), counter = $.support.cssPseudoElement || !$.nodeName( $list[ 0 ], "ol" ) ? 0 : 1, item, itemClass, itemTheme, a, last, splittheme, countParent, icon; if ( counter ) { $list.find( ".ui-li-dec" ).remove(); } for ( var pos = 0, numli = li.length; pos < numli; pos++ ) { item = li.eq( pos ); itemClass = "ui-li"; // If we're creating the element, we update it regardless if ( create || !item.hasClass( "ui-li" ) ) { itemTheme = item.jqmData("theme") || o.theme; a = item.children( "a" ); if ( a.length ) { icon = item.jqmData("icon"); item.buttonMarkup({ wrapperEls: "div", shadow: false, corners: false, iconpos: "right", icon: a.length > 1 || icon === false ? false : icon || "arrow-r", theme: itemTheme }); a.first().addClass( "ui-link-inherit" ); if ( a.length > 1 ) { itemClass += " ui-li-has-alt"; last = a.last(); splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme; last.appendTo(item) .attr( "title", last.text() ) .addClass( "ui-li-link-alt" ) .empty() .buttonMarkup({ shadow: false, corners: false, theme: itemTheme, icon: false, iconpos: false }) .find( ".ui-btn-inner" ) .append( $( "<span />" ).buttonMarkup({ shadow: true, corners: true, theme: splittheme, iconpos: "notext", icon: listspliticon || last.jqmData( "icon" ) || o.splitIcon }) ); } } else if ( item.jqmData( "role" ) === "list-divider" ) { itemClass += " ui-li-divider ui-btn ui-bar-" + dividertheme; item.attr( "role", "heading" ); //reset counter when a divider heading is encountered if ( counter ) { counter = 1; } } else { itemClass += " ui-li-static ui-body-" + itemTheme; } } if ( o.inset ) { if ( pos === 0 ) { itemClass += " ui-corner-top"; item.add( item.find( ".ui-btn-inner" ) ) .find( ".ui-li-link-alt" ) .addClass( "ui-corner-tr" ) .end() .find( ".ui-li-thumb" ) .addClass( "ui-corner-tl" ); if ( item.next().next().length ) { self._removeCorners( item.next() ); } } if ( pos === li.length - 1 ) { itemClass += " ui-corner-bottom"; item.add( item.find( ".ui-btn-inner" ) ) .find( ".ui-li-link-alt" ) .addClass( "ui-corner-br" ) .end() .find( ".ui-li-thumb" ) .addClass( "ui-corner-bl" ); if ( item.prev().prev().length ) { self._removeCorners( item.prev() ); } else if ( item.prev().length ) { self._removeCorners( item.prev(), "bottom" ); } } } if ( counter && itemClass.indexOf( "ui-li-divider" ) < 0 ) { countParent = item.is( ".ui-li-static:first" ) ? item : item.find( ".ui-link-inherit" ); countParent.addClass( "ui-li-jsnumbering" ) .prepend( "<span class='ui-li-dec'>" + (counter++) + ". </span>" ); } item.add( item.children( ".ui-btn-inner" ) ).addClass( itemClass ); if ( !create ) { self._itemApply( $list, item ); } } }, //create a string for ID/subpage url creation _idStringEscape: function( str ) { return str.replace(/[^a-zA-Z0-9]/g, '-'); }, _createSubPages: function() { var parentList = this.element, parentPage = parentList.closest( ".ui-page" ), parentUrl = parentPage.jqmData( "url" ), parentId = parentUrl || parentPage[ 0 ][ $.expando ], parentListId = parentList.attr( "id" ), o = this.options, dns = "data-" + $.mobile.ns, self = this, persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ), hasSubPages; if ( typeof listCountPerPage[ parentId ] === "undefined" ) { listCountPerPage[ parentId ] = -1; } parentListId = parentListId || ++listCountPerPage[ parentId ]; $( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) { var self = this, list = $( this ), listId = list.attr( "id" ) || parentListId + "-" + i, parent = list.parent(), nodeEls = $( list.prevAll().toArray().reverse() ), nodeEls = nodeEls.length ? nodeEls : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ), title = nodeEls.first().text(),//url limits to first 30 chars of text id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId, theme = list.jqmData( "theme" ) || o.theme, countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme, newPage, anchor; //define hasSubPages for use in later removal hasSubPages = true; newPage = list.detach() .wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" ) .parent() .before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" ) .after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>") : "" ) .parent() .appendTo( $.mobile.pageContainer ); newPage.page(); anchor = parent.find('a:first'); if ( !anchor.length ) { anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() ); } anchor.attr( "href", "#" + id ); }).listview(); //on pagehide, remove any nested pages along with the parent page, as long as they aren't active if( hasSubPages && parentPage.data("page").options.domCache === false ){ var newRemove = function( e, ui ){ var nextPage = ui.nextPage, npURL; if( ui.nextPage ){ npURL = nextPage.jqmData( "url" ); if( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ){ self.childPages().remove(); parentPage.remove(); } } }; // unbind the original page remove and replace with our specialized version parentPage .unbind( "pagehide.remove" ) .bind( "pagehide.remove", newRemove); } }, // TODO sort out a better way to track sub pages of the listview this is brittle childPages: function(){ var parentUrl = this.parentPage.jqmData( "url" ); return $( ":jqmData(url^='"+ parentUrl + "&" + $.mobile.subPageUrlKey +"')"); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.listview.prototype.options.initSelector, e.target ).listview(); }); })( jQuery ); /* * jQuery Mobile Framework : "listview" filter extension * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.mobile.listview.prototype.options.filter = false; $.mobile.listview.prototype.options.filterPlaceholder = "Filter items..."; $.mobile.listview.prototype.options.filterTheme = "c"; $( ":jqmData(role='listview')" ).live( "listviewcreate", function() { var list = $( this ), listview = list.data( "listview" ); if ( !listview.options.filter ) { return; } var wrapper = $( "<form>", { "class": "ui-listview-filter ui-bar-" + listview.options.filterTheme, "role": "search" }), search = $( "<input>", { placeholder: listview.options.filterPlaceholder }) .attr( "data-" + $.mobile.ns + "type", "search" ) .jqmData( "lastval", "" ) .bind( "keyup change", function() { var $this = $(this), val = this.value.toLowerCase(), listItems = null, lastval = $this.jqmData( "lastval" ) + "", childItems = false, itemtext = "", item; // Change val as lastval for next execution $this.jqmData( "lastval" , val ); change = val.replace( new RegExp( "^" + lastval ) , "" ); if ( val.length < lastval.length || change.length != ( val.length - lastval.length ) ) { // Removed chars or pasted something totaly different, check all items listItems = list.children(); } else { // Only chars added, not removed, only use visible subset listItems = list.children( ":not(.ui-screen-hidden)" ); } if ( val ) { // This handles hiding regular rows without the text we search for // and any list dividers without regular rows shown under it for ( var i = listItems.length - 1; i >= 0; i-- ) { item = $( listItems[ i ] ); itemtext = item.jqmData( "filtertext" ) || item.text(); if ( item.is( "li:jqmData(role=list-divider)" ) ) { item.toggleClass( "ui-filter-hidequeue" , !childItems ); // New bucket! childItems = false; } else if ( itemtext.toLowerCase().indexOf( val ) === -1 ) { //mark to be hidden item.toggleClass( "ui-filter-hidequeue" , true ); } else { // There"s a shown item in the bucket childItems = true; } } // Show items, not marked to be hidden listItems .filter( ":not(.ui-filter-hidequeue)" ) .toggleClass( "ui-screen-hidden", false ); // Hide items, marked to be hidden listItems .filter( ".ui-filter-hidequeue" ) .toggleClass( "ui-screen-hidden", true ) .toggleClass( "ui-filter-hidequeue", false ); } else { //filtervalue is empty => show all listItems.toggleClass( "ui-screen-hidden", false ); } }) .appendTo( wrapper ) .textinput(); if ( $( this ).jqmData( "inset" ) ) { wrapper.addClass( "ui-listview-filter-inset" ); } wrapper.bind( "submit", function() { return false; }) .insertBefore( list ); }); })( jQuery );/* * jQuery Mobile Framework : "fieldcontain" plugin - simple class additions to make form row separators * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" ); }); })( jQuery );/* * jQuery Mobile Framework : "checkboxradio" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.checkboxradio", $.mobile.widget, { options: { theme: null, initSelector: "input[type='checkbox'],input[type='radio']" }, _create: function() { var self = this, input = this.element, // NOTE: Windows Phone could not find the label through a selector // filter works though. label = input.closest( "form,fieldset,:jqmData(role='page')" ).find( "label" ).filter( "[for='" + input[ 0 ].id + "']"), inputtype = input.attr( "type" ), checkedState = inputtype + "-on", uncheckedState = inputtype + "-off", icon = input.parents( ":jqmData(type='horizontal')" ).length ? undefined : uncheckedState, activeBtn = icon ? "" : " " + $.mobile.activeBtnClass, checkedClass = "ui-" + checkedState + activeBtn, uncheckedClass = "ui-" + uncheckedState, checkedicon = "ui-icon-" + checkedState, uncheckedicon = "ui-icon-" + uncheckedState; if ( inputtype !== "checkbox" && inputtype !== "radio" ) { return; } // Expose for other methods $.extend( this, { label: label, inputtype: inputtype, checkedClass: checkedClass, uncheckedClass: uncheckedClass, checkedicon: checkedicon, uncheckedicon: uncheckedicon }); // If there's no selected theme... if( !this.options.theme ) { this.options.theme = this.element.jqmData( "theme" ); } label.buttonMarkup({ theme: this.options.theme, icon: icon, shadow: false }); // Wrap the input + label in a div input.add( label ) .wrapAll( "<div class='ui-" + inputtype + "'></div>" ); label.bind({ vmouseover: function() { if ( $( this ).parent().is( ".ui-disabled" ) ) { return false; } }, vclick: function( event ) { if ( input.is( ":disabled" ) ) { event.preventDefault(); return; } self._cacheVals(); input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) ); // Input set for common radio buttons will contain all the radio // buttons, but will not for checkboxes. clearing the checked status // of other radios ensures the active button state is applied properly self._getInputSet().not( input ).prop( "checked", false ); self._updateAll(); return false; } }); input .bind({ vmousedown: function() { this._cacheVals(); }, vclick: function() { var $this = $(this); // Adds checked attribute to checked input when keyboard is used if ( $this.is( ":checked" ) ) { $this.prop( "checked", true); self._getInputSet().not($this).prop( "checked", false ); } else { $this.prop( "checked", false ); } self._updateAll(); }, focus: function() { label.addClass( "ui-focus" ); }, blur: function() { label.removeClass( "ui-focus" ); } }); this.refresh(); }, _cacheVals: function() { this._getInputSet().each(function() { var $this = $(this); $this.jqmData( "cacheVal", $this.is( ":checked" ) ); }); }, //returns either a set of radios with the same name attribute, or a single checkbox _getInputSet: function(){ if(this.inputtype == "checkbox") { return this.element; } return this.element.closest( "form,fieldset,:jqmData(role='page')" ) .find( "input[name='"+ this.element.attr( "name" ) +"'][type='"+ this.inputtype +"']" ); }, _updateAll: function() { var self = this; this._getInputSet().each(function() { var $this = $(this); if ( $this.is( ":checked" ) || self.inputtype === "checkbox" ) { $this.trigger( "change" ); } }) .checkboxradio( "refresh" ); }, refresh: function() { var input = this.element, label = this.label, icon = label.find( ".ui-icon" ); // input[0].checked expando doesn't always report the proper value // for checked='checked' if ( $( input[ 0 ] ).prop( "checked" ) ) { label.addClass( this.checkedClass ).removeClass( this.uncheckedClass ); icon.addClass( this.checkedicon ).removeClass( this.uncheckedicon ); } else { label.removeClass( this.checkedClass ).addClass( this.uncheckedClass ); icon.removeClass( this.checkedicon ).addClass( this.uncheckedicon ); } if ( input.is( ":disabled" ) ) { this.disable(); } else { this.enable(); } }, disable: function() { this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" ); }, enable: function() { this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.checkboxradio.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .checkboxradio(); }); })( jQuery ); /* * jQuery Mobile Framework : "button" plugin - links that proxy to native input/buttons * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.button", $.mobile.widget, { options: { theme: null, icon: null, iconpos: null, inline: null, corners: true, shadow: true, iconshadow: true, initSelector: "button, [type='button'], [type='submit'], [type='reset'], [type='image']" }, _create: function() { var $el = this.element, o = this.options, type; // Add ARIA role this.button = $( "<div></div>" ) .text( $el.text() || $el.val() ) .buttonMarkup({ theme: o.theme, icon: o.icon, iconpos: o.iconpos, inline: o.inline, corners: o.corners, shadow: o.shadow, iconshadow: o.iconshadow }) .insertBefore( $el ) .append( $el.addClass( "ui-btn-hidden" ) ); // Add hidden input during submit type = $el.attr( "type" ); if ( type !== "button" && type !== "reset" ) { $el.bind( "vclick", function() { var $buttonPlaceholder = $( "<input>", { type: "hidden", name: $el.attr( "name" ), value: $el.attr( "value" ) }) .insertBefore( $el ); // Bind to doc to remove after submit handling $( document ).submit(function(){ $buttonPlaceholder.remove(); }); }); } this.refresh(); }, enable: function() { this.element.attr( "disabled", false ); this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); }, disable: function() { this.element.attr( "disabled", true ); this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); }, refresh: function() { if ( this.element.attr( "disabled" ) ) { this.disable(); } else { this.enable(); } } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.button.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .button(); }); })( jQuery );/* * jQuery Mobile Framework : "slider" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ ( function( $, undefined ) { $.widget( "mobile.slider", $.mobile.widget, { options: { theme: null, trackTheme: null, disabled: false, initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')" }, _create: function() { // TODO: Each of these should have comments explain what they're for var self = this, control = this.element, parentTheme = control.parents( "[class*='ui-bar-'],[class*='ui-body-']" ).eq( 0 ), parentTheme = parentTheme.length ? parentTheme.attr( "class" ).match( /ui-(bar|body)-([a-z])/ )[ 2 ] : "c", theme = this.options.theme ? this.options.theme : parentTheme, trackTheme = this.options.trackTheme ? this.options.trackTheme : parentTheme, cType = control[ 0 ].nodeName.toLowerCase(), selectClass = ( cType == "select" ) ? "ui-slider-switch" : "", controlID = control.attr( "id" ), labelID = controlID + "-label", label = $( "[for='"+ controlID +"']" ).attr( "id", labelID ), val = function() { return cType == "input" ? parseFloat( control.val() ) : control[0].selectedIndex; }, min = cType == "input" ? parseFloat( control.attr( "min" ) ) : 0, max = cType == "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1, step = window.parseFloat( control.attr( "step" ) || 1 ), slider = $( "<div class='ui-slider " + selectClass + " ui-btn-down-" + trackTheme + " ui-btn-corner-all' role='application'></div>" ), handle = $( "<a href='#' class='ui-slider-handle'></a>" ) .appendTo( slider ) .buttonMarkup({ corners: true, theme: theme, shadow: true }) .attr({ "role": "slider", "aria-valuemin": min, "aria-valuemax": max, "aria-valuenow": val(), "aria-valuetext": val(), "title": val(), "aria-labelledby": labelID }), options; $.extend( this, { slider: slider, handle: handle, dragging: false, beforeStart: null }); if ( cType == "select" ) { slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" ); options = control.find( "option" ); control.find( "option" ).each(function( i ) { var side = !i ? "b":"a", corners = !i ? "right" :"left", theme = !i ? " ui-btn-down-" + trackTheme :" ui-btn-active"; $( "<div class='ui-slider-labelbg ui-slider-labelbg-" + side + theme + " ui-btn-corner-" + corners + "'></div>" ) .prependTo( slider ); $( "<span class='ui-slider-label ui-slider-label-" + side + theme + " ui-btn-corner-" + corners + "' role='img'>" + $( this ).text() + "</span>" ) .prependTo( handle ); }); } label.addClass( "ui-slider" ); // monitor the input for updated values control.addClass( cType === "input" ? "ui-slider-input" : "ui-slider-switch" ) .change( function() { self.refresh( val(), true ); }) .keyup( function() { // necessary? self.refresh( val(), true, true ); }) .blur( function() { self.refresh( val(), true ); }); // prevent screen drag when slider activated $( document ).bind( "vmousemove", function( event ) { if ( self.dragging ) { self.refresh( event ); return false; } }); slider.bind( "vmousedown", function( event ) { self.dragging = true; if ( cType === "select" ) { self.beforeStart = control[0].selectedIndex; } self.refresh( event ); return false; }); slider.add( document ) .bind( "vmouseup", function() { if ( self.dragging ) { self.dragging = false; if ( cType === "select" ) { if ( self.beforeStart === control[ 0 ].selectedIndex ) { //tap occurred, but value didn't change. flip it! self.refresh( !self.beforeStart ? 1 : 0 ); } var curval = val(); var snapped = Math.round( curval / ( max - min ) * 100 ); handle .addClass( "ui-slider-handle-snapping" ) .css( "left", snapped + "%" ) .animationComplete( function() { handle.removeClass( "ui-slider-handle-snapping" ); }); } return false; } }); slider.insertAfter( control ); // NOTE force focus on handle this.handle .bind( "vmousedown", function() { $( this ).focus(); }) .bind( "vclick", false ); this.handle .bind( "keydown", function( event ) { var index = val(); if ( self.options.disabled ) { return; } // In all cases prevent the default and mark the handle as active switch ( event.keyCode ) { case $.mobile.keyCode.HOME: case $.mobile.keyCode.END: case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: event.preventDefault(); if ( !self._keySliding ) { self._keySliding = true; $( this ).addClass( "ui-state-active" ); } break; } // move the slider according to the keypress switch ( event.keyCode ) { case $.mobile.keyCode.HOME: self.refresh( min ); break; case $.mobile.keyCode.END: self.refresh( max ); break; case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: self.refresh( index + step ); break; case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: self.refresh( index - step ); break; } }) // remove active mark .keyup( function( event ) { if ( self._keySliding ) { self._keySliding = false; $( this ).removeClass( "ui-state-active" ); } }); this.refresh(undefined, undefined, true); }, refresh: function( val, isfromControl, preventInputUpdate ) { if ( this.options.disabled ) { return; } var control = this.element, percent, cType = control[0].nodeName.toLowerCase(), min = cType === "input" ? parseFloat( control.attr( "min" ) ) : 0, max = cType === "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length - 1; if ( typeof val === "object" ) { var data = val, // a slight tolerance helped get to the ends of the slider tol = 8; if ( !this.dragging || data.pageX < this.slider.offset().left - tol || data.pageX > this.slider.offset().left + this.slider.width() + tol ) { return; } percent = Math.round( ( ( data.pageX - this.slider.offset().left ) / this.slider.width() ) * 100 ); } else { if ( val == null ) { val = cType === "input" ? parseFloat( control.val() ) : control[0].selectedIndex; } percent = ( parseFloat( val ) - min ) / ( max - min ) * 100; } if ( isNaN( percent ) ) { return; } if ( percent < 0 ) { percent = 0; } if ( percent > 100 ) { percent = 100; } var newval = Math.round( ( percent / 100 ) * ( max - min ) ) + min; if ( newval < min ) { newval = min; } if ( newval > max ) { newval = max; } // Flip the stack of the bg colors if ( percent > 60 && cType === "select" ) { // TODO: Dead path? } this.handle.css( "left", percent + "%" ); this.handle.attr( { "aria-valuenow": cType === "input" ? newval : control.find( "option" ).eq( newval ).attr( "value" ), "aria-valuetext": cType === "input" ? newval : control.find( "option" ).eq( newval ).text(), title: newval }); // add/remove classes for flip toggle switch if ( cType === "select" ) { if ( newval === 0 ) { this.slider.addClass( "ui-slider-switch-a" ) .removeClass( "ui-slider-switch-b" ); } else { this.slider.addClass( "ui-slider-switch-b" ) .removeClass( "ui-slider-switch-a" ); } } if ( !preventInputUpdate ) { // update control"s value if ( cType === "input" ) { control.val( newval ); } else { control[ 0 ].selectedIndex = newval; } if ( !isfromControl ) { control.trigger( "change" ); } } }, enable: function() { this.element.attr( "disabled", false ); this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); }, disable: function() { this.element.attr( "disabled", true ); this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.slider.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .slider(); }); })( jQuery );/* * jQuery Mobile Framework : "textinput" plugin for text inputs, textareas * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.textinput", $.mobile.widget, { options: { theme: null, initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea" }, _create: function() { var input = this.element, o = this.options, theme = o.theme, themedParent, themeclass, themeLetter, focusedEl, clearbtn; if ( !theme ) { themedParent = this.element.closest( "[class*='ui-bar-'],[class*='ui-body-']" ); themeLetter = themedParent.length && /ui-(bar|body)-([a-z])/.exec( themedParent.attr( "class" ) ); theme = themeLetter && themeLetter[2] || "c"; } themeclass = " ui-body-" + theme; $( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" ); input.addClass("ui-input-text ui-body-"+ o.theme ); focusedEl = input; // XXX: Temporary workaround for issue 785. Turn off autocorrect and // autocomplete since the popup they use can't be dismissed by // the user. Note that we test for the presence of the feature // by looking for the autocorrect property on the input element. if ( typeof input[0].autocorrect !== "undefined" ) { // Set the attribute instead of the property just in case there // is code that attempts to make modifications via HTML. input[0].setAttribute( "autocorrect", "off" ); input[0].setAttribute( "autocomplete", "off" ); } //"search" input widget if ( input.is( "[type='search'],:jqmData(type='search')" ) ) { focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + "'></div>" ).parent(); clearbtn = $( "<a href='#' class='ui-input-clear' title='clear text'>clear text</a>" ) .tap(function( event ) { input.val( "" ).focus(); input.trigger( "change" ); clearbtn.addClass( "ui-input-clear-hidden" ); event.preventDefault(); }) .appendTo( focusedEl ) .buttonMarkup({ icon: "delete", iconpos: "notext", corners: true, shadow: true }); function toggleClear() { if ( !input.val() ) { clearbtn.addClass( "ui-input-clear-hidden" ); } else { clearbtn.removeClass( "ui-input-clear-hidden" ); } } toggleClear(); input.keyup( toggleClear ) .focus( toggleClear ); } else { input.addClass( "ui-corner-all ui-shadow-inset" + themeclass ); } input.focus(function() { focusedEl.addClass( "ui-focus" ); }) .blur(function(){ focusedEl.removeClass( "ui-focus" ); }); // Autogrow if ( input.is( "textarea" ) ) { var extraLineHeight = 15, keyupTimeoutBuffer = 100, keyup = function() { var scrollHeight = input[ 0 ].scrollHeight, clientHeight = input[ 0 ].clientHeight; if ( clientHeight < scrollHeight ) { input.css({ height: (scrollHeight + extraLineHeight) }); } }, keyupTimeout; input.keyup(function() { clearTimeout( keyupTimeout ); keyupTimeout = setTimeout( keyup, keyupTimeoutBuffer ); }); } }, disable: function(){ ( this.element.attr( "disabled", true ).is( "[type='search'],:jqmData(type='search')" ) ? this.element.parent() : this.element ).addClass( "ui-disabled" ); }, enable: function(){ ( this.element.attr( "disabled", false).is( "[type='search'],:jqmData(type='search')" ) ? this.element.parent() : this.element ).removeClass( "ui-disabled" ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.textinput.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .textinput(); }); })( jQuery ); /* * jQuery Mobile Framework : "selectmenu" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.selectmenu", $.mobile.widget, { options: { theme: null, disabled: false, icon: "arrow-d", iconpos: "right", inline: null, corners: true, shadow: true, iconshadow: true, menuPageTheme: "b", overlayTheme: "a", hidePlaceholderMenuItems: true, closeText: "Close", nativeMenu: true, initSelector: "select:not(:jqmData(role='slider'))" }, _create: function() { var self = this, o = this.options, select = this.element .wrap( "<div class='ui-select'>" ), selectID = select.attr( "id" ), label = $( "label[for='"+ selectID +"']" ).addClass( "ui-select" ), // IE throws an exception at options.item() function when // there is no selected item // select first in this case selectedIndex = select[ 0 ].selectedIndex == -1 ? 0 : select[ 0 ].selectedIndex, button = ( self.options.nativeMenu ? $( "<div/>" ) : $( "<a>", { "href": "#", "role": "button", "id": buttonId, "aria-haspopup": "true", "aria-owns": menuId }) ) .text( $( select[ 0 ].options.item( selectedIndex ) ).text() ) .insertBefore( select ) .buttonMarkup({ theme: o.theme, icon: o.icon, iconpos: o.iconpos, inline: o.inline, corners: o.corners, shadow: o.shadow, iconshadow: o.iconshadow }), // Multi select or not isMultiple = self.isMultiple = select[ 0 ].multiple; // Opera does not properly support opacity on select elements // In Mini, it hides the element, but not its text // On the desktop,it seems to do the opposite // for these reasons, using the nativeMenu option results in a full native select in Opera if ( o.nativeMenu && window.opera && window.opera.version ) { select.addClass( "ui-select-nativeonly" ); } //vars for non-native menus if ( !o.nativeMenu ) { var options = select.find("option"), buttonId = selectID + "-button", menuId = selectID + "-menu", thisPage = select.closest( ".ui-page" ), //button theme theme = /ui-btn-up-([a-z])/.exec( button.attr( "class" ) )[1], menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' data-" +$.mobile.ns + "theme='"+ o.menuPageTheme +"'>" + "<div data-" + $.mobile.ns + "role='header'>" + "<div class='ui-title'>" + label.text() + "</div>"+ "</div>"+ "<div data-" + $.mobile.ns + "role='content'></div>"+ "</div>" ) .appendTo( $.mobile.pageContainer ) .page(), menuPageContent = menuPage.find( ".ui-content" ), menuPageClose = menuPage.find( ".ui-header a" ), screen = $( "<div>", {"class": "ui-selectmenu-screen ui-screen-hidden"}) .appendTo( thisPage ), listbox = $("<div>", { "class": "ui-selectmenu ui-selectmenu-hidden ui-overlay-shadow ui-corner-all ui-body-" + o.overlayTheme + " " + $.mobile.defaultDialogTransition }) .insertAfter(screen), list = $( "<ul>", { "class": "ui-selectmenu-list", "id": menuId, "role": "listbox", "aria-labelledby": buttonId }) .attr( "data-" + $.mobile.ns + "theme", theme ) .appendTo( listbox ), header = $( "<div>", { "class": "ui-header ui-bar-" + theme }) .prependTo( listbox ), headerTitle = $( "<h1>", { "class": "ui-title" }) .appendTo( header ), headerClose = $( "<a>", { "text": o.closeText, "href": "#", "class": "ui-btn-left" }) .attr( "data-" + $.mobile.ns + "iconpos", "notext" ) .attr( "data-" + $.mobile.ns + "icon", "delete" ) .appendTo( header ) .buttonMarkup(), menuType; } // End non native vars // Add counter for multi selects if ( isMultiple ) { self.buttonCount = $( "<span>" ) .addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" ) .hide() .appendTo( button ); } // Disable if specified if ( o.disabled ) { this.disable(); } // Events on native select select.change(function() { self.refresh(); }); // Expose to other methods $.extend( self, { select: select, optionElems: options, selectID: selectID, label: label, buttonId: buttonId, menuId: menuId, thisPage: thisPage, button: button, menuPage: menuPage, menuPageContent: menuPageContent, screen: screen, listbox: listbox, list: list, menuType: menuType, header: header, headerClose: headerClose, headerTitle: headerTitle, placeholder: "" }); // Support for using the native select menu with a custom button if ( o.nativeMenu ) { select.appendTo( button ) .bind( "vmousedown", function() { // Add active class to button button.addClass( $.mobile.activeBtnClass ); }) .bind( "focus vmouseover", function() { button.trigger( "vmouseover" ); }) .bind( "vmousemove", function() { // Remove active class on scroll/touchmove button.removeClass( $.mobile.activeBtnClass ); }) .bind( "change blur vmouseout", function() { button.trigger( "vmouseout" ) .removeClass( $.mobile.activeBtnClass ); }); } else { // Create list from select, update state self.refresh(); select.attr( "tabindex", "-1" ) .focus(function() { $(this).blur(); button.focus(); }); // Button events button.bind( "vclick keydown" , function( event ) { if ( event.type == "vclick" || event.keyCode && ( event.keyCode === $.mobile.keyCode.ENTER || event.keyCode === $.mobile.keyCode.SPACE ) ) { self.open(); event.preventDefault(); } }); // Events for list items list.attr( "role", "listbox" ) .delegate( ".ui-li>a", "focusin", function() { $( this ).attr( "tabindex", "0" ); }) .delegate( ".ui-li>a", "focusout", function() { $( this ).attr( "tabindex", "-1" ); }) .delegate( "li:not(.ui-disabled, .ui-li-divider)", "vclick", function( event ) { var $this = $( this ), // index of option tag to be selected oldIndex = select[ 0 ].selectedIndex, newIndex = $this.jqmData( "option-index" ), option = self.optionElems[ newIndex ]; // toggle selected status on the tag for multi selects option.selected = isMultiple ? !option.selected : true; // toggle checkbox class for multiple selects if ( isMultiple ) { $this.find( ".ui-icon" ) .toggleClass( "ui-icon-checkbox-on", option.selected ) .toggleClass( "ui-icon-checkbox-off", !option.selected ); } // trigger change if value changed if ( isMultiple || oldIndex !== newIndex ) { select.trigger( "change" ); } //hide custom select for single selects only if ( !isMultiple ) { self.close(); } event.preventDefault(); }) //keyboard events for menu items .keydown(function( event ) { var target = $( event.target ), li = target.closest( "li" ), prev, next; // switch logic based on which key was pressed switch ( event.keyCode ) { // up or left arrow keys case 38: prev = li.prev(); // if there's a previous option, focus it if ( prev.length ) { target .blur() .attr( "tabindex", "-1" ); prev.find( "a" ).first().focus(); } return false; break; // down or right arrow keys case 40: next = li.next(); // if there's a next option, focus it if ( next.length ) { target .blur() .attr( "tabindex", "-1" ); next.find( "a" ).first().focus(); } return false; break; // If enter or space is pressed, trigger click case 13: case 32: target.trigger( "vclick" ); return false; break; } }); // button refocus ensures proper height calculation // by removing the inline style and ensuring page inclusion self.menuPage.bind( "pagehide", function(){ self.list.appendTo( self.listbox ); self._focusButton(); }); // Events on "screen" overlay screen.bind( "vclick", function( event ) { self.close(); }); // Close button on small overlays self.headerClose.click(function() { if ( self.menuType == "overlay" ) { self.close(); return false; } }); } }, _buildList: function() { var self = this, o = this.options, placeholder = this.placeholder, optgroups = [], lis = [], dataIcon = self.isMultiple ? "checkbox-off" : "false"; self.list.empty().filter( ".ui-listview" ).listview( "destroy" ); // Populate menu with options from select element self.select.find( "option" ).each(function( i ) { var $this = $( this ), $parent = $this.parent(), text = $this.text(), anchor = "<a href='#'>"+ text +"</a>", classes = [], extraAttrs = []; // Are we inside an optgroup? if ( $parent.is( "optgroup" ) ) { var optLabel = $parent.attr( "label" ); // has this optgroup already been built yet? if ( $.inArray( optLabel, optgroups ) === -1 ) { lis.push( "<li data-" + $.mobile.ns + "role='list-divider'>"+ optLabel +"</li>" ); optgroups.push( optLabel ); } } // Find placeholder text // TODO: Are you sure you want to use getAttribute? ^RW if ( !this.getAttribute( "value" ) || text.length == 0 || $this.jqmData( "placeholder" ) ) { if ( o.hidePlaceholderMenuItems ) { classes.push( "ui-selectmenu-placeholder" ); } placeholder = self.placeholder = text; } // support disabled option tags if ( this.disabled ) { classes.push( "ui-disabled" ); extraAttrs.push( "aria-disabled='true'" ); } lis.push( "<li data-" + $.mobile.ns + "option-index='" + i + "' data-" + $.mobile.ns + "icon='"+ dataIcon +"' class='"+ classes.join(" ") + "' " + extraAttrs.join(" ") +">"+ anchor +"</li>" ) }); self.list.html( lis.join(" ") ); self.list.find( "li" ) .attr({ "role": "option", "tabindex": "-1" }) .first().attr( "tabindex", "0" ); // Hide header close link for single selects if ( !this.isMultiple ) { this.headerClose.hide(); } // Hide header if it's not a multiselect and there's no placeholder if ( !this.isMultiple && !placeholder.length ) { this.header.hide(); } else { this.headerTitle.text( this.placeholder ); } // Now populated, create listview self.list.listview(); }, refresh: function( forceRebuild ) { var self = this, select = this.element, isMultiple = this.isMultiple, options = this.optionElems = select.find( "option" ), selected = options.filter( ":selected" ), // return an array of all selected index's indicies = selected.map(function() { return options.index( this ); }).get(); if ( !self.options.nativeMenu && ( forceRebuild || select[0].options.length != self.list.find( "li" ).length ) ) { self._buildList(); } self.button.find( ".ui-btn-text" ) .text(function() { if ( !isMultiple ) { return selected.text(); } return selected.length ? selected.map(function() { return $( this ).text(); }).get().join( ", " ) : self.placeholder; }); // multiple count inside button if ( isMultiple ) { self.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length ); } if ( !self.options.nativeMenu ) { self.list.find( "li:not(.ui-li-divider)" ) .removeClass( $.mobile.activeBtnClass ) .attr( "aria-selected", false ) .each(function( i ) { if ( $.inArray( i, indicies ) > -1 ) { var item = $( this ).addClass( $.mobile.activeBtnClass ); // Aria selected attr item.find( "a" ).attr( "aria-selected", true ); // Multiple selects: add the "on" checkbox state to the icon if ( isMultiple ) { item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" ); } } }); } }, open: function() { if ( this.options.disabled || this.options.nativeMenu ) { return; } var self = this, menuHeight = self.list.parent().outerHeight(), menuWidth = self.list.parent().outerWidth(), scrollTop = $( window ).scrollTop(), btnOffset = self.button.offset().top, screenHeight = window.innerHeight, screenWidth = window.innerWidth; //add active class to button self.button.addClass( $.mobile.activeBtnClass ); //remove after delay setTimeout(function() { self.button.removeClass( $.mobile.activeBtnClass ); }, 300); function focusMenuItem() { self.list.find( ".ui-btn-active" ).focus(); } if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) { // prevent the parent page from being removed from the DOM, // otherwise the results of selecting a list item in the dialog // fall into a black hole self.thisPage.unbind( "pagehide.remove" ); //for webos (set lastscroll using button offset) if ( scrollTop == 0 && btnOffset > screenHeight ) { self.thisPage.one( "pagehide", function() { $( this ).jqmData( "lastScroll", btnOffset ); }); } self.menuPage.one( "pageshow", function() { // silentScroll() is called whenever a page is shown to restore // any previous scroll position the page may have had. We need to // wait for the "silentscroll" event before setting focus to avoid // the browser"s "feature" which offsets rendering to make sure // whatever has focus is in view. $( window ).one( "silentscroll", function() { focusMenuItem(); }); self.isOpen = true; }); self.menuType = "page"; self.menuPageContent.append( self.list ); $.mobile.changePage( self.menuPage, { transition: $.mobile.defaultDialogTransition }); } else { self.menuType = "overlay"; self.screen.height( $(document).height() ) .removeClass( "ui-screen-hidden" ); // Try and center the overlay over the button var roomtop = btnOffset - scrollTop, roombot = scrollTop + screenHeight - btnOffset, halfheight = menuHeight / 2, maxwidth = parseFloat( self.list.parent().css( "max-width" ) ), newtop, newleft; if ( roomtop > menuHeight / 2 && roombot > menuHeight / 2 ) { newtop = btnOffset + ( self.button.outerHeight() / 2 ) - halfheight; } else { // 30px tolerance off the edges newtop = roomtop > roombot ? scrollTop + screenHeight - menuHeight - 30 : scrollTop + 30; } // If the menuwidth is smaller than the screen center is if ( menuWidth < maxwidth ) { newleft = ( screenWidth - menuWidth ) / 2; } else { //otherwise insure a >= 30px offset from the left newleft = self.button.offset().left + self.button.outerWidth() / 2 - menuWidth / 2; // 30px tolerance off the edges if ( newleft < 30 ) { newleft = 30; } else if ( ( newleft + menuWidth ) > screenWidth ) { newleft = screenWidth - menuWidth - 30; } } self.listbox.append( self.list ) .removeClass( "ui-selectmenu-hidden" ) .css({ top: newtop, left: newleft }) .addClass( "in" ); focusMenuItem(); // duplicate with value set in page show for dialog sized selects self.isOpen = true; } }, _focusButton : function(){ var self = this; setTimeout(function() { self.button.focus(); }, 40); }, close: function() { if ( this.options.disabled || !this.isOpen || this.options.nativeMenu ) { return; } var self = this; if ( self.menuType == "page" ) { // rebind the page remove that was unbound in the open function // to allow for the parent page removal from actions other than the use // of a dialog sized custom select self.thisPage.bind( "pagehide.remove", function(){ $(this).remove(); }); // doesn't solve the possible issue with calling change page // where the objects don't define data urls which prevents dialog key // stripping - changePage has incoming refactor window.history.back(); } else{ self.screen.addClass( "ui-screen-hidden" ); self.listbox.addClass( "ui-selectmenu-hidden" ).removeAttr( "style" ).removeClass( "in" ); self.list.appendTo( self.listbox ); self._focusButton(); } // allow the dialog to be closed again this.isOpen = false; }, disable: function() { this.element.attr( "disabled", true ); this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); }, enable: function() { this.element.attr( "disabled", false ); this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.selectmenu.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .selectmenu(); }); })( jQuery ); /* * jQuery Mobile Framework : plugin for making button-like links * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ ( function( $, undefined ) { $.fn.buttonMarkup = function( options ) { return this.each( function() { var el = $( this ), o = $.extend( {}, $.fn.buttonMarkup.defaults, el.jqmData(), options ), // Classes Defined innerClass = "ui-btn-inner", buttonClass, iconClass, themedParent, wrap; if ( attachEvents ) { attachEvents(); } // if not, try to find closest theme container if ( !o.theme ) { themedParent = el.closest( "[class*='ui-bar-'],[class*='ui-body-']" ); o.theme = themedParent.length ? /ui-(bar|body)-([a-z])/.exec( themedParent.attr( "class" ) )[2] : "c"; } buttonClass = "ui-btn ui-btn-up-" + o.theme; if ( o.inline ) { buttonClass += " ui-btn-inline"; } if ( o.icon ) { o.icon = "ui-icon-" + o.icon; o.iconpos = o.iconpos || "left"; iconClass = "ui-icon " + o.icon; if ( o.iconshadow ) { iconClass += " ui-icon-shadow"; } } if ( o.iconpos ) { buttonClass += " ui-btn-icon-" + o.iconpos; if ( o.iconpos == "notext" && !el.attr( "title" ) ) { el.attr( "title", el.text() ); } } if ( o.corners ) { buttonClass += " ui-btn-corner-all"; innerClass += " ui-btn-corner-all"; } if ( o.shadow ) { buttonClass += " ui-shadow"; } el.attr( "data-" + $.mobile.ns + "theme", o.theme ) .addClass( buttonClass ); wrap = ( "<D class='" + innerClass + "'><D class='ui-btn-text'></D>" + ( o.icon ? "<span class='" + iconClass + "'></span>" : "" ) + "</D>" ).replace( /D/g, o.wrapperEls ); el.wrapInner( wrap ); }); }; $.fn.buttonMarkup.defaults = { corners: true, shadow: true, iconshadow: true, wrapperEls: "span" }; function closestEnabledButton( element ) { while ( element ) { var $ele = $( element ); if ( $ele.hasClass( "ui-btn" ) && !$ele.hasClass( "ui-disabled" ) ) { break; } element = element.parentNode; } return element; } var attachEvents = function() { $( document ).bind( { "vmousedown": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-down-" + theme ); } }, "vmousecancel vmouseup": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme ); } }, "vmouseover focus": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-hover-" + theme ); } }, "vmouseout blur": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-hover-" + theme ).addClass( "ui-btn-up-" + theme ); } } }); attachEvents = null; }; //links in bars, or those with data-role become buttons //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target ) .not( ".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" ) .buttonMarkup(); }); })( jQuery ); /* * jQuery Mobile Framework: "controlgroup" plugin - corner-rounding for groups of buttons, checks, radios, etc * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.fn.controlgroup = function( options ) { return this.each(function() { var $el = $( this ), o = $.extend({ direction: $el.jqmData( "type" ) || "vertical", shadow: false, excludeInvisible: true }, options ), groupheading = $el.find( ">legend" ), flCorners = o.direction == "horizontal" ? [ "ui-corner-left", "ui-corner-right" ] : [ "ui-corner-top", "ui-corner-bottom" ], type = $el.find( "input:eq(0)" ).attr( "type" ); // Replace legend with more stylable replacement div if ( groupheading.length ) { $el.wrapInner( "<div class='ui-controlgroup-controls'></div>" ); $( "<div role='heading' class='ui-controlgroup-label'>" + groupheading.html() + "</div>" ).insertBefore( $el.children(0) ); groupheading.remove(); } $el.addClass( "ui-corner-all ui-controlgroup ui-controlgroup-" + o.direction ); // TODO: This should be moved out to the closure // otherwise it is redefined each time controlgroup() is called function flipClasses( els ) { els.removeClass( "ui-btn-corner-all ui-shadow" ) .eq( 0 ).addClass( flCorners[ 0 ] ) .end() .filter( ":last" ).addClass( flCorners[ 1 ] ).addClass( "ui-controlgroup-last" ); } flipClasses( $el.find( ".ui-btn" + ( o.excludeInvisible ? ":visible" : "" ) ) ); flipClasses( $el.find( ".ui-btn-inner" ) ); if ( o.shadow ) { $el.addClass( "ui-shadow" ); } }); }; //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='controlgroup')", e.target ).controlgroup({ excludeInvisible: false }); }); })(jQuery);/* * jQuery Mobile Framework : "fieldcontain" plugin - simple class additions to make form row separators * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $( document ).bind( "pagecreate create", function( e ){ //links within content areas $( e.target ) .find( "a" ) .not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" ) .addClass( "ui-link" ); }); })( jQuery );/* * jQuery Mobile Framework : "fixHeaderFooter" plugin - on-demand positioning for headers,footers * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { var slideDownClass = "ui-header-fixed ui-fixed-inline fade", slideUpClass = "ui-footer-fixed ui-fixed-inline fade", slideDownSelector = ".ui-header:jqmData(position='fixed')", slideUpSelector = ".ui-footer:jqmData(position='fixed')"; $.fn.fixHeaderFooter = function( options ) { if ( !$.support.scrollTop ) { return this; } return this.each(function() { var $this = $( this ); if ( $this.jqmData( "fullscreen" ) ) { $this.addClass( "ui-page-fullscreen" ); } // Should be slidedown $this.find( slideDownSelector ).addClass( slideDownClass ); // Should be slideup $this.find( slideUpSelector ).addClass( slideUpClass ); }); }; // single controller for all showing,hiding,toggling $.mobile.fixedToolbars = (function() { if ( !$.support.scrollTop ) { return; } var stickyFooter, delayTimer, currentstate = "inline", autoHideMode = false, showDelay = 100, ignoreTargets = "a,input,textarea,select,button,label,.ui-header-fixed,.ui-footer-fixed", toolbarSelector = ".ui-header-fixed:first, .ui-footer-fixed:not(.ui-footer-duplicate):last", // for storing quick references to duplicate footers supportTouch = $.support.touch, touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", stateBefore = null, scrollTriggered = false, touchToggleEnabled = true; function showEventCallback( event ) { // An event that affects the dimensions of the visual viewport has // been triggered. If the header and/or footer for the current page are in overlay // mode, we want to hide them, and then fire off a timer to show them at a later // point. Events like a resize can be triggered continuously during a scroll, on // some platforms, so the timer is used to delay the actual positioning until the // flood of events have subsided. // // If we are in autoHideMode, we don't do anything because we know the scroll // callbacks for the plugin will fire off a show when the scrolling has stopped. if ( !autoHideMode && currentstate === "overlay" ) { if ( !delayTimer ) { $.mobile.fixedToolbars.hide( true ); } $.mobile.fixedToolbars.startShowTimer(); } } $(function() { var $document = $( document ), $window = $( window ); $document .bind( "vmousedown", function( event ) { if ( touchToggleEnabled ) { stateBefore = currentstate; } }) .bind( "vclick", function( event ) { if ( touchToggleEnabled ) { if ( $(event.target).closest( ignoreTargets ).length ) { return; } if ( !scrollTriggered ) { $.mobile.fixedToolbars.toggle( stateBefore ); stateBefore = null; } } }) .bind( "silentscroll", showEventCallback ); // The below checks first for a $(document).scrollTop() value, and if zero, binds scroll events to $(window) instead. // If the scrollTop value is actually zero, both will return zero anyway. // // Works with $(document), not $(window) : Opera Mobile (WinMO phone; kinda broken anyway) // Works with $(window), not $(document) : IE 7/8 // Works with either $(window) or $(document) : Chrome, FF 3.6/4, Android 1.6/2.1, iOS // Needs work either way : BB5, Opera Mobile (iOS) ( ( $document.scrollTop() === 0 ) ? $window : $document ) .bind( "scrollstart", function( event ) { scrollTriggered = true; if ( stateBefore === null ) { stateBefore = currentstate; } // We only enter autoHideMode if the headers/footers are in // an overlay state or the show timer was started. If the // show timer is set, clear it so the headers/footers don't // show up until after we're done scrolling. var isOverlayState = stateBefore == "overlay"; autoHideMode = isOverlayState || !!delayTimer; if ( autoHideMode ) { $.mobile.fixedToolbars.clearShowTimer(); if ( isOverlayState ) { $.mobile.fixedToolbars.hide( true ); } } }) .bind( "scrollstop", function( event ) { if ( $( event.target ).closest( ignoreTargets ).length ) { return; } scrollTriggered = false; if ( autoHideMode ) { $.mobile.fixedToolbars.startShowTimer(); autoHideMode = false; } stateBefore = null; }); $window.bind( "resize", showEventCallback ); }); // 1. Before page is shown, check for duplicate footer // 2. After page is shown, append footer to new page $( ".ui-page" ) .live( "pagebeforeshow", function( event, ui ) { var page = $( event.target ), footer = page.find( ":jqmData(role='footer')" ), id = footer.data( "id" ), prevPage = ui.prevPage, prevFooter = prevPage && prevPage.find( ":jqmData(role='footer')" ), prevFooterMatches = prevFooter.length && prevFooter.jqmData( "id" ) === id; if ( id && prevFooterMatches ) { stickyFooter = footer; setTop( stickyFooter.removeClass( "fade in out" ).appendTo( $.mobile.pageContainer ) ); } }) .live( "pageshow", function( event, ui ) { var $this = $( this ); if ( stickyFooter && stickyFooter.length ) { setTimeout(function() { setTop( stickyFooter.appendTo( $this ).addClass( "fade" ) ); stickyFooter = null; }, 500); } $.mobile.fixedToolbars.show( true, this ); }); // When a collapsiable is hidden or shown we need to trigger the fixed toolbar to reposition itself (#1635) $( ".ui-collapsible-contain" ).live( "collapse expand", showEventCallback ); // element.getBoundingClientRect() is broken in iOS 3.2.1 on the iPad. The // coordinates inside of the rect it returns don't have the page scroll position // factored out of it like the other platforms do. To get around this, // we'll just calculate the top offset the old fashioned way until core has // a chance to figure out how to handle this situation. // // TODO: We'll need to get rid of getOffsetTop() once a fix gets folded into core. function getOffsetTop( ele ) { var top = 0, op, body; if ( ele ) { body = document.body; op = ele.offsetParent; top = ele.offsetTop; while ( ele && ele != body ) { top += ele.scrollTop || 0; if ( ele == op ) { top += op.offsetTop; op = ele.offsetParent; } ele = ele.parentNode; } } return top; } function setTop( el ) { var fromTop = $(window).scrollTop(), thisTop = getOffsetTop( el[ 0 ] ), // el.offset().top returns the wrong value on iPad iOS 3.2.1, call our workaround instead. thisCSStop = el.css( "top" ) == "auto" ? 0 : parseFloat(el.css( "top" )), screenHeight = window.innerHeight, thisHeight = el.outerHeight(), useRelative = el.parents( ".ui-page:not(.ui-page-fullscreen)" ).length, relval; if ( el.is( ".ui-header-fixed" ) ) { relval = fromTop - thisTop + thisCSStop; if ( relval < thisTop ) { relval = 0; } return el.css( "top", useRelative ? relval : fromTop ); } else { // relval = -1 * (thisTop - (fromTop + screenHeight) + thisCSStop + thisHeight); // if ( relval > thisTop ) { relval = 0; } relval = fromTop + screenHeight - thisHeight - (thisTop - thisCSStop ); return el.css( "top", useRelative ? relval : fromTop + screenHeight - thisHeight ); } } // Exposed methods return { show: function( immediately, page ) { $.mobile.fixedToolbars.clearShowTimer(); currentstate = "overlay"; var $ap = page ? $( page ) : ( $.mobile.activePage ? $.mobile.activePage : $( ".ui-page-active" ) ); return $ap.children( toolbarSelector ).each(function() { var el = $( this ), fromTop = $( window ).scrollTop(), // el.offset().top returns the wrong value on iPad iOS 3.2.1, call our workaround instead. thisTop = getOffsetTop( el[ 0 ] ), screenHeight = window.innerHeight, thisHeight = el.outerHeight(), alreadyVisible = ( el.is( ".ui-header-fixed" ) && fromTop <= thisTop + thisHeight ) || ( el.is( ".ui-footer-fixed" ) && thisTop <= fromTop + screenHeight ); // Add state class el.addClass( "ui-fixed-overlay" ).removeClass( "ui-fixed-inline" ); if ( !alreadyVisible && !immediately ) { el.animationComplete(function() { el.removeClass( "in" ); }).addClass( "in" ); } setTop(el); }); }, hide: function( immediately ) { currentstate = "inline"; var $ap = $.mobile.activePage ? $.mobile.activePage : $( ".ui-page-active" ); return $ap.children( toolbarSelector ).each(function() { var el = $(this), thisCSStop = el.css( "top" ), classes; thisCSStop = thisCSStop == "auto" ? 0 : parseFloat(thisCSStop); // Add state class el.addClass( "ui-fixed-inline" ).removeClass( "ui-fixed-overlay" ); if ( thisCSStop < 0 || ( el.is( ".ui-header-fixed" ) && thisCSStop !== 0 ) ) { if ( immediately ) { el.css( "top", 0); } else { if ( el.css( "top" ) !== "auto" && parseFloat( el.css( "top" ) ) !== 0 ) { classes = "out reverse"; el.animationComplete(function() { el.removeClass( classes ).css( "top", 0 ); }).addClass( classes ); } } } }); }, startShowTimer: function() { $.mobile.fixedToolbars.clearShowTimer(); var args = [].slice.call( arguments ); delayTimer = setTimeout(function() { delayTimer = undefined; $.mobile.fixedToolbars.show.apply( null, args ); }, showDelay); }, clearShowTimer: function() { if ( delayTimer ) { clearTimeout( delayTimer ); } delayTimer = undefined; }, toggle: function( from ) { if ( from ) { currentstate = from; } return ( currentstate === "overlay" ) ? $.mobile.fixedToolbars.hide() : $.mobile.fixedToolbars.show(); }, setTouchToggleEnabled: function( enabled ) { touchToggleEnabled = enabled; } }; })(); // TODO - Deprecated namepace on $. Remove in a later release $.fixedToolbars = $.mobile.fixedToolbars; //auto self-init widgets $( document ).bind( "pagecreate create", function( event ) { if ( $( ":jqmData(position='fixed')", event.target ).length ) { $( event.target ).each(function() { if ( !$.support.scrollTop ) { return this; } var $this = $( this ); if ( $this.jqmData( "fullscreen" ) ) { $this.addClass( "ui-page-fullscreen" ); } // Should be slidedown $this.find( slideDownSelector ).addClass( slideDownClass ); // Should be slideup $this.find( slideUpSelector ).addClass( slideUpClass ); }) } }); })( jQuery ); /* * jQuery Mobile Framework : resolution and CSS media query related helpers and behavior * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { var $window = $( window ), $html = $( "html" ), //media-query-like width breakpoints, which are translated to classes on the html element resolutionBreakpoints = [ 320, 480, 768, 1024 ]; /* private function for adding/removing breakpoint classes to HTML element for faux media-query support It does not require media query support, instead using JS to detect screen width > cross-browser support This function is called on orientationchange, resize, and mobileinit, and is bound via the 'htmlclass' event namespace */ function detectResolutionBreakpoints() { var currWidth = $window.width(), minPrefix = "min-width-", maxPrefix = "max-width-", minBreakpoints = [], maxBreakpoints = [], unit = "px", breakpointClasses; $html.removeClass( minPrefix + resolutionBreakpoints.join(unit + " " + minPrefix) + unit + " " + maxPrefix + resolutionBreakpoints.join( unit + " " + maxPrefix) + unit ); $.each( resolutionBreakpoints, function( i, breakPoint ) { if( currWidth >= breakPoint ) { minBreakpoints.push( minPrefix + breakPoint + unit ); } if( currWidth <= breakPoint ) { maxBreakpoints.push( maxPrefix + breakPoint + unit ); } }); if ( minBreakpoints.length ) { breakpointClasses = minBreakpoints.join(" "); } if ( maxBreakpoints.length ) { breakpointClasses += " " + maxBreakpoints.join(" "); } $html.addClass( breakpointClasses ); }; /* $.mobile.addResolutionBreakpoints method: pass either a number or an array of numbers and they'll be added to the min/max breakpoint classes Examples: $.mobile.addResolutionBreakpoints( 500 ); $.mobile.addResolutionBreakpoints( [500, 1200] ); */ $.mobile.addResolutionBreakpoints = function( newbps ) { if( $.type( newbps ) === "array" ){ resolutionBreakpoints = resolutionBreakpoints.concat( newbps ); } else { resolutionBreakpoints.push( newbps ); } resolutionBreakpoints.sort(function( a, b ) { return a - b; }); detectResolutionBreakpoints(); }; /* on mobileinit, add classes to HTML element and set handlers to update those on orientationchange and resize */ $( document ).bind( "mobileinit.htmlclass", function() { // bind to orientationchange and resize // to add classes to HTML element for min/max breakpoints and orientation var ev = $.support.orientation; $window.bind( "orientationchange.htmlclass throttledResize.htmlclass", function( event ) { // add orientation class to HTML element on flip/resize. if ( event.orientation ) { $html.removeClass( "portrait landscape" ).addClass( event.orientation ); } // add classes to HTML element for min/max breakpoints detectResolutionBreakpoints(); }); }); /* Manually trigger an orientationchange event when the dom ready event fires. This will ensure that any viewport meta tag that may have been injected has taken effect already, allowing us to properly calculate the width of the document. */ $(function() { //trigger event manually $window.trigger( "orientationchange.htmlclass" ); }); })(jQuery);/*! * jQuery Mobile v@VERSION * http://jquerymobile.com/ * * Copyright 2010, jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, window, undefined ) { var $html = $( "html" ), $head = $( "head" ), $window = $( window ); //trigger mobileinit event - useful hook for configuring $.mobile settings before they're used $( window.document ).trigger( "mobileinit" ); //support conditions //if device support condition(s) aren't met, leave things as they are -> a basic, usable experience, //otherwise, proceed with the enhancements if ( !$.mobile.gradeA() ) { return; } // override ajaxEnabled on platforms that have known conflicts with hash history updates // or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini) if( $.mobile.ajaxBlacklist ){ $.mobile.ajaxEnabled = false; } //add mobile, initial load "rendering" classes to docEl $html.addClass( "ui-mobile ui-mobile-rendering" ); //loading div which appears during Ajax requests //will not appear if $.mobile.loadingMessage is false var $loader = $( "<div class='ui-loader ui-body-a ui-corner-all'><span class='ui-icon ui-icon-loading spin'></span><h1></h1></div>" ); $.extend($.mobile, { // turn on/off page loading message. showPageLoadingMsg: function() { if( $.mobile.loadingMessage ){ var activeBtn = $( "." + $.mobile.activeBtnClass ).first(); $loader .find( "h1" ) .text( $.mobile.loadingMessage ) .end() .appendTo( $.mobile.pageContainer ) //position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top .css( { top: $.support.scrollTop && $(window).scrollTop() + $(window).height() / 2 || activeBtn.length && activeBtn.offset().top || 100 } ); } $html.addClass( "ui-loading" ); }, hidePageLoadingMsg: function() { $html.removeClass( "ui-loading" ); }, // XXX: deprecate for 1.0 pageLoading: function ( done ) { if ( done ) { $.mobile.hidePageLoadingMsg(); } else { $.mobile.showPageLoadingMsg(); } }, // find and enhance the pages in the dom and transition to the first page. initializePage: function(){ //find present pages var $pages = $( ":jqmData(role='page')" ); //if no pages are found, create one with body's inner html if( !$pages.length ){ $pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 ); } //add dialogs, set data-url attrs $pages.add( ":jqmData(role='dialog')" ).each(function(){ var $this = $(this); // unless the data url is already set set it to the id if( !$this.jqmData('url') ){ $this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) ); } }); //define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback) $.mobile.firstPage = $pages.first(); //define page container $.mobile.pageContainer = $pages.first().parent().addClass( "ui-mobile-viewport" ); //cue page loading message $.mobile.showPageLoadingMsg(); // if hashchange listening is disabled or there's no hash deeplink, change to the first page in the DOM if( !$.mobile.hashListeningEnabled || !$.mobile.path.stripHash( location.hash ) ){ $.mobile.changePage( $.mobile.firstPage, { transition: "none", reverse: true, changeHash: false, fromHashChange: true } ); } // otherwise, trigger a hashchange to load a deeplink else { $window.trigger( "hashchange", [ true ] ); } } }); //initialize events now, after mobileinit has occurred $.mobile._registerInternalEvents(); //check which scrollTop value should be used by scrolling to 1 immediately at domready //then check what the scroll top is. Android will report 0... others 1 //note that this initial scroll won't hide the address bar. It's just for the check. $(function(){ window.scrollTo( 0, 1 ); //if defaultHomeScroll hasn't been set yet, see if scrollTop is 1 //it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar) //so if it's 1, use 0 from now on $.mobile.defaultHomeScroll = ( !$.support.scrollTop || $(window).scrollTop() === 1 ) ? 0 : 1; //dom-ready inits if( $.mobile.autoInitializePage ){ $( $.mobile.initializePage ); } //window load event //hide iOS browser chrome on load $window.load( $.mobile.silentScroll ); }); })( jQuery, this );
JavaScript
//quick view source in new window links $.fn.addSourceLink = function(style){ return $(this).each(function(){ var link = $('<a href="#" data-'+ $.mobile.ns +'inline="true">View Source</a>'), src = src = $('<div></div>').append( $(this).clone() ).html(), page = $( "<div data-"+ $.mobile.ns +"role='dialog' data-"+ $.mobile.ns +"theme='a'>" + "<div data-"+ $.mobile.ns +"role='header' data-"+ $.mobile.ns +"theme='b'>" + "<a href='#' class='ui-btn-left' data-"+ $.mobile.ns +"icon='delete' data-"+ $.mobile.ns +"iconpos='notext'>Close</a>"+ "<div class='ui-title'>jQuery Mobile Source Excerpt</div>"+ "</div>"+ "<div data-"+ $.mobile.ns +"role='content'></div>"+ "</div>" ) .appendTo( "body" ) .page(); $('<a href="#">View Source</a>') .buttonMarkup({ icon: 'arrow-u', iconpos: 'notext' }) .click(function(){ var codeblock = $('<pre><code></code></pre>'); src = src.replace(/&/gmi, '&amp;').replace(/"/gmi, '&quot;').replace(/>/gmi, '&gt;').replace(/</gmi, '&lt;').replace('data-'+ $.mobile.ns +'source="true"',''); codeblock.find('code').append(src); var activePage = $(this).parents('.ui-page-active'); page.find('.ui-content').append(codeblock); $.changePage(page, 'slideup',false); page.find('.ui-btn-left').click(function(){ $.changePage(activepage, 'slideup',true); return false; }); }) .insertAfter(this); }); }; //set up view source links $('div').live('pagebeforecreate',function(){ $(this).find('[data-'+ $.mobile.ns +'source="true"]').addSourceLink(); });
JavaScript
//set up the theme switcher on the homepage $('div').live('pagecreate',function(event){ if( !$(this).is('.ui-dialog')){ var appendEl = $(this).find('.ui-footer:last'); if( !appendEl.length ){ appendEl = $(this).find('.ui-content'); } if( appendEl.is("[data-position]") ){ return; } $('<a href="#themeswitcher" data-'+ $.mobile.ns +'rel="dialog" data-'+ $.mobile.ns +'transition="pop">Switch theme</a>') .buttonMarkup({ 'icon':'gear', 'inline': true, 'shadow': false, 'theme': 'd' }) .appendTo( appendEl ) .wrap('<div class="jqm-themeswitcher">') .bind( "vclick", function(){ $.themeswitcher(); }); } }); //collapse page navs after use $(function(){ $('body').delegate('.content-secondary .ui-collapsible-content', 'click', function(){ $(this).trigger("collapse") }); }); function setDefaultTransition(){ var winwidth = $( window ).width(), trans ="slide"; if( winwidth >= 1000 ){ trans = "none"; } else if( winwidth >= 650 ){ trans = "fade"; } $.mobile.defaultPageTransition = trans; } $(function(){ setDefaultTransition(); $( window ).bind( "throttledresize", setDefaultTransition ); });
JavaScript
/* * mobile button unit tests */ (function($){ $.mobile.page.prototype.options.keepNative = "button.should-be-native"; test( "button elements in the keepNative set shouldn't be enhanced", function() { same( $("button.should-be-native").siblings("div.ui-slider").length, 0 ); }); test( "button elements should be enhanced", function() { ok( $("#enhanced").hasClass( "ui-btn-hidden" ) ); }); test( "button markup text value should be changed on refresh", function() { var textValueButton = $("#text"), valueButton = $("#value"); // the value shouldn't change unless it's been altered textValueButton.button( 'refresh' ); same( textValueButton.siblings().text(), "foo" ); // use the text where it's provided same( textValueButton.siblings().text(), "foo" ); textValueButton.text( "bar" ).button( 'refresh' ); same( textValueButton.siblings().text(), "bar" ); // use the val if it's provided where the text isn't same( valueButton.siblings().text(), "foo" ); valueButton.val( "bar" ).button( 'refresh' ); same( valueButton.siblings().text(), "bar" ); // prefer the text to the value textValueButton.text( "bar" ).val( "baz" ).button( 'refresh' ); same( textValueButton.siblings().text(), "bar" ); }); // Issue 2877 test( "verify the button placeholder is added many times", function() { var $form = $( "#hidden-element-addition-form" ), count = 3; expect( count * 2 ); for( var x = 0; x < count; x++ ) { $( "#hidden-element-addition" ).trigger( "vclick" ); same( $form.find( "input[type='hidden']" ).length, 1, "hidden form input should be added" ); $form.trigger( "submit" ); same( $form.find( "[type='hidden']" ).length, 0, "hidden form input is removed" ); } }); })( jQuery );
JavaScript
/* * mobile page unit tests */ (function($){ var libName = 'jquery.mobile.page.js'; module(libName); test( "nested header anchors aren't altered", function(){ ok(!$('.ui-header > div > a').hasClass('ui-btn')); }); test( "nested footer anchors aren't altered", function(){ ok(!$('.ui-footer > div > a').hasClass('ui-btn')); }); test( "nested bar anchors aren't styled", function(){ ok(!$('.ui-bar > div > a').hasClass('ui-btn')); }); test( "unnested footer anchors are styled", function(){ ok($('.ui-footer > a').hasClass('ui-btn')); }); test( "unnested footer anchors are styled", function(){ ok($('.ui-footer > a').hasClass('ui-btn')); }); test( "unnested bar anchors are styled", function(){ ok($('.ui-bar > a').hasClass('ui-btn')); }); test( "no auto-generated back button exists on first page", function(){ ok( !$(".ui-header > :jqmData(rel='back')").length ); }); })(jQuery);
JavaScript
/* * mobile textinput unit tests */ (function($){ module( "jquery.mobile.forms.textinput.js" ); test( "inputs without type specified are enhanced", function(){ ok( $( "#typeless-input" ).hasClass( "ui-input-text" ) ); }); $.mobile.page.prototype.options.keepNative = "textarea.should-be-native"; // not testing the positive case here since's it's obviously tested elsewhere test( "textarea in the keepNative set shouldn't be enhanced", function() { ok( !$("textarea.should-be-native").is("ui-input-text") ); }); asyncTest( "textarea should autogrow on document ready", function() { var test = $( "#init-autogrow" ); setTimeout(function() { ok( $( "#reference-autogrow" )[0].clientHeight < test[0].clientHeight, "the height is greater than the reference text area with no content" ); ok( test[0].clientHeight > 100, "autogrow text area's height is greater than any style padding"); start(); }, 400); }); asyncTest( "textarea should autogrow when text is added via the keyboard", function() { var test = $( "#keyup-autogrow" ), originalHeight = test[0].clientHeight; test.keyup(function() { setTimeout(function() { ok( test[0].clientHeight > originalHeight, "the height is greater than original with no content" ); ok( test[0].clientHeight > 100, "autogrow text area's height is greater any style/padding"); start(); }, 400); }); test.val("foo\n\n\n\n\n\n\n\n\n\n\n\n\n\n").trigger("keyup"); }); asyncTest( "text area should auto grow when the parent page is loaded via ajax", function() { $.testHelper.pageSequence([ function() { $("#external").click(); }, function() { setTimeout(function() { ok($.mobile.activePage.find( "textarea" )[0].clientHeight > 100, "text area's height has grown"); window.history.back(); }, 1000); }, function() { start(); } ]); }); })(jQuery);
JavaScript
(function($) { asyncTest( "nested pages hash key is always in the hash on default page with no id (replaceState) ", function(){ $.testHelper.pageSequence([ function(){ // Click on the link of the third li element $('.ui-page-active li:eq(2) a:eq(0)').click(); }, function(){ ok( location.hash.search($.mobile.subPageUrlKey) >= 0 ); start(); } ]); }); })(jQuery);
JavaScript
/* * mobile listview unit tests */ // TODO split out into seperate test files (function($){ var home = $.mobile.path.parseUrl( location.href ).pathname; $.mobile.defaultTransition = "none"; module( "Basic Linked list", { setup: function(){ $.testHelper.openPage( "#basic-linked-test" ); } }); asyncTest( "The page should enhanced correctly", function(){ setTimeout(function() { ok($('#basic-linked-test .ui-li').length, ".ui-li classes added to li elements"); start(); }, 800); }); asyncTest( "Slides to the listview page when the li a is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#basic-linked-test"); }, function(){ $('#basic-linked-test li a').first().click(); }, function(){ ok($('#basic-link-results').hasClass('ui-page-active')); start(); } ]); }); asyncTest( "Slides back to main page when back button is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#basic-link-results"); }, function(){ window.history.back(); }, function(){ ok($('#basic-linked-test').hasClass('ui-page-active')); start(); } ]); }); asyncTest( "Presence of ui-li-has- classes", function(){ $.testHelper.pageSequence( [ function() { $.testHelper.openPage( "#ui-li-has-test" ); }, function() { var page = $( ".ui-page-active" ), items = page.find( "li" ); ok( items.eq( 0 ).hasClass( "ui-li-has-count"), "First LI should have ui-li-has-count class" ); ok( items.eq( 0 ).hasClass( "ui-li-has-arrow"), "First LI should have ui-li-has-arrow class" ); ok( !items.eq( 1 ).hasClass( "ui-li-has-count"), "Second LI should NOT have ui-li-has-count class" ); ok( items.eq( 1 ).hasClass( "ui-li-has-arrow"), "Second LI should have ui-li-has-arrow class" ); ok( !items.eq( 2 ).hasClass( "ui-li-has-count"), "Third LI should NOT have ui-li-has-count class" ); ok( !items.eq( 2 ).hasClass( "ui-li-has-arrow"), "Third LI should NOT have ui-li-has-arrow class" ); ok( items.eq( 3 ).hasClass( "ui-li-has-count"), "Fourth LI should have ui-li-has-count class" ); ok( !items.eq( 3 ).hasClass( "ui-li-has-arrow"), "Fourth LI should NOT have ui-li-has-arrow class" ); ok( !items.eq( 4 ).hasClass( "ui-li-has-count"), "Fifth LI should NOT have ui-li-has-count class" ); ok( !items.eq( 4 ).hasClass( "ui-li-has-arrow"), "Fifth LI should NOT have ui-li-has-arrow class" ); start(); } ]); }); module('Nested List Test'); asyncTest( "Changes page to nested list test and enhances", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#nested-list-test"); }, function(){ ok($('#nested-list-test').hasClass('ui-page-active'), "makes nested list test page active"); ok($(':jqmData(url="nested-list-test&ui-page=0-0")').length == 1, "Adds first UL to the page"); ok($(':jqmData(url="nested-list-test&ui-page=0-1")').length == 1, "Adds second nested UL to the page"); start(); } ]); }); asyncTest( "change to nested page when the li a is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#nested-list-test"); }, function(){ $('.ui-page-active li:eq(1) a:eq(0)').click(); }, function(){ var $new_page = $(':jqmData(url="nested-list-test&ui-page=0-0")'); ok($new_page.hasClass('ui-page-active'), 'Makes the nested page the active page.'); ok($('.ui-listview', $new_page).find(":contains('Rhumba of rattlesnakes')").length == 1, "The current page should have the proper text in the list."); ok($('.ui-listview', $new_page).find(":contains('Shoal of Bass')").length == 1, "The current page should have the proper text in the list."); start(); } ]); }); asyncTest( "should go back to top level when the back button is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#nested-list-test&ui-page=0-0"); }, function(){ window.history.back(); }, function(){ ok($('#nested-list-test').hasClass('ui-page-active'), 'Transitions back to the parent nested page'); start(); } ]); }); test( "nested list title should use first text node, regardless of line breaks", function(){ ok($('#nested-list-test .linebreaknode').text() === "More animals", 'Text should be "More animals"'); }); asyncTest( "Multiple nested lists on a page with same labels", function() { $.testHelper.pageSequence([ function(){ // https://github.com/jquery/jquery-mobile/issues/1617 $.testHelper.openPage("#nested-lists-test"); }, function(){ // Click on the link of the third li element $('.ui-page-active li:eq(2) a:eq(0)').click(); }, function(){ equal($('.ui-page-active .ui-content .ui-listview li').text(), "Item A-3-0Item A-3-1Item A-3-2", 'Text should be "Item A-3-0Item A-3-1Item A-3-2"'); start(); } ]); }); module('Ordered Lists'); asyncTest( "changes to the numbered list page and enhances it", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#numbered-list-test"); }, function(){ var $new_page = $('#numbered-list-test'); ok($new_page.hasClass('ui-page-active'), "Makes the new page active when the hash is changed."); ok($('.ui-link-inherit', $new_page).first().text() == "Number 1", "The text of the first LI should be Number 1"); start(); } ]); }); asyncTest( "changes to number 1 page when the li a is clicked", function() { $.testHelper.pageSequence([ function(){ $('#numbered-list-test li a').first().click(); }, function(){ ok($('#numbered-list-results').hasClass('ui-page-active'), "The new numbered page was transitioned correctly."); start(); } ]); }); asyncTest( "takes us back to the numbered list when the back button is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage('#numbered-list-test'); }, function(){ $.testHelper.openPage('#numbered-list-results'); }, function(){ window.history.back(); }, function(){ ok($('#numbered-list-test').hasClass('ui-page-active')); start(); } ]); }); module('Read only list'); asyncTest( "changes to the read only page when hash is changed", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#read-only-list-test"); }, function(){ var $new_page = $('#read-only-list-test'); ok($new_page.hasClass('ui-page-active'), "makes the read only page the active page"); ok($('li', $new_page).first().text() === "Read", "The first LI has the proper text."); start(); } ]); }); module('Split view list'); asyncTest( "changes the page to the split view list and enhances it correctly.", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#split-list-test"); }, function(){ var $new_page = $('#split-list-test'); ok($('.ui-li-link-alt', $new_page).length == 3); ok($('.ui-link-inherit', $new_page).length == 3); start(); } ]); }); asyncTest( "change the page to the split view page 1 when the first link is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#split-list-test"); }, function(){ $('.ui-page-active .ui-li a:eq(0)').click(); }, function(){ ok($('#split-list-link1').hasClass('ui-page-active')); start(); } ]); }); asyncTest( "Slide back to the parent list view when the back button is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#split-list-test"); }, function(){ $('.ui-page-active .ui-listview a:eq(0)').click(); }, function(){ history.back(); }, function(){ ok($('#split-list-test').hasClass('ui-page-active')); start(); } ]); }); asyncTest( "Clicking on the icon (the second link) should take the user to other a href of this LI", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#split-list-test"); }, function(){ $('.ui-page-active .ui-li-link-alt:eq(0)').click(); }, function(){ ok($('#split-list-link2').hasClass('ui-page-active')); start(); } ]); }); module( "List Dividers" ); asyncTest( "Makes the list divider page the active page and enhances it correctly.", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#list-divider-test"); }, function(){ var $new_page = $('#list-divider-test'); ok($new_page.find('.ui-li-divider').length == 2); ok($new_page.hasClass('ui-page-active')); start(); } ]); }); module( "Search Filter"); var searchFilterId = "#search-filter-test"; asyncTest( "Filter downs results when the user enters information", function() { var $searchPage = $(searchFilterId); $.testHelper.pageSequence([ function() { $.testHelper.openPage(searchFilterId); }, function() { $searchPage.find('input').val('at'); $searchPage.find('input').trigger('change'); same($searchPage.find('li.ui-screen-hidden').length, 2); start(); } ]); }); asyncTest( "Redisplay results when user removes values", function() { var $searchPage = $(searchFilterId); $.testHelper.pageSequence([ function() { $.testHelper.openPage(searchFilterId); }, function() { $searchPage.find('input').val('a'); $searchPage.find('input').trigger('change'); same($searchPage.find("li[style^='display: none;']").length, 0); start(); } ]); }); asyncTest( "Filter works fine with \\W- or regexp-special-characters", function() { var $searchPage = $(searchFilterId); $.testHelper.pageSequence([ function() { $.testHelper.openPage(searchFilterId); }, function() { $searchPage.find('input').val('*'); $searchPage.find('input').trigger('change'); same($searchPage.find('li.ui-screen-hidden').length, 4); start(); } ]); }); test( "Refresh applies thumb styling", function(){ var ul = $('.ui-page-active ul'); ul.append("<li id='fiz'><img/></li>"); ok(!ul.find("#fiz img").hasClass("ui-li-thumb")); ul.listview('refresh'); ok(ul.find("#fiz img").hasClass("ui-li-thumb")); }); asyncTest( "Filter downs results and dividers when the user enters information", function() { var $searchPage = $("#search-filter-with-dividers-test"); $.testHelper.pageSequence([ function() { $.testHelper.openPage("#search-filter-with-dividers-test"); }, // wait for the page to become active/enhanced function(){ $searchPage.find('input').val('at'); $searchPage.find('input').trigger('change'); setTimeout(function() { //there should be four hidden list entries same($searchPage.find('li.ui-screen-hidden').length, 4); //there should be two list entries that are list dividers and hidden same($searchPage.find('li.ui-screen-hidden:jqmData(role=list-divider)').length, 2); //there should be two list entries that are not list dividers and hidden same($searchPage.find('li.ui-screen-hidden:not(:jqmData(role=list-divider))').length, 2); start(); }, 1000); } ]); }); asyncTest( "Redisplay results when user removes values", function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#search-filter-with-dividers-test"); }, function() { $('.ui-page-active input').val('a'); $('.ui-page-active input').trigger('change'); setTimeout(function() { same($('.ui-page-active input').val(), 'a'); same($('.ui-page-active li[style^="display: none;"]').length, 0); start(); }, 1000); } ]); }); asyncTest( "Dividers are hidden when preceding hidden rows and shown when preceding shown rows", function () { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#search-filter-with-dividers-test"); }, function() { var $page = $('.ui-page-active'); $page.find('input').val('at'); $page.find('input').trigger('change'); setTimeout(function() { same($page.find('li:jqmData(role=list-divider):hidden').length, 2); same($page.find('li:jqmData(role=list-divider):hidden + li:not(:jqmData(role=list-divider)):hidden').length, 2); same($page.find('li:jqmData(role=list-divider):not(:hidden) + li:not(:jqmData(role=list-divider)):not([:hidden)').length, 2); start(); }, 1000); } ]); }); asyncTest( "Inset List View should refresh corner classes after filtering", 4 * 2, function () { var checkClasses = function() { var $page = $( ".ui-page-active" ), $li = $page.find( "li:visible" ); ok($li.first().hasClass( "ui-corner-top" ), $li.length+" li elements: First visible element should have class ui-corner-top"); ok($li.last().hasClass( "ui-corner-bottom" ), $li.length+" li elements: Last visible element should have class ui-corner-bottom"); }; $.testHelper.pageSequence([ function() { $.testHelper.openPage("#search-filter-inset-test"); }, function() { var $page = $('.ui-page-active'); $.testHelper.sequence([ function() { checkClasses(); $page.find('input').val('man'); $page.find('input').trigger('change'); }, function() { checkClasses(); $page.find('input').val('at'); $page.find('input').trigger('change'); }, function() { checkClasses(); $page.find('input').val('catwoman'); $page.find('input').trigger('change'); }, function() { checkClasses(); start(); } ], 50); } ]); }); module( "Programmatically generated list items", { setup: function(){ var item, data = [ { id: 1, label: "Item 1" }, { id: 2, label: "Item 2" }, { id: 3, label: "Item 3" }, { id: 4, label: "Item 4" } ]; $( "#programmatically-generated-list-items" ).html(""); for ( var i = 0, len = data.length; i < len; i++ ) { item = $( '<li id="myItem' + data[i].id + '">' ); label = $( "<strong>" + data[i].label + "</strong>").appendTo( item ); $( "#programmatically-generated-list-items" ).append( item ); } } }); asyncTest( "Corner styling on programmatically created list items", function() { // https://github.com/jquery/jquery-mobile/issues/1470 $.testHelper.pageSequence([ function() { $.testHelper.openPage( "#programmatically-generated-list" ); }, function() { ok(!$( "#programmatically-generated-list-items li:first-child" ).hasClass( "ui-corner-bottom" ), "First list item should not have class ui-corner-bottom" ); start(); } ]); }); module("Programmatic list items manipulation"); asyncTest("Removing list items", 4, function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#removing-items-from-list-test"); }, function() { var ul = $('#removing-items-from-list-test ul'); ul.find("li").first().remove(); equal(ul.find("li").length, 3, "There should be only 3 list items left"); ul.listview('refresh'); ok(ul.find("li").first().hasClass("ui-corner-top"), "First list item should have class ui-corner-top"); ul.find("li").last().remove(); equal(ul.find("li").length, 2, "There should be only 2 list items left"); ul.listview('refresh'); ok(ul.find("li").last().hasClass("ui-corner-bottom"), "Last list item should have class ui-corner-bottom"); start(); } ]); }); module("Rounded corners"); asyncTest("Top and bottom corners rounded in inset list", 14, function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#corner-rounded-test"); }, function() { var ul = $('#corner-rounded-test ul'); for( var t = 0; t<3; t++){ ul.append("<li>Item " + t + "</li>"); ul.listview('refresh'); equals(ul.find(".ui-corner-top").length, 1, "There should be only one element with class ui-corner-top"); equals(ul.find("li:visible").first()[0], ul.find(".ui-corner-top")[0], "First list item should have class ui-corner-top in list with " + ul.find("li").length + " item(s)"); equals(ul.find(".ui-corner-bottom").length, 1, "There should be only one element with class ui-corner-bottom"); equals(ul.find("li:visible").last()[0], ul.find(".ui-corner-bottom")[0], "Last list item should have class ui-corner-bottom in list with " + ul.find("li").length + " item(s)"); } ul.find( "li" ).first().hide(); ul.listview( "refresh" ); equals(ul.find("li:visible").first()[0], ul.find(".ui-corner-top")[0], "First visible list item should have class ui-corner-top"); ul.find( "li" ).last().hide(); ul.listview( "refresh" ); equals(ul.find("li:visible").last()[0], ul.find(".ui-corner-bottom")[0], "Last visible list item should have class ui-corner-bottom"); start(); } ]); }); test( "Listview will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-listview").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-listview").length, "enhancements applied" ); }); module( "Cached Linked List" ); var findNestedPages = function(selector){ return $( selector + " #topmost" ).listview( 'childPages' ); }; asyncTest( "nested pages are removed from the dom by default", function(){ $.testHelper.pageSequence([ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function(){ $.testHelper.openPage( "#cache-tests/uncached-nested.html" ); }, function(){ ok( findNestedPages( "#uncached-nested-list" ).length > 0, "verify that there are nested pages" ); $.testHelper.openPage( "#" + home ); }, function() { $.testHelper.openPage( "#cache-tests/clear.html" ); }, function(){ same( findNestedPages( "#uncached-nested-list" ).length, 0 ); start(); } ]); }); asyncTest( "nested pages preserved when parent page is cached", function(){ $.testHelper.pageSequence([ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function(){ $.testHelper.openPage( "#cache-tests/cached-nested.html" ); }, function(){ ok( findNestedPages( "#cached-nested-list" ).length > 0, "verify that there are nested pages" ); $.testHelper.openPage( "#" + home ); }, function() { $.testHelper.openPage( "#cache-tests/clear.html" ); }, function(){ ok( findNestedPages( "#cached-nested-list" ).length > 0, "nested pages remain" ); start(); } ]); }); asyncTest( "parent page is not removed when visiting a sub page", function(){ $.testHelper.pageSequence([ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function(){ $.testHelper.openPage( "#cache-tests/cached-nested.html" ); }, function(){ same( $("#cached-nested-list").length, 1 ); $.testHelper.openPage( "#" + home ); }, function() { $.testHelper.openPage( "#cache-tests/clear.html" ); }, function(){ same( $("#cached-nested-list").length, 1 ); start(); } ]); }); asyncTest( "filterCallback can be altered after widget creation", function(){ var listPage = $( "#search-filter-test" ); expect( listPage.find("li").length ); $.testHelper.pageSequence( [ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function() { $.testHelper.openPage( "#search-filter-test" ); }, function() { // set the listview instance callback listPage.find( "ul" ).listview( "option", "filterCallback", function() { ok(true, "custom callback invoked"); }); // trigger a change in the search filter listPage.find( "input" ).val( "foo" ).trigger( "change" ); //NOTE beware a poossible issue with timing here start(); } ]); }); asyncTest( "nested pages hash key is always in the hash (replaceState)", function(){ $.testHelper.pageSequence([ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function(){ // https://github.com/jquery/jquery-mobile/issues/1617 $.testHelper.openPage("#nested-lists-test"); }, function(){ // Click on the link of the third li element $('.ui-page-active li:eq(2) a:eq(0)').click(); }, function(){ ok( location.hash.search($.mobile.subPageUrlKey) >= 0 ); start(); } ]); }); asyncTest( "embedded listview page with nested pages is not removed from the dom", function() { $.testHelper.pageSequence([ function() { // open the nested list page same( $("div#nested-list-test").length, 1 ); $( "a#nested-list-test-anchor" ).click(); }, function() { // go back to the origin page window.history.back(); }, function() { // make sure the page is still in place same( $("div#nested-list-test").length, 1 ); start(); } ]); }); asyncTest( "list inherits theme from parent", function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#list-theme-inherit"); }, function() { var theme = $.mobile.activePage.jqmData('theme'); ok( $.mobile.activePage.find("ul > li").hasClass("ui-body-b"), "theme matches the parent"); window.history.back(); }, start ]); }); })(jQuery);
JavaScript