code
stringlengths
1
2.08M
language
stringclasses
1 value
/** * @license Highcharts JS v3.0.1 (2013-04-09) * Exporting module * * (c) 2010-2013 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, Math, setTimeout */ (function (Highcharts) { // encapsulate // create shortcuts var Chart = Highcharts.Chart, addEvent = Highcharts.addEvent, removeEvent = Highcharts.removeEvent, createElement = Highcharts.createElement, discardElement = Highcharts.discardElement, css = Highcharts.css, merge = Highcharts.merge, each = Highcharts.each, extend = Highcharts.extend, math = Math, mathMax = math.max, doc = document, win = window, isTouchDevice = Highcharts.isTouchDevice, M = 'M', L = 'L', DIV = 'div', HIDDEN = 'hidden', NONE = 'none', PREFIX = 'highcharts-', ABSOLUTE = 'absolute', PX = 'px', UNDEFINED, symbols = Highcharts.Renderer.prototype.symbols, defaultOptions = Highcharts.getOptions(), buttonOffset; // Add language extend(defaultOptions.lang, { printChart: 'Print chart', downloadPNG: 'Download PNG image', downloadJPEG: 'Download JPEG image', downloadPDF: 'Download PDF document', downloadSVG: 'Download SVG vector image', contextButtonTitle: 'Chart context menu' }); // Buttons and menus are collected in a separate config option set called 'navigation'. // This can be extended later to add control buttons like zoom and pan right click menus. defaultOptions.navigation = { menuStyle: { border: '1px solid #A0A0A0', background: '#FFFFFF', padding: '5px 0' }, menuItemStyle: { padding: '0 10px', background: NONE, color: '#303030', fontSize: isTouchDevice ? '14px' : '11px' }, menuItemHoverStyle: { background: '#4572A5', color: '#FFFFFF' }, buttonOptions: { symbolFill: '#E0E0E0', symbolSize: 14, symbolStroke: '#666', symbolStrokeWidth: 3, symbolX: 12.5, symbolY: 10.5, align: 'right', buttonSpacing: 3, height: 22, // text: null, theme: { fill: 'white', // capture hover stroke: 'none' }, verticalAlign: 'top', width: 24 } }; // Add the export related options defaultOptions.exporting = { //enabled: true, //filename: 'chart', type: 'image/png', url: 'http://export.highcharts.com/', //width: undefined, //scale: 2 buttons: { contextButton: { //x: -10, symbol: 'menu', _titleKey: 'contextButtonTitle', menuItems: [{ textKey: 'printChart', onclick: function () { this.print(); } }, { separator: true }, { textKey: 'downloadPNG', onclick: function () { this.exportChart(); } }, { textKey: 'downloadJPEG', onclick: function () { this.exportChart({ type: 'image/jpeg' }); } }, { textKey: 'downloadPDF', onclick: function () { this.exportChart({ type: 'application/pdf' }); } }, { textKey: 'downloadSVG', onclick: function () { this.exportChart({ type: 'image/svg+xml' }); } } // Enable this block to add "View SVG" to the dropdown menu /* ,{ text: 'View SVG', onclick: function () { var svg = this.getSVG() .replace(/</g, '\n&lt;') .replace(/>/g, '&gt;'); doc.body.innerHTML = '<pre>' + svg + '</pre>'; } } // */ ] } } }; // Add the Highcharts.post utility Highcharts.post = function (url, data) { var name, form; // create the form form = createElement('form', { method: 'post', action: url, enctype: 'multipart/form-data' }, { display: NONE }, doc.body); // add the data for (name in data) { createElement('input', { type: HIDDEN, name: name, value: data[name] }, null, form); } // submit form.submit(); // clean up discardElement(form); }; extend(Chart.prototype, { /** * Return an SVG representation of the chart * * @param additionalOptions {Object} Additional chart options for the generated SVG representation */ getSVG: function (additionalOptions) { var chart = this, chartCopy, sandbox, svg, seriesOptions, sourceWidth, sourceHeight, cssWidth, cssHeight, options = merge(chart.options, additionalOptions); // copy the options and add extra options // IE compatibility hack for generating SVG content that it doesn't really understand if (!doc.createElementNS) { /*jslint unparam: true*//* allow unused parameter ns in function below */ doc.createElementNS = function (ns, tagName) { return doc.createElement(tagName); }; /*jslint unparam: false*/ } // create a sandbox where a new chart will be generated sandbox = createElement(DIV, null, { position: ABSOLUTE, top: '-9999em', width: chart.chartWidth + PX, height: chart.chartHeight + PX }, doc.body); // get the source size cssWidth = chart.renderTo.style.width; cssHeight = chart.renderTo.style.height; sourceWidth = options.exporting.sourceWidth || options.chart.width || (/px$/.test(cssWidth) && parseInt(cssWidth, 10)) || 600; sourceHeight = options.exporting.sourceHeight || options.chart.height || (/px$/.test(cssHeight) && parseInt(cssHeight, 10)) || 400; // override some options extend(options.chart, { animation: false, renderTo: sandbox, forExport: true, width: sourceWidth, height: sourceHeight }); options.exporting.enabled = false; // hide buttons in print options.chart.plotBackgroundImage = null; // the converter doesn't handle images // prepare for replicating the chart options.series = []; each(chart.series, function (serie) { seriesOptions = merge(serie.options, { animation: false, // turn off animation showCheckbox: false, visible: serie.visible }); if (!seriesOptions.isInternal) { // used for the navigator series that has its own option set options.series.push(seriesOptions); } }); // generate the chart copy chartCopy = new Highcharts.Chart(options, chart.callback); // reflect axis extremes in the export each(['xAxis', 'yAxis'], function (axisType) { each(chart[axisType], function (axis, i) { var axisCopy = chartCopy[axisType][i], extremes = axis.getExtremes(), userMin = extremes.userMin, userMax = extremes.userMax; if (userMin !== UNDEFINED || userMax !== UNDEFINED) { axisCopy.setExtremes(userMin, userMax, true, false); } }); }); // get the SVG from the container's innerHTML svg = chartCopy.container.innerHTML; // free up memory options = null; chartCopy.destroy(); discardElement(sandbox); // sanitize svg = svg .replace(/zIndex="[^"]+"/g, '') .replace(/isShadow="[^"]+"/g, '') .replace(/symbolName="[^"]+"/g, '') .replace(/jQuery[0-9]+="[^"]+"/g, '') .replace(/url\([^#]+#/g, 'url(#') .replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ') .replace(/ href=/g, ' xlink:href=') .replace(/\n/, ' ') .replace(/<\/svg>.*?$/, '</svg>') // any HTML added to the container after the SVG (#894) /* This fails in IE < 8 .replace(/([0-9]+)\.([0-9]+)/g, function(s1, s2, s3) { // round off to save weight return s2 +'.'+ s3[0]; })*/ // Replace HTML entities, issue #347 .replace(/&nbsp;/g, '\u00A0') // no-break space .replace(/&shy;/g, '\u00AD') // soft hyphen // IE specific .replace(/<IMG /g, '<image ') .replace(/height=([^" ]+)/g, 'height="$1"') .replace(/width=([^" ]+)/g, 'width="$1"') .replace(/hc-svg-href="([^"]+)">/g, 'xlink:href="$1"/>') .replace(/id=([^" >]+)/g, 'id="$1"') .replace(/class=([^" ]+)/g, 'class="$1"') .replace(/ transform /g, ' ') .replace(/:(path|rect)/g, '$1') .replace(/style="([^"]+)"/g, function (s) { return s.toLowerCase(); }); // IE9 beta bugs with innerHTML. Test again with final IE9. svg = svg.replace(/(url\(#highcharts-[0-9]+)&quot;/g, '$1') .replace(/&quot;/g, "'"); if (svg.match(/ xmlns="/g).length === 2) { svg = svg.replace(/xmlns="[^"]+"/, ''); } return svg; }, /** * Submit the SVG representation of the chart to the server * @param {Object} options Exporting options. Possible members are url, type and width. * @param {Object} chartOptions Additional chart options for the SVG representation of the chart */ exportChart: function (options, chartOptions) { options = options || {}; var chart = this, chartExportingOptions = chart.options.exporting, svg = chart.getSVG(merge( { chart: { borderRadius: 0 } }, chartExportingOptions, chartOptions, { exporting: { sourceWidth: options.sourceWidth || chartExportingOptions.sourceWidth, // docs: option and parameter in exportChart() sourceHeight: options.sourceHeight || chartExportingOptions.sourceHeight // docs } } )); // merge the options options = merge(chart.options.exporting, options); // do the post Highcharts.post(options.url, { filename: options.filename || 'chart', type: options.type, width: options.width || 0, // IE8 fails to post undefined correctly, so use 0 scale: options.scale || 2, svg: svg }); }, /** * Print the chart */ print: function () { var chart = this, container = chart.container, origDisplay = [], origParent = container.parentNode, body = doc.body, childNodes = body.childNodes; if (chart.isPrinting) { // block the button while in printing mode return; } chart.isPrinting = true; // hide all body content each(childNodes, function (node, i) { if (node.nodeType === 1) { origDisplay[i] = node.style.display; node.style.display = NONE; } }); // pull out the chart body.appendChild(container); // print win.focus(); // #1510 win.print(); // allow the browser to prepare before reverting setTimeout(function () { // put the chart back in origParent.appendChild(container); // restore all body content each(childNodes, function (node, i) { if (node.nodeType === 1) { node.style.display = origDisplay[i]; } }); chart.isPrinting = false; }, 1000); }, /** * Display a popup menu for choosing the export type * * @param {String} name An identifier for the menu * @param {Array} items A collection with text and onclicks for the items * @param {Number} x The x position of the opener button * @param {Number} y The y position of the opener button * @param {Number} width The width of the opener button * @param {Number} height The height of the opener button */ contextMenu: function (name, items, x, y, width, height, button) { var chart = this, navOptions = chart.options.navigation, menuItemStyle = navOptions.menuItemStyle, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, cacheName = 'cache-' + name, menu = chart[cacheName], menuPadding = mathMax(width, height), // for mouse leave detection boxShadow = '3px 3px 10px #888', innerMenu, hide, hideTimer, menuStyle; // create the menu only the first time if (!menu) { // create a HTML element above the SVG chart[cacheName] = menu = createElement(DIV, { className: PREFIX + name }, { position: ABSOLUTE, zIndex: 1000, padding: menuPadding + PX }, chart.container); innerMenu = createElement(DIV, null, extend({ MozBoxShadow: boxShadow, WebkitBoxShadow: boxShadow, boxShadow: boxShadow }, navOptions.menuStyle), menu); // hide on mouse out hide = function () { css(menu, { display: NONE }); if (button) { button.setState(0); } }; // Hide the menu some time after mouse leave (#1357) addEvent(menu, 'mouseleave', function () { hideTimer = setTimeout(hide, 500); }); addEvent(menu, 'mouseenter', function () { clearTimeout(hideTimer); }); // create the items each(items, function (item) { if (item) { var element = item.separator ? createElement('hr', null, null, innerMenu) : createElement(DIV, { onmouseover: function () { css(this, navOptions.menuItemHoverStyle); }, onmouseout: function () { css(this, menuItemStyle); }, onclick: function () { hide(); item.onclick.apply(chart, arguments); }, innerHTML: item.text || chart.options.lang[item.textKey] }, extend({ cursor: 'pointer' }, menuItemStyle), innerMenu); // Keep references to menu divs to be able to destroy them chart.exportDivElements.push(element); } }); // Keep references to menu and innerMenu div to be able to destroy them chart.exportDivElements.push(innerMenu, menu); chart.exportMenuWidth = menu.offsetWidth; chart.exportMenuHeight = menu.offsetHeight; } menuStyle = { display: 'block' }; // if outside right, right align it if (x + chart.exportMenuWidth > chartWidth) { menuStyle.right = (chartWidth - x - width - menuPadding) + PX; } else { menuStyle.left = (x - menuPadding) + PX; } // if outside bottom, bottom align it if (y + height + chart.exportMenuHeight > chartHeight) { menuStyle.bottom = (chartHeight - y - menuPadding) + PX; } else { menuStyle.top = (y + height - menuPadding) + PX; } css(menu, menuStyle); }, /** * Add the export button to the chart */ addButton: function (options) { var chart = this, renderer = chart.renderer, btnOptions = merge(chart.options.navigation.buttonOptions, options), onclick = btnOptions.onclick, menuItems = btnOptions.menuItems, symbol, button, symbolAttr = { stroke: btnOptions.symbolStroke, fill: btnOptions.symbolFill }, symbolSize = btnOptions.symbolSize || 12, menuKey; if (!chart.btnCount) { chart.btnCount = 0; } menuKey = chart.btnCount++; // Keeps references to the button elements if (!chart.exportDivElements) { chart.exportDivElements = []; chart.exportSVGElements = []; } if (btnOptions.enabled === false) { return; } var attr = btnOptions.theme, states = attr.states, hover = states && states.hover, select = states && states.select, callback; delete attr.states; if (onclick) { callback = function () { onclick.apply(chart, arguments); }; } else if (menuItems) { callback = function () { chart.contextMenu( 'contextmenu', menuItems, button.translateX, button.translateY, button.width, button.height, button ); button.setState(2); }; } if (btnOptions.text && btnOptions.symbol) { attr.paddingLeft = Highcharts.pick(attr.paddingLeft, 25); } else if (!btnOptions.text) { extend(attr, { width: btnOptions.width, height: btnOptions.height, padding: 0 }); } button = renderer.button(btnOptions.text, 0, 0, callback, attr, hover, select) .attr({ title: chart.options.lang[btnOptions._titleKey], 'stroke-linecap': 'round' }); if (btnOptions.symbol) { symbol = renderer.symbol( btnOptions.symbol, btnOptions.symbolX - (symbolSize / 2), btnOptions.symbolY - (symbolSize / 2), symbolSize, symbolSize ) .attr(extend(symbolAttr, { 'stroke-width': btnOptions.symbolStrokeWidth || 1, zIndex: 1 })).add(button); } button.add() .align(extend(btnOptions, { width: button.width, x: Highcharts.pick(btnOptions.x, buttonOffset) // #1654 }), true, 'spacingBox'); buttonOffset += (button.width + btnOptions.buttonSpacing) * (btnOptions.align === 'right' ? -1 : 1); chart.exportSVGElements.push(button, symbol); }, /** * Destroy the buttons. */ destroyExport: function (e) { var chart = e.target, i, elem; // Destroy the extra buttons added for (i = 0; i < chart.exportSVGElements.length; i++) { elem = chart.exportSVGElements[i]; // Destroy and null the svg/vml elements elem.onclick = elem.ontouchstart = null; chart.exportSVGElements[i] = elem.destroy(); } // Destroy the divs for the menu for (i = 0; i < chart.exportDivElements.length; i++) { elem = chart.exportDivElements[i]; // Remove the event handler removeEvent(elem, 'mouseleave'); // Remove inline events chart.exportDivElements[i] = elem.onmouseout = elem.onmouseover = elem.ontouchstart = elem.onclick = null; // Destroy the div by moving to garbage bin discardElement(elem); } } }); symbols.menu = function (x, y, width, height) { var arr = [ M, x, y + 2.5, L, x + width, y + 2.5, M, x, y + height / 2 + 0.5, L, x + width, y + height / 2 + 0.5, M, x, y + height - 1.5, L, x + width, y + height - 1.5 ]; return arr; }; // Add the buttons on chart load Chart.prototype.callbacks.push(function (chart) { var n, exportingOptions = chart.options.exporting, buttons = exportingOptions.buttons; buttonOffset = 0; if (exportingOptions.enabled !== false) { for (n in buttons) { chart.addButton(buttons[n]); } // Destroy the export elements at chart destroy addEvent(chart, 'destroy', chart.destroyExport); } }); }(Highcharts));
JavaScript
/** * @license Highcharts JS v3.0.1 (2013-04-09) * MooTools adapter * * (c) 2010-2013 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Fx, $, $extend, $each, $merge, Events, Event, DOMEvent */ (function () { var win = window, doc = document, mooVersion = win.MooTools.version.substring(0, 3), // Get the first three characters of the version number legacy = mooVersion === '1.2' || mooVersion === '1.1', // 1.1 && 1.2 considered legacy, 1.3 is not. legacyEvent = legacy || mooVersion === '1.3', // In versions 1.1 - 1.3 the event class is named Event, in newer versions it is named DOMEvent. $extend = win.$extend || function () { return Object.append.apply(Object, arguments); }; win.HighchartsAdapter = { /** * Initialize the adapter. This is run once as Highcharts is first run. * @param {Object} pathAnim The helper object to do animations across adapters. */ init: function (pathAnim) { var fxProto = Fx.prototype, fxStart = fxProto.start, morphProto = Fx.Morph.prototype, morphCompute = morphProto.compute; // override Fx.start to allow animation of SVG element wrappers /*jslint unparam: true*//* allow unused parameters in fx functions */ fxProto.start = function (from, to) { var fx = this, elem = fx.element; // special for animating paths if (from.d) { //this.fromD = this.element.d.split(' '); fx.paths = pathAnim.init( elem, elem.d, fx.toD ); } fxStart.apply(fx, arguments); return this; // chainable }; // override Fx.step to allow animation of SVG element wrappers morphProto.compute = function (from, to, delta) { var fx = this, paths = fx.paths; if (paths) { fx.element.attr( 'd', pathAnim.step(paths[0], paths[1], delta, fx.toD) ); } else { return morphCompute.apply(fx, arguments); } }; /*jslint unparam: false*/ }, /** * Run a general method on the framework, following jQuery syntax * @param {Object} el The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (el, method) { // This currently works for getting inner width and height. If adding // more methods later, we need a conditional implementation for each. if (method === 'width' || method === 'height') { return parseInt($(el).getStyle(method), 10); } }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: function (scriptLocation, callback) { // We cannot assume that Assets class from mootools-more is available so instead insert a script tag to download script. var head = doc.getElementsByTagName('head')[0]; var script = doc.createElement('script'); script.type = 'text/javascript'; script.src = scriptLocation; script.onload = callback; head.appendChild(script); }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var isSVGElement = el.attr, effect, complete = options && options.complete; if (isSVGElement && !el.setStyle) { // add setStyle and getStyle methods for internal use in Moo el.getStyle = el.attr; el.setStyle = function () { // property value is given as array in Moo - break it down var args = arguments; this.attr.call(this, args[0], args[1][0]); }; // dirty hack to trick Moo into handling el as an element wrapper el.$family = function () { return true; }; } // stop running animations win.HighchartsAdapter.stop(el); // define and run the effect effect = new Fx.Morph( isSVGElement ? el : $(el), $extend({ transition: Fx.Transitions.Quad.easeInOut }, options) ); // Make sure that the element reference is set when animating svg elements if (isSVGElement) { effect.element = el; } // special treatment for paths if (params.d) { effect.toD = params.d; } // jQuery-like events if (complete) { effect.addEvent('complete', complete); } // run effect.start(params); // record for use in stop method el.fx = effect; }, /** * MooTool's each function * */ each: function (arr, fn) { return legacy ? $each(arr, fn) : Array.each(arr, fn); }, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { return arr.map(fn); }, /** * Grep or filter an array * @param {Array} arr * @param {Function} fn */ grep: function (arr, fn) { return arr.filter(fn); }, /** * Return the index of an item in an array, or -1 if not matched */ inArray: function (item, arr, from) { return arr.indexOf(item, from); }, /** * Get the offset of an element relative to the top left corner of the web page */ offset: function (el) { var offsets = el.getPosition(); // #1496 return { left: offsets.x, top: offsets.y }; }, /** * Extends an object with Events, if its not done */ extendWithEvents: function (el) { // if the addEvent method is not defined, el is a custom Highcharts object // like series or point if (!el.addEvent) { if (el.nodeName) { el = $(el); // a dynamically generated node } else { $extend(el, new Events()); // a custom object } } }, /** * Add an event listener * @param {Object} el HTML element or custom object * @param {String} type Event type * @param {Function} fn Event handler */ addEvent: function (el, type, fn) { if (typeof type === 'string') { // chart broke due to el being string, type function if (type === 'unload') { // Moo self destructs before custom unload events type = 'beforeunload'; } win.HighchartsAdapter.extendWithEvents(el); el.addEvent(type, fn); } }, removeEvent: function (el, type, fn) { if (typeof el === 'string') { // el.removeEvents below apperantly calls this method again. Do not quite understand why, so for now just bail out. return; } if (el.addEvent) { // If el doesn't have an addEvent method, there are no events to remove if (type) { if (type === 'unload') { // Moo self destructs before custom unload events type = 'beforeunload'; } if (fn) { el.removeEvent(type, fn); } else if (el.removeEvents) { // #958 el.removeEvents(type); } } else { el.removeEvents(); } } }, fireEvent: function (el, event, eventArguments, defaultFunction) { var eventArgs = { type: event, target: el }; // create an event object that keeps all functions event = legacyEvent ? new Event(eventArgs) : new DOMEvent(eventArgs); event = $extend(event, eventArguments); // When running an event on the Chart.prototype, MooTools nests the target in event.event if (!event.target && event.event) { event.target = event.event.target; } // override the preventDefault function to be able to use // this for custom events event.preventDefault = function () { defaultFunction = null; }; // if fireEvent is not available on the object, there hasn't been added // any events to it above if (el.fireEvent) { el.fireEvent(event.type, event); } // fire the default if it is passed and it is not prevented above if (defaultFunction) { defaultFunction(event); } }, /** * Set back e.pageX and e.pageY that MooTools has abstracted away. #1165, #1346. */ washMouseEvent: function (e) { if (e.page) { e.pageX = e.page.x; e.pageY = e.page.y; } return e; }, /** * Stop running animations on the object */ stop: function (el) { if (el.fx) { el.fx.cancel(); } } }; }());
JavaScript
/** * Dark blue theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: [0, 0, 250, 500], stops: [ [0, 'rgb(48, 96, 48)'], [1, 'rgb(0, 0, 0)'] ] }, borderColor: '#000000', borderWidth: 2, className: 'dark-container', plotBackgroundColor: 'rgba(255, 255, 255, .1)', plotBorderColor: '#CCCCCC', plotBorderWidth: 1 }, title: { style: { color: '#C0C0C0', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineColor: '#333333', gridLineWidth: 1, labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', tickColor: '#A0A0A0', title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { gridLineColor: '#333333', labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', minorTickInterval: null, tickColor: '#A0A0A0', tickWidth: 1, title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, tooltip: { backgroundColor: 'rgba(0, 0, 0, 0.75)', style: { color: '#F0F0F0' } }, toolbar: { itemStyle: { color: 'silver' } }, plotOptions: { line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } }, candlestick: { lineColor: 'white' } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#A0A0A0' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#444' } }, credits: { style: { color: '#666' } }, labels: { style: { color: '#CCC' } }, navigation: { buttonOptions: { symbolStroke: '#DDDDDD', hoverSymbolStroke: '#FFFFFF', theme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, stroke: '#000000' } } }, // scroll charts rangeSelector: { buttonTheme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, stroke: '#000000', style: { color: '#CCC', fontWeight: 'bold' }, states: { hover: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#BBB'], [0.6, '#888'] ] }, stroke: '#000000', style: { color: 'white' } }, select: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.1, '#000'], [0.3, '#333'] ] }, stroke: '#000000', style: { color: 'yellow' } } } }, inputStyle: { backgroundColor: '#333', color: 'silver' }, labelStyle: { color: 'silver' } }, navigator: { handles: { backgroundColor: '#666', borderColor: '#AAA' }, outlineColor: '#CCC', maskFill: 'rgba(16, 16, 16, 0.5)', series: { color: '#7798BF', lineColor: '#A6C7ED' } }, scrollbar: { barBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, barBorderColor: '#CCC', buttonArrowColor: '#CCC', buttonBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, buttonBorderColor: '#CCC', rifleColor: '#FFF', trackBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#000'], [1, '#333'] ] }, trackBorderColor: '#666' }, // special colors for some of the legendBackgroundColor: 'rgba(0, 0, 0, 0.5)', legendBackgroundColorSolid: 'rgb(35, 35, 70)', dataLabelsColor: '#444', textColor: '#C0C0C0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Grid theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'], chart: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 }, stops: [ [0, 'rgb(255, 255, 255)'], [1, 'rgb(240, 240, 255)'] ] }, borderWidth: 2, plotBackgroundColor: 'rgba(255, 255, 255, .9)', plotShadow: true, plotBorderWidth: 1 }, title: { style: { color: '#000', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineWidth: 1, lineColor: '#000', tickColor: '#000', labels: { style: { color: '#000', font: '11px Trebuchet MS, Verdana, sans-serif' } }, title: { style: { color: '#333', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { minorTickInterval: 'auto', lineColor: '#000', lineWidth: 1, tickWidth: 1, tickColor: '#000', labels: { style: { color: '#000', font: '11px Trebuchet MS, Verdana, sans-serif' } }, title: { style: { color: '#333', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: 'black' }, itemHoverStyle: { color: '#039' }, itemHiddenStyle: { color: 'gray' } }, labels: { style: { color: '#99b' } }, navigation: { buttonOptions: { theme: { stroke: '#CCCCCC' } } } }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Skies theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#514F78", "#42A07B", "#9B5E4A", "#72727F", "#1F949A", "#82914E", "#86777F", "#42A07B"], chart: { className: 'skies', borderWidth: 0, plotShadow: true, plotBackgroundImage: '/demo/gfx/skies.jpg', plotBackgroundColor: { linearGradient: [0, 0, 250, 500], stops: [ [0, 'rgba(255, 255, 255, 1)'], [1, 'rgba(255, 255, 255, 0)'] ] }, plotBorderWidth: 1 }, title: { style: { color: '#3E576F', font: '16px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, subtitle: { style: { color: '#6D869F', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, xAxis: { gridLineWidth: 0, lineColor: '#C0D0E0', tickColor: '#C0D0E0', labels: { style: { color: '#666', fontWeight: 'bold' } }, title: { style: { color: '#666', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, yAxis: { alternateGridColor: 'rgba(255, 255, 255, .5)', lineColor: '#C0D0E0', tickColor: '#C0D0E0', tickWidth: 1, labels: { style: { color: '#666', fontWeight: 'bold' } }, title: { style: { color: '#666', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#3E576F' }, itemHoverStyle: { color: 'black' }, itemHiddenStyle: { color: 'silver' } }, labels: { style: { color: '#3E576F' } } }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Gray theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#7798BF", "#55BF3B", "#DF5353", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, 'rgb(96, 96, 96)'], [1, 'rgb(16, 16, 16)'] ] }, borderWidth: 0, borderRadius: 15, plotBackgroundColor: null, plotShadow: false, plotBorderWidth: 0 }, title: { style: { color: '#FFF', font: '16px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, subtitle: { style: { color: '#DDD', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, xAxis: { gridLineWidth: 0, lineColor: '#999', tickColor: '#999', labels: { style: { color: '#999', fontWeight: 'bold' } }, title: { style: { color: '#AAA', font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, yAxis: { alternateGridColor: null, minorTickInterval: null, gridLineColor: 'rgba(255, 255, 255, .1)', minorGridLineColor: 'rgba(255,255,255,0.07)', lineWidth: 0, tickWidth: 0, labels: { style: { color: '#999', fontWeight: 'bold' } }, title: { style: { color: '#AAA', font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, legend: { itemStyle: { color: '#CCC' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#333' } }, labels: { style: { color: '#CCC' } }, tooltip: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, 'rgba(96, 96, 96, .8)'], [1, 'rgba(16, 16, 16, .8)'] ] }, borderWidth: 0, style: { color: '#FFF' } }, plotOptions: { series: { shadow: true }, line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } }, candlestick: { lineColor: 'white' } }, toolbar: { itemStyle: { color: '#CCC' } }, navigation: { buttonOptions: { symbolStroke: '#DDDDDD', hoverSymbolStroke: '#FFFFFF', theme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, stroke: '#000000' } } }, // scroll charts rangeSelector: { buttonTheme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, stroke: '#000000', style: { color: '#CCC', fontWeight: 'bold' }, states: { hover: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#BBB'], [0.6, '#888'] ] }, stroke: '#000000', style: { color: 'white' } }, select: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.1, '#000'], [0.3, '#333'] ] }, stroke: '#000000', style: { color: 'yellow' } } } }, inputStyle: { backgroundColor: '#333', color: 'silver' }, labelStyle: { color: 'silver' } }, navigator: { handles: { backgroundColor: '#666', borderColor: '#AAA' }, outlineColor: '#CCC', maskFill: 'rgba(16, 16, 16, 0.5)', series: { color: '#7798BF', lineColor: '#A6C7ED' } }, scrollbar: { barBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, barBorderColor: '#CCC', buttonArrowColor: '#CCC', buttonBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, buttonBorderColor: '#CCC', rifleColor: '#FFF', trackBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#000'], [1, '#333'] ] }, trackBorderColor: '#666' }, // special colors for some of the demo examples legendBackgroundColor: 'rgba(48, 48, 48, 0.8)', legendBackgroundColorSolid: 'rgb(70, 70, 70)', dataLabelsColor: '#444', textColor: '#E0E0E0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Dark blue theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 }, stops: [ [0, 'rgb(48, 48, 96)'], [1, 'rgb(0, 0, 0)'] ] }, borderColor: '#000000', borderWidth: 2, className: 'dark-container', plotBackgroundColor: 'rgba(255, 255, 255, .1)', plotBorderColor: '#CCCCCC', plotBorderWidth: 1 }, title: { style: { color: '#C0C0C0', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineColor: '#333333', gridLineWidth: 1, labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', tickColor: '#A0A0A0', title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { gridLineColor: '#333333', labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', minorTickInterval: null, tickColor: '#A0A0A0', tickWidth: 1, title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, tooltip: { backgroundColor: 'rgba(0, 0, 0, 0.75)', style: { color: '#F0F0F0' } }, toolbar: { itemStyle: { color: 'silver' } }, plotOptions: { line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } }, candlestick: { lineColor: 'white' } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#A0A0A0' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#444' } }, credits: { style: { color: '#666' } }, labels: { style: { color: '#CCC' } }, navigation: { buttonOptions: { symbolStroke: '#DDDDDD', hoverSymbolStroke: '#FFFFFF', theme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, stroke: '#000000' } } }, // scroll charts rangeSelector: { buttonTheme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, stroke: '#000000', style: { color: '#CCC', fontWeight: 'bold' }, states: { hover: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#BBB'], [0.6, '#888'] ] }, stroke: '#000000', style: { color: 'white' } }, select: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.1, '#000'], [0.3, '#333'] ] }, stroke: '#000000', style: { color: 'yellow' } } } }, inputStyle: { backgroundColor: '#333', color: 'silver' }, labelStyle: { color: 'silver' } }, navigator: { handles: { backgroundColor: '#666', borderColor: '#AAA' }, outlineColor: '#CCC', maskFill: 'rgba(16, 16, 16, 0.5)', series: { color: '#7798BF', lineColor: '#A6C7ED' } }, scrollbar: { barBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, barBorderColor: '#CCC', buttonArrowColor: '#CCC', buttonBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, buttonBorderColor: '#CCC', rifleColor: '#FFF', trackBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#000'], [1, '#333'] ] }, trackBorderColor: '#666' }, // special colors for some of the legendBackgroundColor: 'rgba(0, 0, 0, 0.5)', legendBackgroundColorSolid: 'rgb(35, 35, 70)', dataLabelsColor: '#444', textColor: '#C0C0C0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v3.0.1 (2013-04-09) * * (c) 2009-2013 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console */ (function () { // encapsulated variables var UNDEFINED, doc = document, win = window, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = navigator.userAgent, isOpera = win.opera, isIE = /msie/i.test(userAgent) && !isOpera, docMode8 = doc.documentMode === 8, isWebKit = /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext, Renderer, hasTouch = doc.documentElement.ontouchstart !== UNDEFINED, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, timeUnits, noop = function () {}, charts = [], PRODUCT = 'Highcharts', VERSION = '3.0.1', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', /* * Empirical lowest possible opacities for TRACKER_FILL * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')', // invisible but clickable //TRACKER_FILL = 'rgba(192,192,192,0.5)', NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', MILLISECOND = 'millisecond', SECOND = 'second', MINUTE = 'minute', HOUR = 'hour', DAY = 'day', WEEK = 'week', MONTH = 'month', YEAR = 'year', // constants for attributes LINEAR_GRADIENT = 'linearGradient', STOPS = 'stops', STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used makeTime, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}; // The Highcharts namespace win.Highcharts = win.Highcharts ? error(16, true) : {}; /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ function extend(a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; } /** * Deep merge two or more objects and return a third object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, len = arguments.length, ret = {}, doCopy = function (copy, original) { var value, key; for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // For each argument, extend the return for (i = 0; i < len; i++) { ret = doCopy(ret, arguments[i]); } return ret; } /** * Take an array and turn into a hash with even number arguments as keys and odd numbers as * values. Allows creating constants for commonly used style properties, attributes etc. * Avoid it in performance critical situations like looping */ function hash() { var i = 0, args = arguments, length = args.length, obj = {}; for (; i < length; i++) { obj[args[i++]] = args[i]; } return obj; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. Like MooTools' $.defined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, setAttribute = 'setAttribute', ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem[setAttribute](prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem[setAttribute](key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. Like * MooTools' $.splat. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Return the first value that is defined. Like MooTools' $.pick. */ function pick() { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (typeof arg !== 'undefined' && arg !== null) { return arg; } } } /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isIE) { if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function () {}; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ function numberFormat(number, decimals, decPoint, thousandsSep) { var lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = number, c = decimals === -1 ? ((n || 0).toString().split('.')[1] || '').length : // preserve decimals (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals), d = decPoint === undefined ? lang.decimalPoint : decPoint, t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "", i = String(pInt(n = mathAbs(+n || 0).toFixed(c))), j = i.length > 3 ? i.length % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""); } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { // Create an array of the remaining length +1 and join it with 0's return new Array((length || 2) + 1 - String(number).length).join(0) + number; } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ function wrap(obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return 'Invalid date'; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; val = numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, options) { var normalized, i; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (options && options.allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { interval = multiples[i]; if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) { break; } } // multiply back to the correct magnitude interval *= magnitude; return interval; } /** * Get a normalized tick interval for dates. Returns a configuration object with * unit range (interval), count and name. Used to prepare data for getTimeTicks. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs * of segments in stock charts, the normalizing logic was extracted in order to * prevent it for running over again for each segment having the same interval. * #662, #697. */ function normalizeTimeTickInterval(tickInterval, unitsOption) { var units = unitsOption || [[ MILLISECOND, // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ SECOND, [1, 2, 5, 10, 15, 30] ], [ MINUTE, [1, 2, 5, 10, 15, 30] ], [ HOUR, [1, 2, 3, 4, 6, 8, 12] ], [ DAY, [1, 2] ], [ WEEK, [1, 2] ], [ MONTH, [1, 2, 3, 4, 6] ], [ YEAR, null ]], unit = units[units.length - 1], // default unit is years interval = timeUnits[unit[0]], multiples = unit[1], count, i; // loop through the units to find the one that best fits the tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = timeUnits[unit[0]]; multiples = unit[1]; if (units[i + 1]) { // lessThan is in the middle between the highest multiple and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + timeUnits[units[i + 1][0]]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the count count = normalizeTickInterval(tickInterval / interval, multiples); return { unitRange: interval, count: count, unitName: unit[0] }; } /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. Return an array * with the time positions. Used in datetime axes as well as for grouping * data on a datetime axis. * * @param {Object} normalizedInterval The interval in axis values (ms) and the count * @param {Number} min The minimum in axis values * @param {Number} max The maximum in axis values * @param {Number} startOfWeek */ function getTimeTicks(normalizedInterval, min, max, startOfWeek) { var tickPositions = [], i, higherRanks = {}, useUTC = defaultOptions.global.useUTC, minYear, // used in months and years as a basis for Date.UTC() minDate = new Date(min), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 if (interval >= timeUnits[SECOND]) { // second minDate.setMilliseconds(0); minDate.setSeconds(interval >= timeUnits[MINUTE] ? 0 : count * mathFloor(minDate.getSeconds() / count)); } if (interval >= timeUnits[MINUTE]) { // minute minDate[setMinutes](interval >= timeUnits[HOUR] ? 0 : count * mathFloor(minDate[getMinutes]() / count)); } if (interval >= timeUnits[HOUR]) { // hour minDate[setHours](interval >= timeUnits[DAY] ? 0 : count * mathFloor(minDate[getHours]() / count)); } if (interval >= timeUnits[DAY]) { // day minDate[setDate](interval >= timeUnits[MONTH] ? 1 : count * mathFloor(minDate[getDate]() / count)); } if (interval >= timeUnits[MONTH]) { // month minDate[setMonth](interval >= timeUnits[YEAR] ? 0 : count * mathFloor(minDate[getMonth]() / count)); minYear = minDate[getFullYear](); } if (interval >= timeUnits[YEAR]) { // year minYear -= minYear % count; minDate[setFullYear](minYear); } // week is a special case that runs outside the hierarchy if (interval === timeUnits[WEEK]) { // get start of current week, independent of count minDate[setDate](minDate[getDate]() - minDate[getDay]() + pick(startOfWeek, 1)); } // get tick positions i = 1; minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), timezoneOffset = useUTC ? 0 : (24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950 // iterate and add tick positions at appropriate values while (time < max) { tickPositions.push(time); // if the interval is years, use Date.UTC to increase years if (interval === timeUnits[YEAR]) { time = makeTime(minYear + i * count, 0); // if the interval is months, use Date.UTC to increase months } else if (interval === timeUnits[MONTH]) { time = makeTime(minYear, minMonth + i * count); // if we're using global time, the interval is not fixed as it jumps // one hour at the DST crossover } else if (!useUTC && (interval === timeUnits[DAY] || interval === timeUnits[WEEK])) { time = makeTime(minYear, minMonth, minDateDate + i * count * (interval === timeUnits[DAY] ? 1 : 7)); // else, the interval is fixed and we use simple addition } else { // mark new days if the time is dividable by day if (interval <= timeUnits[HOUR] && time % timeUnits[DAY] === timezoneOffset) { higherRanks[time] = DAY; } time += interval * count; } i++; } // push the last time tickPositions.push(time); } // record information on the chosen unit - for dynamic label formatter tickPositions.info = extend(normalizedInterval, { higherRanks: higherRanks, totalRange: interval * count }); return tickPositions; } /** * Helper class that contains variuos counters that are local to the chart. */ function ChartCounters() { this.color = 0; this.symbol = 0; } ChartCounters.prototype = { /** * Wraps the color counter if it reaches the specified length. */ wrapColor: function (length) { if (this.color >= length) { this.color = 0; } }, /** * Wraps the symbol counter if it reaches the specified length. */ wrapSymbol: function (length) { if (this.symbol >= length) { this.symbol = 0; } } }; /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].ss_i = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.ss_i - b.ss_i : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].ss_i; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Provide error messages for debugging, with links to online explanation */ function error(code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw msg; } else if (win.console) { console.log(msg); } } /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num) { return parseFloat( num.toPrecision(14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ /*jslint white: true*/ timeUnits = hash( MILLISECOND, 1, SECOND, 1000, MINUTE, 60000, HOUR, 3600000, DAY, 24 * 3600000, WEEK, 7 * 24 * 3600000, MONTH, 31 * 24 * 3600000, YEAR, 31556952000 ); /*jslint white: false*/ /** * Path interpolation algorithm used across adapters */ pathAnim = { /** * Prepare start and end values so that the path can be animated one to one */ init: function (elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy startBaseLine, endBaseLine, sixify = function (arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] === M) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } }; if (bezier) { sixify(start); sixify(end); } // pull out the base lines before padding if (elem.isArea) { startBaseLine = start.splice(start.length - 6, 6); endBaseLine = end.splice(end.length - 6, 6); } // if shifting points, prepend a dummy point to the end path if (shift <= end.length / numParams) { while (shift--) { end = [].concat(end).splice(0, numParams).concat(end); } } elem.shift = 0; // reset for following animations // copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { //bezier && sixify(start); slice = [].concat(start).splice(start.length - numParams, numParams); if (bezier) { // disable first control point slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } start = start.concat(slice); } } if (startBaseLine) { // append the base lines for areas start = start.concat(startBaseLine); end = end.concat(endBaseLine); } return [start, end]; }, /** * Interpolate each value of the path and return the array */ step: function (start, end, pos, complete) { var ret = [], i = start.length, startVal; if (pos === 1) { // land on the final path without adjustment points appended in the ends ret = complete; } else if (i === end.length && pos < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : pos * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } return ret; } }; (function ($) { /** * The default HighchartsAdapter for jQuery */ win.HighchartsAdapter = win.HighchartsAdapter || ($ && { /** * Initialize the adapter by applying some extensions to jQuery */ init: function (pathAnim) { // extend the animate function to allow SVG animations var Fx = $.fx, Step = Fx.step, dSetter, Tween = $.Tween, propHooks = Tween && Tween.propHooks; /*jslint unparam: true*//* allow unused param x in this function */ $.extend($.easing, { easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; } }); /*jslint unparam: false*/ // extend some methods to check for elem.attr, which means it is a Highcharts SVG object $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) { var obj = Step, base, elem; // Handle different parent objects if (fn === 'cur') { obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype } else if (fn === '_default' && Tween) { // jQuery 1.8 model obj = propHooks[fn]; fn = 'set'; } // Overwrite the method base = obj[fn]; if (base) { // step.width and step.height don't exist in jQuery < 1.7 // create the extended function replacement obj[fn] = function (fx) { // Fx.prototype.cur does not use fx argument fx = i ? fx : this; // shortcut elem = fx.elem; // Fx.prototype.cur returns the current value. The other ones are setters // and returning a value has no effect. return elem.attr ? // is SVG element wrapper elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method base.apply(this, arguments); // use jQuery's built-in method }; } }); // Define the setter function for d (path definitions) dSetter = function (fx) { var elem = fx.elem, ends; // Normally start and end should be set in state == 0, but sometimes, // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped // in these cases if (!fx.started) { ends = pathAnim.init(elem, elem.d, elem.toD); fx.start = ends[0]; fx.end = ends[1]; fx.started = true; } // interpolate each value of the path elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD)); }; // jQuery 1.8 style if (Tween) { propHooks.d = { set: dSetter }; // pre 1.8 } else { // animate paths Step.d = dSetter; } /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ this.each = Array.prototype.forEach ? function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } : function (arr, fn) { // legacy var i = 0, len = arr.length; for (; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; /** * Register Highcharts as a plugin in the respective framework */ $.fn.highcharts = function () { var constr = 'Chart', // default constructor args = arguments, options, ret, chart; if (isString(args[0])) { constr = args[0]; args = Array.prototype.slice.call(args, 1); } options = args[0]; // Create the chart if (options !== UNDEFINED) { /*jslint unused:false*/ options.chart = options.chart || {}; options.chart.renderTo = this[0]; chart = new Highcharts[constr](options, args[1]); ret = this; /*jslint unused:true*/ } // When called without parameters or with the return argument, get a predefined chart if (options === UNDEFINED) { ret = charts[attr(this[0], 'data-highcharts-chart')]; } return ret; }; }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: $.getScript, /** * Return the index of an item in an array, or -1 if not found */ inArray: $.inArray, /** * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method. * @param {Object} elem The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (elem, method) { return $(elem)[method](); }, /** * Filter an array */ grep: $.grep, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { //return jQuery.map(arr, fn); var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Get the position of an element relative to the top left of the page */ offset: function (el) { return $(el).offset(); }, /** * Add an event listener * @param {Object} el A HTML element or custom object * @param {String} event The event type * @param {Function} fn The event handler */ addEvent: function (el, event, fn) { $(el).bind(event, fn); }, /** * Remove event added with addEvent * @param {Object} el The object * @param {String} eventType The event type. Leave blank to remove all events. * @param {Function} handler The function to remove */ removeEvent: function (el, eventType, handler) { // workaround for jQuery issue with unbinding custom events: // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2 var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent'; if (doc[func] && el && !el[func]) { el[func] = function () {}; } $(el).unbind(eventType, handler); }, /** * Fire an event on a custom object * @param {Object} el * @param {String} type * @param {Object} eventArguments * @param {Function} defaultFunction */ fireEvent: function (el, type, eventArguments, defaultFunction) { var event = $.Event(type), detachedType = 'detached' + type, defaultPrevented; // Remove warnings in Chrome when accessing layerX and layerY. Although Highcharts // never uses these properties, Chrome includes them in the default click event and // raises the warning when they are copied over in the extend statement below. // // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid // testing if they are there (warning in chrome) the only option is to test if running IE. if (!isIE && eventArguments) { delete eventArguments.layerX; delete eventArguments.layerY; } extend(event, eventArguments); // Prevent jQuery from triggering the object method that is named the // same as the event. For example, if the event is 'select', jQuery // attempts calling el.select and it goes into a loop. if (el[type]) { el[detachedType] = el[type]; el[type] = null; } // Wrap preventDefault and stopPropagation in try/catch blocks in // order to prevent JS errors when cancelling events on non-DOM // objects. #615. /*jslint unparam: true*/ $.each(['preventDefault', 'stopPropagation'], function (i, fn) { var base = event[fn]; event[fn] = function () { try { base.call(event); } catch (e) { if (fn === 'preventDefault') { defaultPrevented = true; } } }; }); /*jslint unparam: false*/ // trigger it $(el).trigger(event); // attach the method if (el[detachedType]) { el[type] = el[detachedType]; el[detachedType] = null; } if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) { defaultFunction(event); } }, /** * Extension method needed for MooTools */ washMouseEvent: function (e) { var ret = e.originalEvent || e; // computed by jQuery, needed by IE8 if (ret.pageX === UNDEFINED) { // #1236 ret.pageX = e.pageX; ret.pageY = e.pageY; } return ret; }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var $el = $(el); if (params.d) { el.toD = params.d; // keep the array form for paths, used in $.fx.step.d params.d = 1; // because in jQuery, animating to an array has a different meaning } $el.stop(); if (params.opacity !== UNDEFINED && el.attr) { params.opacity += 'px'; // force jQuery to use same logic as width and height } $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { $(el).stop(); } }); }(win.jQuery)); // check for a custom HighchartsAdapter defined prior to this file var globalAdapter = win.HighchartsAdapter, adapter = globalAdapter || {}; // Initialize the adapter if (globalAdapter) { globalAdapter.init.call(globalAdapter, pathAnim); } // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object // and all the utility functions will be null. In that case they are populated by the // default adapters below. var adapterRun = adapter.adapterRun, getScript = adapter.getScript, inArray = adapter.inArray, each = adapter.each, grep = adapter.grep, offset = adapter.offset, map = adapter.map, addEvent = adapter.addEvent, removeEvent = adapter.removeEvent, fireEvent = adapter.fireEvent, washMouseEvent = adapter.washMouseEvent, animate = adapter.animate, stop = adapter.stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ var defaultLabelOptions = { enabled: true, // rotation: 0, align: 'center', x: 0, y: 15, /*formatter: function () { return this.value; },*/ style: { color: '#666', cursor: 'default', fontSize: '11px', lineHeight: '14px' } }; defaultOptions = { colors: ['#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', '#492970', '#f28f43', '#77a1e5', '#c42525', '#a6c96a'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ',' }, global: { useUTC: true, canvasToolsURL: 'http://code.highcharts.com/3.0.1/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/3.0.1/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 5, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacingTop: 10, spacingRight: 10, spacingBottom: 15, spacingLeft: 10, style: { fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, // margin: 15, // x: 0, // verticalAlign: 'top', y: 15, style: { color: '#274b6d',//#3E576F', fontSize: '16px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', y: 30, style: { color: '#4d759e' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, lineWidth: 2, //shadow: false, // stacking: null, marker: { enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true //radius: base + 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: merge(defaultLabelOptions, { enabled: false, formatter: function () { return this.y; }, verticalAlign: 'bottom', // above singular point y: 0 // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, // padding: 3, // shadow: false }), cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, showInLegend: true, states: { // states for the entire series hover: { //enabled: false, //lineWidth: base + 1, marker: { // lineWidth: base + 1, // radius: base + 1 } }, select: { marker: {} } }, stickyTracking: true //tooltip: { //pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} // turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, borderWidth: 1, borderColor: '#909090', borderRadius: 5, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 10, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { cursor: 'pointer', color: '#274b6d', fontSize: '12px' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '1em' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(255, 255, 255, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>', shadow: true, //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var useUTC = defaultOptions.global.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) { return new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Pull out axis options and apply them to the respective default axis options /*defaultXAxisOptions = merge(defaultXAxisOptions, options.xAxis); defaultYAxisOptions = merge(defaultYAxisOptions, options.yAxis); options.xAxis = options.yAxis = UNDEFINED;*/ // Merge in the default options defaultOptions = merge(defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Merely exposing defaultOptions for outside modules * isn't enough because the setOptions method creates a new object. */ function getOptions() { return defaultOptions; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var Color = function (input) { // declare variables var rgba = [], result, stops; /** * Parse the input color to rgba array * @param {String} input */ function init(input) { // Gradients if (input && input.stops) { stops = map(input.stops, function (stop) { return Color(stop[1]); }); // Solid colors } else { // rgba result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } else { // rgb result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } } } } } /** * Return the color a specified format * @param {String} format */ function get(format) { var ret; if (stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(stops, function (stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && !isNaN(rgba[0])) { if (format === 'rgb') { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; } /** * Brighten the color * @param {Number} alpha */ function brighten(alpha) { if (stops) { each(stops, function (stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { var i; for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; } /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ function setOpacity(alpha) { rgba[3] = alpha; return this; } // initialize: parse the input init(input); // public methods return { get: get, brighten: brighten, rgba: rgba, setOpacity: setOpacity }; }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; /** * A collection of attribute setters. These methods, if defined, are called right before a certain * attribute is set on an element wrapper. Returning false prevents the default attribute * setter to run. Returning a value causes the default setter to set that value. Used in * Renderer.label. */ wrapper.attrSetters = {}; }, /** * Default base for animation */ opacity: 1, /** * Animate a given attribute * @param {Object} params * @param {Number} options The same options as in jQuery animation * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions); if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params); if (complete) { complete(); } } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val) { var wrapper = this, key, value, result, i, child, element = wrapper.element, nodeName = element.nodeName.toLowerCase(), // Android2 requires lower for "text" renderer = wrapper.renderer, skipAttr, titleNode, attrSetters = wrapper.attrSetters, shadows = wrapper.shadows, hasSetSymbolSize, doTransform, ret = wrapper; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (isString(hash)) { key = hash; if (nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } else if (key === 'strokeWidth') { key = 'stroke-width'; } ret = attr(element, key) || wrapper[key] || 0; if (key !== 'd' && key !== 'visibility') { // 'd' is string in animation step ret = parseFloat(ret); } // setter } else { for (key in hash) { skipAttr = false; // reset value = hash[key]; // check for a specific attribute setter result = attrSetters[key] && attrSetters[key].call(wrapper, value, key); if (result !== false) { if (result !== UNDEFINED) { value = result; // the attribute setter has returned a new value to set } // paths if (key === 'd') { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } //wrapper.d = value; // shortcut for animations // update child tspans x values } else if (key === 'x' && nodeName === 'text') { for (i = 0; i < element.childNodes.length; i++) { child = element.childNodes[i]; // if the x values are equal, the tspan represents a linebreak if (attr(child, 'x') === attr(element, 'x')) { //child.setAttribute('x', value); attr(child, 'x', value); } } } else if (wrapper.rotation && (key === 'x' || key === 'y')) { doTransform = true; // apply gradients } else if (key === 'fill') { value = renderer.color(value, element, key); // circle x and y } else if (nodeName === 'circle' && (key === 'x' || key === 'y')) { key = { x: 'cx', y: 'cy' }[key] || key; // rectangle border radius } else if (nodeName === 'rect' && key === 'r') { attr(element, { rx: value, ry: value }); skipAttr = true; // translation and text rotation } else if (key === 'translateX' || key === 'translateY' || key === 'rotation' || key === 'verticalAlign' || key === 'scaleX' || key === 'scaleY') { doTransform = true; skipAttr = true; // apply opacity as subnode (required by legacy WebKit and Batik) } else if (key === 'stroke') { value = renderer.color(value, element, key); // emulate VML's dashstyle implementation } else if (key === 'dashstyle') { key = 'stroke-dasharray'; value = value && value.toLowerCase(); if (value === 'solid') { value = NONE; } else if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * hash['stroke-width']; } value = value.join(','); } // IE9/MooTools combo: MooTools returns objects instead of numbers and IE9 Beta 2 // is unable to cast them. Test again with final IE9. } else if (key === 'width') { value = pInt(value); // Text alignment } else if (key === 'align') { key = 'text-anchor'; value = { left: 'start', center: 'middle', right: 'end' }[value]; // Title requires a subnode, #431 } else if (key === 'title') { titleNode = element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); element.appendChild(titleNode); } titleNode.textContent = value; } // jQuery animate changes case if (key === 'strokeWidth') { key = 'stroke-width'; } // In Chrome/Win < 6 as well as Batik, the stroke attribute can't be set when the stroke- // width is 0. #1369 if (key === 'stroke-width' || key === 'stroke') { wrapper[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (wrapper.stroke && wrapper['stroke-width']) { attr(element, 'stroke', wrapper.stroke); attr(element, 'stroke-width', wrapper['stroke-width']); wrapper.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && wrapper.hasStroke) { element.removeAttribute('stroke'); wrapper.hasStroke = false; } skipAttr = true; } // symbols if (wrapper.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { wrapper.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } // let the shadow follow the main element if (shadows && /^(width|height|visibility|x|y|d|transform)$/.test(key)) { i = shadows.length; while (i--) { attr( shadows[i], key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : value ); } } // validate heights if ((key === 'width' || key === 'height') && nodeName === 'rect' && value < 0) { value = 0; } // Record for animation and quick access without polling the DOM wrapper[key] = value; if (key === 'text') { // Delete bBox memo when the text changes if (value !== wrapper.textStr) { delete wrapper.bBox; } wrapper.textStr = value; if (wrapper.added) { renderer.buildText(wrapper); } } else if (!skipAttr) { attr(element, key, value); } } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (doTransform) { wrapper.updateTransform(); } } return ret; }, /** * Add a class name to an element */ addClass: function (className) { attr(this.element, 'class', attr(this.element, 'class') + ' ' + className); return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName](wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (strokeWidth, x, y, width, height) { var wrapper = this, key, attribs = {}, values = {}, normalizer; strokeWidth = strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges values.x = mathFloor(x || wrapper.x || 0) + normalizer; values.y = mathFloor(y || wrapper.y || 0) + normalizer; values.width = mathFloor((width || wrapper.width || 0) - 2 * normalizer); values.height = mathFloor((height || wrapper.height || 0) - 2 * normalizer); values.strokeWidth = strokeWidth; for (key in values) { if (wrapper[key] !== values[key]) { // only set attribute if changed wrapper[key] = attribs[key] = values[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { /*jslint unparam: true*//* allow unused param a in the regexp function below */ var elemWrapper = this, elem = elemWrapper.element, textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text', n, serializedCss = '', hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Merge the new styles with the old ones styles = extend( elemWrapper.styles, styles ); // store object elemWrapper.styles = styles; // Don't handle line wrap on canvas if (useCanVG && textWidth) { delete styles.width; } // serialize and set style attribute if (isIE && !hasSVG) { // legacy IE doesn't support setting style attribute if (textWidth) { delete styles.width; } css(elemWrapper.element, styles); } else { for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } elemWrapper.attr({ style: serializedCss }); } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // touch if (hasTouch && eventType === 'click') { this.element.ontouchstart = function (e) { e.preventDefault(); handler(); }; } // simplest possible event model for internal use this.element['on' + eventType] = handler; return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { this.element.radialReference = coordinates; return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element, bBox = wrapper.bBox; // faking getBBox in exported SVG in legacy IE if (!bBox) { // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } bBox = wrapper.bBox = { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; } return bBox; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], nonLeft = align && align !== 'left', shadows = wrapper.shadows; // apply translate if (translateX || translateY) { css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var width, height, rotation = wrapper.rotation, baseline, radians = 0, costheta = 1, sintheta = 0, quad, textWidth = pInt(wrapper.textWidth), xCorr = wrapper.xCorr || 0, yCorr = wrapper.yCorr || 0, currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','), rotationStyle = {}, cssTransformKey; if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed if (defined(rotation)) { if (renderer.isSVG) { // #916 cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; } else { radians = rotation * deg2rad; // deg to rad costheta = mathCos(radians); sintheta = mathSin(radians); // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://highcharts.com/tests/?file=text-rotation rotationStyle.filter = rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE; } css(elem, rotationStyle); } width = pick(wrapper.elemWidth, elem.offsetWidth); height = pick(wrapper.elemHeight, elem.offsetHeight); // update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: 'normal' }); width = textWidth; } // correct x and y baseline = renderer.fontMetrics(elem.style.fontSize).b; xCorr = costheta < 0 && -width; yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(elem, { textAlign: align }); } // record correction wrapper.xCorr = xCorr; wrapper.yCorr = yCorr; } // apply position with correction css(elem, { left: (x + xCorr) + PX, top: (y + yCorr) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { height = elem.offsetHeight; // assigned to height for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, transform = []; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // apply translate if (translateX || translateY) { transform.push('translate(' + translateX + ',' + translateY + ')'); } // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (wrapper.x || 0) + ' ' + (wrapper.y || 0) + ')'); } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { attr(wrapper.element, 'transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function () { var wrapper = this, bBox = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad; if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669) if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '22.7') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } wrapper.bBox = bBox; } return bBox; }, /** * Show the element */ show: function () { return this.attr({ visibility: VISIBLE }); }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.hide(); } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, parentWrapper = parent || renderer, parentNode = parentWrapper.element || renderer.box, childNodes = parentNode.childNodes, element = this.element, zIndex = attr(element, 'zIndex'), otherElement, otherZIndex, i, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // mark the container as having z indexed children if (zIndex) { parentWrapper.handleZ = true; zIndex = pInt(zIndex); } // insert according to this and other elements' zIndex if (parentWrapper.handleZ) { // this element or any of its siblings has a z index for (i = 0; i < childNodes.length; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // insert before the first element with a higher zIndex pInt(otherZIndex) > zIndex || // if no zIndex given, insert before the first element with a zIndex (!defined(zIndex) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; break; } } } // default: append at the end if (!inserted) { parentNode.appendChild(element); } // mark as added this.added = true; // fire an event for internal hooks fireEvent(this, 'add'); return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, forExport) { var renderer = this, loc = location, boxWrapper, desc; boxWrapper = renderer.createElement('svg') .attr({ xmlns: SVG_NS, version: '1.1' }); container.appendChild(boxWrapper.element); // object properties renderer.isSVG = true; renderer.box = boxWrapper.element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? loc.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION)); renderer.defs = this.createElement('defs').add(); renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, lines = pick(wrapper.textStr, '').toString() .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g), childNodes = textNode.childNodes, styleRegex = /style="([^"]+)"/, hrefRegex = /href="([^"]+)"/, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = textStyles && textStyles.width && pInt(textStyles.width), textLineHeight = textStyles && textStyles.lineHeight, i = childNodes.length; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } if (width && !wrapper.added) { this.box.appendChild(textNode); // attach it to the DOM to read offset width } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = (span.replace(/<(.|\n)*?>/g, '') || ' ') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>'); // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left attributes.x = parentX; } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', textLineHeight || renderer.fontMetrics( /px$/.test(tspan.style.fontSize) ? tspan.style.fontSize : textStyles.fontSize ).h, // Safari 6.0.2 - too optimized for its own good (#1539) // TODO: revisit this with future versions of Safari isWebKit && tspan.offsetHeight ); } // Append it textNode.appendChild(tspan); spanNo++; // check width and apply soft breaks if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 tooLong, actualWidth, rest = []; while (words.length || rest.length) { delete wrapper.bBox; // delete cache actualWidth = wrapper.getBBox().width; tooLong = actualWidth > width; if (!tooLong || words.length === 1) { // new line needed words = rest; rest = []; if (words.length) { tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: textLineHeight || 16, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } } } }); }); }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState) { var label = this.label(text, x, y, null, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, STYLE = 'style', verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState[STYLE]; delete normalState[STYLE]; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState[STYLE]; delete hoverState[STYLE]; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState[STYLE]; delete pressedState[STYLE]; // add the events addEvent(label.element, 'mouseenter', function () { label.attr(hoverState) .css(hoverStyle); }); addEvent(label.element, 'mouseleave', function () { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); }); label.setState = function (state) { curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } }; return label .on('click', function () { callback.call(label); }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }; return this.createElement('circle').attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { // arcs are defined as symbols for the ability to set // attributes in attr and animate if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } return this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect').attr({ rx: r, ry: r, fill: NONE }); return wrapper.attr( isObject(x) ? x : // do not crispify when an object is passed in (as in column charts) wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)) ); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageElement, imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc]; // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. // obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). imageElement = createElement('img', { onload: function () { centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); }, src: imageSrc }); } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; return wrapper; }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object. Prior to Highstock, an array was used to define * a linear gradient with pixel positions relative to the SVG. In newer versions * we change the coordinates to apply relative to the shape, using coordinates * 0-1 within the shape. To preserve backwards compatibility, linearGradient * in this definition is an object of x1, y1, x2 and y2. * * @param {Object} color The color or config object */ color: function (color, elem, prop) { var renderer = this, colorObject, regexRgba = /^rgba/, gradName, gradAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color && color.linearGradient) { gradName = 'linearGradient'; } else if (color && color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { gradAttr = merge(gradAttr, { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2], gradientUnits: 'userSpaceOnUse' }); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].id; } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Return the reference to the gradient object return 'url(' + renderer.url + '#' + id + ')'; // Webkit and Batik can't show rgba. } else if (regexRgba.test(color)) { colorObject = Color(color); attr(elem, prop + '-opacity', colorObject.get('a')); return colorObject.get('rgb'); } else { // Remove the opacity attribute added above. Does not throw if the attribute is not there. elem.removeAttribute(prop + '-opacity'); return color; } }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, defaultChartStyle = defaultOptions.chart.style, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper; if (useHTML && !renderer.forExport) { return renderer.html(str, x, y); } x = mathRound(pick(x, 0)); y = mathRound(pick(y, 0)); wrapper = renderer.createElement('text') .attr({ x: x, y: y, text: str }) .css({ fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } wrapper.x = x; wrapper.y = y; return wrapper; }, /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var defaultChartStyle = defaultOptions.chart.style, wrapper = this.createElement('span'), attrSetters = wrapper.attrSetters, element = wrapper.element, renderer = wrapper.renderer; // Text setter attrSetters.text = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = value; return false; }; // Various setters which rely on update transform attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); return false; }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, whiteSpace: 'nowrap', fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle; // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, { className: attr(parentGroup.element, 'class') }, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup.attrSetters, { translateX: function (value) { htmlGroupStyle.left = value + PX; }, translateY: function (value) { htmlGroupStyle.top = value + PX; }, visibility: function (value, key) { htmlGroupStyle[key] = value; } }); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize) { fontSize = pInt(fontSize || 11); // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2), baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, attrSetters = wrapper.attrSetters, needsBox; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ function updateBoxSize() { var boxX, boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && text.getBBox(); wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize).b; if (needsBox) { // create the border box if it is not already present if (!box) { boxX = mathRound(-alignFactor * padding); boxY = baseline ? -baselineOffset : 0; wrapper.box = box = shape ? renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); box.add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(merge({ width: wrapper.width, height: wrapper.height }, deferredAttr)); } deferredAttr = null; } } /** * This function runs after setting text or padding, but only if padding is changed */ function updateTextPadding() { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = paddingLeft + padding * (1 - alignFactor), y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr({ x: x, y: y }); } // record current values text.x = x; text.y = y; } /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ function boxAttr(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } } function getSizeAfterAdd() { text.add(wrapper); wrapper.attr({ text: str, // alignment is available now x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ addEvent(wrapper, 'add', getSizeAfterAdd); /* * Add specific attribute setters. */ // only change local variables attrSetters.width = function (value) { width = value; return false; }; attrSetters.height = function (value) { height = value; return false; }; attrSetters.padding = function (value) { if (defined(value) && value !== padding) { padding = value; updateTextPadding(); } return false; }; attrSetters.paddingLeft = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } return false; }; // change local variable and set attribue as well attrSetters.align = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; return false; // prevent setting text-anchor on the group }; // apply these to the box and the text alike attrSetters.text = function (value, key) { text.attr(key, value); updateBoxSize(); updateTextPadding(); return false; }; // apply these to the box but not to the text attrSetters[STROKE_WIDTH] = function (value, key) { needsBox = true; crispAdjust = value % 2 / 2; boxAttr(key, value); return false; }; attrSetters.stroke = attrSetters.fill = attrSetters.r = function (value, key) { if (key === 'fill') { needsBox = true; } boxAttr(key, value); return false; }; attrSetters.anchorX = function (value, key) { anchorX = value; boxAttr(key, value + crispAdjust - wrapperX); return false; }; attrSetters.anchorY = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); return false; }; // rename attributes attrSetters.x = function (value) { wrapper.x = value; // for animation getter value -= alignFactor * ((width || bBox.width) + padding); wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); return false; }; attrSetters.y = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); return false; }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width'], function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { removeEvent(wrapper, 'add', getSizeAfterAdd); // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = getSizeAfterAdd = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ Highcharts.VMLElement = VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; wrapper.attrSetters = {}; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks fireEvent(wrapper, 'add'); return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Get or set attributes */ attr: function (hash, val) { var wrapper = this, key, value, i, result, element = wrapper.element || {}, elemStyle = element.style, nodeName = element.nodeName, renderer = wrapper.renderer, symbolName = wrapper.symbolName, hasSetSymbolSize, shadows = wrapper.shadows, skipAttr, attrSetters = wrapper.attrSetters, ret = wrapper; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter, val is undefined if (isString(hash)) { key = hash; if (key === 'strokeWidth' || key === 'stroke-width') { ret = wrapper.strokeweight; } else { ret = wrapper[key]; } // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; // check for a specific attribute setter result = attrSetters[key] && attrSetters[key].call(wrapper, value, key); if (result !== false && value !== null) { // #620 if (result !== UNDEFINED) { value = result; // the attribute setter has returned a new value to set } // prepare paths // symbols if (symbolName && /^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(key)) { // if one of the symbol size affecting parameters are changed, // check all the others only once for each call to an element's // .attr() method if (!hasSetSymbolSize) { wrapper.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } else if (key === 'd') { value = value || []; wrapper.d = value.join(' '); // used in getter for animation // convert paths i = value.length; var convertedPath = [], clockwise; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { convertedPath[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path convertedPath[i] = 'x'; } else { convertedPath[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract 1 from the end X // position. #760, #1371. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { clockwise = value[i] === 'wa' ? 1 : -1; // #1642 if (convertedPath[i + 5] === convertedPath[i + 7]) { convertedPath[i + 7] -= clockwise; } // Start and end Y (#1410) if (convertedPath[i + 6] === convertedPath[i + 8]) { convertedPath[i + 8] -= clockwise; } } } } value = convertedPath.join(' ') || 'x'; element.path = value; // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } skipAttr = true; // handle visibility } else if (key === 'visibility') { // let the shadow follow the main element if (shadows) { i = shadows.length; while (i--) { shadows[i].style[key] = value; } } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { elemStyle[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } elemStyle[key] = value; skipAttr = true; // directly mapped to css } else if (key === 'zIndex') { if (value) { elemStyle[key] = value; } skipAttr = true; // x, y, width, height } else if (inArray(key, ['x', 'y', 'width', 'height']) !== -1) { wrapper[key] = value; // used in getter if (key === 'x' || key === 'y') { key = { x: 'left', y: 'top' }[key]; } else { value = mathMax(0, value); // don't set width or height below zero (#311) } // clipping rectangle special if (wrapper.updateClipping) { wrapper[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' wrapper.updateClipping(); } else { // normal elemStyle[key] = value; } skipAttr = true; // class name } else if (key === 'class' && nodeName === 'DIV') { // IE8 Standards mode has problems retrieving the className element.className = value; // stroke } else if (key === 'stroke') { value = renderer.color(value, element, key); key = 'strokecolor'; // stroke width } else if (key === 'stroke-width' || key === 'strokeWidth') { element.stroked = value ? true : false; key = 'strokeweight'; wrapper[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } // dashStyle } else if (key === 'dashstyle') { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; wrapper.dashstyle = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ skipAttr = true; // fill } else if (key === 'fill') { if (nodeName === 'SPAN') { // text color elemStyle.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE ? true : false; value = renderer.color(value, element, key, wrapper); key = 'fillcolor'; } // opacity: don't bother - animation is too slow and filters introduce artifacts } else if (key === 'opacity') { /*css(element, { opacity: value });*/ skipAttr = true; // rotation on VML elements } else if (nodeName === 'shape' && key === 'rotation') { wrapper[key] = value; // Correction for the 1x1 size of the shape container. Used in gauge needles. element.style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; element.style.top = mathRound(mathCos(value * deg2rad)) + PX; // translation for animation } else if (key === 'translateX' || key === 'translateY' || key === 'rotation') { wrapper[key] = value; wrapper.updateTransform(); skipAttr = true; // text for rotated and non-rotated elements } else if (key === 'text') { this.bBox = null; element.innerHTML = value; skipAttr = true; } if (!skipAttr) { if (docMode8) { // IE8 setAttribute bug element[key] = value; } else { attr(element, key, value); } } } } } return ret; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; } }; VMLElement = extendClass(SVGElement, VMLElement); /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height) { var renderer = this, boxWrapper, box; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV); box = boxWrapper.element; box.style.position = RELATIVE; // for freeform drawing using renderer directly container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // setup default css doc.createStyleSheet().cssText = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], left: isObj ? x.x : x, top: isObj ? x.y : y, width: isObj ? x.width : width, height: isObj ? x.height : height, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { member.css(clipRect.getCSS(member)); }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right addEvent(wrapper, 'add', applyRadialGradient); } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>']; createElement(this.prepVML(markup), null, null, elem); ret = colorObject.get('rgb'); } else { var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { if (isObject(x)) { r = x.r; y = x.y; x = x.x; } return this.symbol('circle').attr({ x: x - r, y: y - r, width: 2 * r, height: 2 * r }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * VML uses a shape for rect to overcome bugs and rotation problems */ rect: function (x, y, width, height, r, strokeWidth) { if (isObject(x)) { y = x.y; width = x.width; height = x.height; strokeWidth = x.strokeWidth; x = x.x; } var wrapper = this.symbol('rect'); wrapper.r = r; return wrapper.attr(wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var parentStyle = parentNode.style; css(element, { flip: 'x', left: pInt(parentStyle.width) - 1, top: pInt(parentStyle.height) - 1, rotation: -90 }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x,// - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h) { return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape * * @param {Number} left Left position * @param {Number} top Top position * @param {Number} r Border radius * @param {Object} options Width and height */ rect: function (left, top, width, height, options) { var right = left + width, bottom = top + height, ret, r; // No radius, return the more lightweight square if (!defined(options) || !options.r) { ret = SVGRenderer.prototype.symbols.square.apply(0, arguments); // Has radius add arcs for the corners } else { r = mathMin(options.r, width, height); ret = [ M, left + r, top, L, right - r, top, 'wa', right - 2 * r, top, right, top + 2 * r, right - r, top, right, top + r, L, right, bottom - r, 'wa', right - 2 * r, bottom - 2 * r, right, bottom, right, bottom - r, right - r, bottom, L, left + r, bottom, 'wa', left, bottom - 2 * r, left + 2 * r, bottom, left + r, bottom, left, bottom - r, L, left, top + r, 'wa', left, top, left + 2 * r, top + 2 * r, left, top + r, left + r, top, 'x', 'e' ]; } return ret; } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, horiz = axis.horiz, categories = axis.categories, names = axis.series[0] && axis.series[0].names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, width = (horiz && categories && !labelOptions.step && !labelOptions.staggerLines && !labelOptions.rotation && chart.plotWidth / tickPositions.length) || (!horiz && (chart.optionsMarginLeft || chart.plotWidth / 2)), // #1580 isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], css, attr, value = categories ? pick(categories[pos], names && names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; css = extend(css, labelOptions.style); // first call if (!defined(label)) { attr = { align: labelOptions.align }; if (isNumber(labelOptions.rotation)) { attr.rotation = labelOptions.rotation; } tick.label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) .attr(attr) // without position absolute, IE export sometimes is wrong .css(css) .add(axis.labelGroup) : null; // update } else if (label) { label.attr({ text: str }) .css(css); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { var label = this.label, axis = this.axis; return label ? ((this.labelBBox = label.getBBox()))[axis.horiz ? 'height' : 'width'] : 0; }, /** * Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision * detection with overflow logic. */ getLabelSides: function () { var bBox = this.labelBBox, // assume getLabelSize has run at this point axis = this.axis, options = axis.options, labelOptions = options.labels, width = bBox.width, leftSide = width * { left: 0, center: 0.5, right: 1 }[labelOptions.align] - labelOptions.x; return [-leftSide, width - leftSide]; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (index, xy) { var show = true, axis = this.axis, chart = axis.chart, isFirst = this.isFirst, isLast = this.isLast, x = xy.x, reversed = axis.reversed, tickPositions = axis.tickPositions; if (isFirst || isLast) { var sides = this.getLabelSides(), leftSide = sides[0], rightSide = sides[1], plotLeft = chart.plotLeft, plotRight = plotLeft + axis.len, neighbour = axis.ticks[tickPositions[index + (isFirst ? 1 : -1)]], neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1]; if ((isFirst && !reversed) || (isLast && reversed)) { // Is the label spilling out to the left of the plot area? if (x + leftSide < plotLeft) { // Align it to plot left x = plotLeft - leftSide; // Hide it if it now overlaps the neighbour label if (neighbour && x + rightSide > neighbourEdge) { show = false; } } } else { // Is the label spilling out to the right of the plot area? if (x + rightSide > plotRight) { // Align it to plot right x = plotRight - rightSide; // Hide it if it now overlaps the neighbour label if (neighbour && x + leftSide < neighbourEdge) { show = false; } } } // Set the modified x position of the label xy.x = x; } return show; }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines; x = x + labelOptions.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + labelOptions.y - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Vertically centered if (!defined(labelOptions.y)) { y += pInt(label.styles.lineHeight) * 0.9 - label.getBBox().height / 2; } // Correct for staggered labels if (staggerLines) { y += (index / (step || 1) % staggerLines) * 16; } return { x: x, y: y }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = options[tickPrefix + 'Width'] || 0, tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos) || (!horiz && y === axis.pos + axis.len)) ? -1 : 1, // #1480 staggerLines = axis.staggerLines; this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth, opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // apply show first and show last if ((tick.isFirst && !pick(options.showFirstLabel, 1)) || (tick.isLast && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (!staggerLines && horiz && labelOptions.overflow === 'justify' && !tick.handleOverflow(index, xy)) { show = false; } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && !isNaN(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ function PlotLineOrBand(axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } } PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function () { var plotLine = this, axis = plotLine.axis, horiz = axis.horiz, halfPointRange = (axis.pointRange || 0) / 2, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, width = options.width, to = options.to, from = options.from, isBand = defined(from) && defined(to), value = options.value, dashStyle = options.dashStyle, svgElem = plotLine.svgElem, path = [], addEvent, eventType, xs, ys, x, y, color = options.color, zIndex = options.zIndex, events = options.events, attribs, renderer = axis.chart.renderer; // logarithmic conversion if (axis.isLog) { from = log2lin(from); to = log2lin(to); value = log2lin(value); } // plot line if (width) { path = axis.getPlotLinePath(value, width); attribs = { stroke: color, 'stroke-width': width }; if (dashStyle) { attribs.dashstyle = dashStyle; } } else if (isBand) { // plot band // keep within plot area from = mathMax(from, axis.min - halfPointRange); to = mathMin(to, axis.max + halfPointRange); path = axis.getPlotBandPath(from, to, options); attribs = { fill: color }; if (options.borderWidth) { attribs.stroke = options.borderColor; attribs['stroke-width'] = options.borderWidth; } } else { return; } // zIndex if (defined(zIndex)) { attribs.zIndex = zIndex; } // common for lines and bands if (svgElem) { if (path) { svgElem.animate({ d: path }, null, svgElem.onGetPath); } else { svgElem.hide(); svgElem.onGetPath = function () { svgElem.show(); }; } } else if (path && path.length) { plotLine.svgElem = svgElem = renderer.path(path) .attr(attribs).add(); // events if (events) { addEvent = function (eventType) { svgElem.on(eventType, function (e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) { // apply defaults optionsLabel = merge({ align: horiz && isBand && 'center', x: horiz ? !isBand && 4 : 10, verticalAlign : !horiz && isBand && 'middle', y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4, rotation: horiz && !isBand && 90 }, optionsLabel); // add the SVG element if (!label) { plotLine.label = label = renderer.text( optionsLabel.text, 0, 0 ) .attr({ align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation, zIndex: zIndex }) .css(optionsLabel.style) .add(); } // get the bounding box and align the label xs = [path[1], path[4], pick(path[6], path[1])]; ys = [path[2], path[5], pick(path[7], path[2])]; x = arrayMin(xs); y = arrayMin(ys); label.align(optionsLabel, false, { x: x, y: y, width: arrayMax(xs) - x, height: arrayMax(ys) - y }); label.show(); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Remove the plot line or band */ destroy: function () { var plotLine = this, axis = plotLine.axis; // remove it from the lookup erase(axis.plotLinesAndBands, plotLine); destroyObjectProperties(plotLine, this.axis); } }; /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption, stacking) { var inverted = axis.chart.inverted; this.axis = axis; // Tells if the stack is negative this.isNegative = isNegative; // Save the options to be able to style the label this.options = options; // Save the x value to be able to position the label later this.x = x; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; this.percent = stacking === 'percent'; // The align options and text align varies on whether the stack is negative and // if the chart is inverted or not. // First test the user supplied value, then use the dynamic. this.alignOptions = { align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'), verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')), y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)), x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0) }; this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center'); } StackItem.prototype = { destroy: function () { destroyObjectProperties(this, this.axis); }, /** * Sets the total of this stack. Should be called when a serie is hidden or shown * since that will affect the total of other stacks. */ setTotal: function (total) { this.total = total; this.cum = total; }, /** * Renders the stack total label and adds it to the stack label group. */ render: function (group) { var options = this.options, str = options.formatter.call(this); // format the text in the label // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden if (this.label) { this.label.attr({text: str, visibility: HIDDEN}); // Create new label } else { this.label = this.axis.chart.renderer.text(str, 0, 0, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries .css(options.style) // apply style .attr({ align: this.textAlign, // fix the text-anchor rotation: options.rotation, // rotation visibility: HIDDEN // hidden until setOffset is called }) .add(group); // add to the labels-group } }, /** * Sets the offset that the stack has from the x value and repositions the label. */ setOffset: function (xOffset, xWidth) { var stackItem = this, axis = stackItem.axis, chart = axis.chart, inverted = chart.inverted, neg = this.isNegative, // special treatment is needed for negative stacks y = axis.translate(this.percent ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates yZero = axis.translate(0), // stack origin h = mathAbs(y - yZero), // stack height x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position plotHeight = chart.plotHeight, stackBox = { // this is the box for the complete stack x: inverted ? (neg ? y : y - h) : x, y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y), width: inverted ? h : xWidth, height: inverted ? xWidth : h }, label = this.label, alignAttr; if (label) { label.align(this.alignOptions, null, stackBox); // align the label to the box // Set visibility (#678) alignAttr = label.alignAttr; label.attr({ visibility: this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN }); } } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ function Axis() { this.init.apply(this, arguments); } Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#C0C0C0', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: defaultLabelOptions, // { step: null }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 5, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#4d759e', //font: defaultFont.replace('normal', 'bold') fontWeight: 'bold' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { align: 'right', x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return this.total; }, style: defaultLabelOptions.style } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { align: 'right', x: -8, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { align: 'left', x: 8, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { align: 'center', x: 0, y: 14 // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for left axes */ defaultTopAxisOptions: { labels: { align: 'center', x: 0, y: -5 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.xOrY = isXAxis ? 'x' : 'y'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.staggerLines = axis.horiz && options.labels.staggerLines; axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series //axis.ignoreMaxPadding = UNDEFINED; axis.chart = chart; axis.reversed = options.reversed; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.categories = options.categories || type === 'category'; // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Flag if percentage mode //axis.usePercentage = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0; // Major ticks axis.ticks = {}; // Minor ticks axis.minorTicks = {}; //axis.tickAmount = UNDEFINED; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis._stacksTouched = 0; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() chart.axes.push(axis); chart[isXAxis ? 'xAxis' : 'yAxis'].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.isXAxis ? 'xAxis' : 'yAxis'], // if set in setOptions (#1053) userOptions ) ); }, /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.xOrY + 'Axis'][this.options.index] = merge(this.userOptions, newOptions); this.destroy(); this._addedPlotLB = false; // #1611 this.init(chart, newOptions); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.xOrY + 'Axis'; // xAxis or yAxis // Remove associated series each(this.series, function (series) { series.remove(false); }); // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && numericSymbols[i] !== null) { ret = numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (value >= 1000) { // add thousands separators ret = numberFormat(value, 0); } else { // small numbers ret = numberFormat(value, -1); } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart, stacks = axis.stacks, posStack = [], negStack = [], stacksTouched = axis._stacksTouched = axis._stacksTouched + 1, type, i; axis.hasVisibleSeries = false; // reset dataMin and dataMax in case we're redrawing axis.dataMin = axis.dataMax = null; // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, stacking, posPointStack, negPointStack, stackKey, stackOption, negKey, xData, yData, x, y, threshold = seriesOptions.threshold, yDataLength, activeYData = [], seriesDataMin, seriesDataMax, activeCounter = 0; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = seriesOptions.threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { var isNegative, pointStack, key, cropped = series.cropped, xExtremes = series.xAxis.getExtremes(), //findPointRange, //pointRange, j, hasModifyValue = !!series.modifyValue; // Handle stacking stacking = seriesOptions.stacking; axis.usePercentage = stacking === 'percent'; // create a stack for this particular series type if (stacking) { stackOption = seriesOptions.stack; stackKey = series.type + pick(stackOption, ''); negKey = '-' + stackKey; series.stackKey = stackKey; // used in translate posPointStack = posStack[stackKey] || []; // contains the total values for each x posStack[stackKey] = posPointStack; negPointStack = negStack[negKey] || []; negStack[negKey] = negPointStack; } if (axis.usePercentage) { axis.dataMin = 0; axis.dataMax = 99; } // processData can alter series.pointRange, so this goes after //findPointRange = series.pointRange === null; xData = series.processedXData; yData = series.processedYData; yDataLength = yData.length; // loop over the non-null y values and read them into a local array for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // Read stacked values into a stack based on the x value, // the sign of y and the stack key. Stacking is also handled for null values (#739) if (stacking) { isNegative = y < threshold; pointStack = isNegative ? negPointStack : posPointStack; key = isNegative ? negKey : stackKey; // Set the stack value and y for extremes if (defined(pointStack[x])) { // we're adding to the stack pointStack[x] = correctFloat(pointStack[x] + y); y = [y, pointStack[x]]; // consider both the actual value and the stack (#1376) } else { // it's the first point in the stack pointStack[x] = y; } // add the series if (!stacks[key]) { stacks[key] = {}; } // If the StackItem is there, just update the values, // if not, create one first if (!stacks[key][x]) { stacks[key][x] = new StackItem(axis, axis.options.stackLabels, isNegative, x, stackOption, stacking); } stacks[key][x].setTotal(pointStack[x]); stacks[key][x].touched = stacksTouched; } // Handle non null values if (y !== null && y !== UNDEFINED && (!axis.isLog || (y.length || y > 0))) { // general hook, used for Highstock compare values feature if (hasModifyValue) { y = series.modifyValue(y); } // For points within the visible range, including the first point outside the // visible range, consider y extremes if (series.getExtremesFromAll || cropped || ((xData[i + 1] || x) >= xExtremes.min && (xData[i - 1] || x) <= xExtremes.max)) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } } // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If the length of activeYData is 0, continue with null values. if (!axis.usePercentage && activeYData.length) { series.dataMin = seriesDataMin = arrayMin(activeYData); series.dataMax = seriesDataMax = arrayMax(activeYData); axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { if (axis.dataMin >= threshold) { axis.dataMin = threshold; axis.ignoreMinPadding = true; } else if (axis.dataMax < threshold) { axis.dataMax = threshold; axis.ignoreMaxPadding = true; } } } } }); // Destroy unused stacks (#1044) for (type in stacks) { for (i in stacks[type]) { if (stacks[type][i].touched < stacksTouched) { stacks[type][i].destroy(); delete stacks[type][i]; } } } }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacementBetween) { var axis = this, axisLength = axis.len, sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axisLength; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * axisLength; } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (postTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (postTranslate) { // log and ordinal axes val = axis.val2lin(val); } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (pointPlacementBetween ? localA * axis.pointRange / 2 : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, translatedValue = axis.translate(value, null, null, old), cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB; x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; if (x1 < axisLeft || x1 > axisLeft + axis.width) { skip = true; } } else { x1 = axisLeft; x2 = cWidth - axis.right; if (y1 < axisTop || y1 > axisTop + axis.height) { skip = true; } } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 0); }, /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to), path = this.getPlotLinePath(from); if (path && toPath) { path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Set the tick positions of a logarithmic axis */ getLogTickPositions: function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max)) { // #1670 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, math.pow(10, mathFloor(math.log(interval) / math.LN10)) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, len; if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( getTimeTicks( normalizeTimeTickInterval(minorTickInterval), axis.min, axis.max, options.startOfWeek ) ); if (minorTickPositions[0] < axis.min) { minorTickPositions.shift(); } } else { for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) { minorTickPositions.push(pos); } } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { var minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, transA = axis.transA; // adjust translation for padding if (axis.isXAxis) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = series.pointRange, pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; if (seriesPointRange > range) { // #1446 seriesPointRange = 0; } pointRange = mathMax(pointRange, seriesPointRange); // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, pointPlacement ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); // Set the closestPointRange if (!series.noSharedTooltip && defined(seriesClosestPointRange)) { closestPointRange = defined(closestPointRange) ? mathMin(closestPointRange, seriesClosestPointRange) : seriesClosestPointRange; } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope ? axis.ordinalSlope / closestPointRange : 1; // #988 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = mathMin(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value axis.closestPointRange = closestPointRange; } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickPositions: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, tickPositioner = axis.options.tickPositioner, magnitude, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickIntervalOption = options.minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, tickPositions, categories = axis.categories; // linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[isXAxis ? 'xAxis' : 'yAxis'][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } } else { // initial min and max from the extreme data values axis.min = pick(axis.userMin, options.min, axis.dataMin); axis.max = pick(axis.userMax, options.max, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934 axis.max = correctFloat(log2lin(axis.max)); } // handle zoomed range if (axis.range) { axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618 axis.userMax = axis.max; if (secondPass) { axis.range = null; // don't use it when running setExtremes } } // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) { axis.min -= length * minPadding; } if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) { axis.max += length * maxPadding; } } } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : (axis.max - axis.min) * tickPixelIntervalOption / (axis.len || 1) ); } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) { axis.tickInterval = minTickIntervalOption; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog) { // linear magnitude = math.pow(10, mathFloor(math.log(axis.tickInterval) / math.LN10)); if (!tickIntervalOption) { axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, magnitude, options); } } // get minorTickInterval axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ? axis.tickInterval / 5 : options.minorTickInterval; // find the tick positions axis.tickPositions = tickPositions = options.tickPositions ? [].concat(options.tickPositions) : // Work on a copy (#1565) (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max])); if (!tickPositions) { if (isDatetimeAxis) { tickPositions = (axis.getNonLinearTimeTicks || getTimeTicks)( normalizeTimeTickInterval(axis.tickInterval, options.units), axis.min, axis.max, options.startOfWeek, axis.ordinalPositions, axis.closestPointRange, true ); } else if (isLog) { tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max); } else { tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max); } axis.tickPositions = tickPositions; } if (!isLinked) { // reset min/max or remove extremes based on start/end on tick var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = axis.minPointOffset || 0, singlePad; if (options.startOnTick) { axis.min = roundedMin; } else if (axis.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (options.endOnTick) { axis.max = roundedMax; } else if (axis.max + minPointOffset < roundedMax) { tickPositions.pop(); } // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (tickPositions.length === 1) { singlePad = 0.001; // The lowest possible number to avoid extra padding on columns axis.min -= singlePad; axis.max += singlePad; } } }, /** * Set the max ticks of either the x and y axis collection */ setMaxTicks: function () { var chart = this.chart, maxTicks = chart.maxTicks || {}, tickPositions = this.tickPositions, key = this._maxTicksKey = [this.xOrY, this.pos, this.len].join('-'); if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) { maxTicks[key] = tickPositions.length; } chart.maxTicks = maxTicks; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var axis = this, chart = axis.chart, key = axis._maxTicksKey, tickPositions = axis.tickPositions, maxTicks = chart.maxTicks; if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false) { // only apply to linear scale var oldTickAmount = axis.tickAmount, calculatedTickAmount = tickPositions.length, tickAmount; // set the axis-level tickAmount to use below axis.tickAmount = tickAmount = maxTicks[key]; if (calculatedTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + axis.tickInterval )); } axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1); axis.max = tickPositions[tickPositions.length - 1]; } if (defined(oldTickAmount) && tickAmount !== oldTickAmount) { axis.isDirty = true; } } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, stacks = axis.stacks, type, i, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) { axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickPositions(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } // reset stacks if (!axis.isXAxis) { for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } // Set the maximum tick amount axis.setMaxTicks(); }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; // Mark for running afterSetExtremes axis.isDirtyExtremes = true; // redraw if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { // Prevent pinch zooming out of range if (!this.allowZoomOutside) { if (newMin <= this.dataMin) { newMin = UNDEFINED; } if (newMax >= this.dataMax) { newMax = UNDEFINED; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width, height, top, left; // Expose basic values to use in Series object and navigator this.left = left = pick(options.left, chart.plotLeft + offsetLeft); this.top = top = pick(options.top, chart.plotTop); this.width = width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight); this.height = height = pick(options.height, chart.plotHeight); this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog; var realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; if (realMin > threshold || threshold === null) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, addPlotBand: function (options) { this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { this.addPlotBandOrLine(options, 'plotLines'); }, /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ addPlotBandOrLine: function (options, coll) { var obj = new PlotLineOrBand(this, options).render(), userOptions = this.userOptions; // Add it to the user options for exporting and Axis.update if (coll) { userOptions[coll] = userOptions[coll] || []; userOptions[coll].push(options); } this.plotLinesAndBands.push(obj); return obj; }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, directionFactor = [-1, 1, 1, -1][side], n; // For reuse in Axis.render axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions)); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .add(); } if (hasData || axis.isLinked) { each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); each(tickPositions, function (pos) { // left side must be align: right and right side must have align: left for labels if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === labelOptions.align) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (axis.staggerLines) { labelOffset += (axis.staggerLines - 1) * 16; } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align] }) .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10); titleOffsetOption = axisTitleOptions.offset; } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.axisTitleMargin = pick(titleOffsetOption, labelOffset + titleMargin + (side !== 2 && labelOffset && directionFactor * options.labels[horiz ? 'y' : 'x']) ); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset ); clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], options.lineWidth); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; this.lineTop = lineTop; // used by flag series if (!opposite) { lineWidth *= -1; // crispify the other way - #1480 } return chart.renderer.crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis : offAxis + (opposite ? this.width : 0) + offset + (axisTitleOptions.x || 0), // x y: horiz ? offAxis - (opposite ? this.height : 0) + offset : alongAxis + (axisTitleOptions.y || 0) // y }; }, /** * Render the axis */ render: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, axisTitle = axis.axisTitle, stacks = axis.stacks, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), hasData = axis.hasData, showAxis = axis.showAxis, from, to; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (hasData || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 each(tickPositions.slice(1).concat([tickPositions[0]]), function (pos, i) { // Reorganize the indices i = (i === tickPositions.length - 1) ? 0 : i + 1; // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true); } ticks[pos].render(i, false, 1); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && axis.min === 0) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { if (i % 2 === 0 && pos < axis.max) { if (!alternateBands[pos]) { alternateBands[pos] = new PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max; alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = globalAnimation ? globalAnimation.duration || 500 : 0, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them if (coll === alternateBands || !chart.hasRendered || !delay) { destroyInactiveItems(); } else if (delay) { setTimeout(destroyInactiveItems, delay); } }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { var stackKey, oneStack, stackCategory, stackTotalGroup = axis.stackTotalGroup; // Create a separate group for the stack total labels if (!stackTotalGroup) { axis.stackTotalGroup = stackTotalGroup = renderer.g('stack-labels') .attr({ visibility: VISIBLE, zIndex: 6 }) .add(); } // plotLeft/Top will change when y axis gets wider so we need to translate the // stackTotalGroup at every render call. See bug #506 and #516 stackTotalGroup.translate(chart.plotLeft, chart.plotTop); // Render each stack total for (stackKey in stacks) { oneStack = stacks[stackKey]; for (stackCategory in oneStack) { oneStack[stackCategory].render(stackTotalGroup); } } } // End stacked totals axis.isDirty = false; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function (id) { var plotLinesAndBands = this.plotLinesAndBands, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { var axis = this, chart = axis.chart, pointer = chart.pointer; // hide tooltip and hover states if (pointer.reset) { pointer.reset(true); } // render the axis axis.render(); // move plot lines and bands each(axis.plotLinesAndBands, function (plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(axis.series, function (series) { series.isDirty = true; }); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); }, /** * Destroys an Axis instance. */ destroy: function () { var axis = this, stacks = axis.stacks, stackKey; // Remove the events removeEvent(axis); // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands, axis.plotLinesAndBands], function (coll) { destroyObjectProperties(coll); }); // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisGroup', 'gridGroup', 'labelGroup', 'axisTitle'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); } }; // end Axis /** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ function Tooltip() { this.init.apply(this, arguments); } Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape, null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .hide() .add(); // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { each(this.crosshairs, function (crosshair) { if (crosshair) { crosshair.destroy(); } }); // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden; // get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: animate ? (now.anchorY + anchorY) / 2 : anchorY }); // move to the intermediate value tooltip.label.attr(now); // run on next tick of the mouse tracker if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) { // never allow two timeouts clearTimeout(this.tooltipTimeout); // set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function () { var tooltip = this, hoverPoints; if (!this.isHidden) { hoverPoints = this.chart.hoverPoints; this.hideTimer = setTimeout(function () { tooltip.label.fadeOut(); tooltip.isHidden = true; }, pick(this.options.hideDelay, 500)); // hide previous hoverPoints and set new if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } this.chart.hoverPoints = null; } }, /** * Hide the crosshairs */ hideCrosshairs: function () { each(this.crosshairs, function (crosshair) { if (crosshair) { crosshair.hide(); } }); }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotX = 0, plotY = 0, yAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; plotX += point.plotX; plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { // Set up the variables var chart = this.chart, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, distance = pick(this.options.distance, 12), pointX = point.plotX, pointY = point.plotY, x = pointX + plotLeft + (chart.inverted ? distance : -boxWidth - distance), y = pointY - boxHeight + plotTop + 15, // 15 means the point is 15 pixels up from the bottom of the tooltip alignedRight; // It is too far to the left, adjust it if (x < 7) { x = plotLeft + mathMax(pointX, 0) + distance; } // Test to see if the tooltip is too far to the right, // if it is, move it back to be inside and then up to not cover the point. if ((x + boxWidth) > (plotLeft + plotWidth)) { x -= (x + boxWidth) - (plotLeft + plotWidth); y = pointY - boxHeight + plotTop - distance; alignedRight = true; } // If it is now above the plot area, align it to the top of the plot area if (y < plotTop + 5) { y = plotTop + 5; // If the tooltip is still covering the point, move it below instead if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) { y = pointY + plotTop + distance; // below } } // Now if the tooltip is below the chart, move it up. It's better to cover the // point than to disappear outside the chart. #834. if (y + boxHeight > plotTop + plotHeight) { y = mathMax(plotTop, plotTop + plotHeight - boxHeight - distance); // below } return {x: x, y: y}; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), series = items[0].series, s; // build the header s = [series.tooltipHeaderFormatter(items[0])]; // build the values each(items, function (item) { series = item.series; s.push((series.tooltipFormatter && series.tooltipFormatter(item)) || item.point.tooltipFormatter(series.tooltipOptions.pointFormat)); }); // footer s.push(tooltip.options.footerFormat || ''); return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, show, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, crosshairsOptions = options.crosshairs, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; // For line type series, hide tooltip if the point falls outside the plot show = shared || !currentSeries.isCartesian || currentSeries.tooltipOutsidePlot || chart.isInsidePlot(x, y); // update the inner HTML if (text === false || !show) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr('opacity', 1).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y }); this.isHidden = false; } // crosshairs if (crosshairsOptions) { crosshairsOptions = splat(crosshairsOptions); // [x, y] var path, i = crosshairsOptions.length, attribs, axis, val; while (i--) { axis = point.series[i ? 'yAxis' : 'xAxis']; if (crosshairsOptions[i] && axis) { val = i ? pick(point.stackY, point.y) : point.x; // #814 if (axis.isLog) { // #1671 val = log2lin(val); } path = axis.getPlotLinePath( val, 1 ); if (tooltip.crosshairs[i]) { tooltip.crosshairs[i].attr({ d: path, visibility: VISIBLE }); } else { attribs = { 'stroke-width': crosshairsOptions[i].width || 1, stroke: crosshairsOptions[i].color || '#C0C0C0', zIndex: crosshairsOptions[i].zIndex || 2 }; if (crosshairsOptions[i].dashStyle) { attribs.dashstyle = crosshairsOptions[i].dashStyle; } tooltip.crosshairs[i] = chart.renderer.path(path) .attr(attribs) .add(); } } } } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y), point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); } }; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ function Pointer(chart, options) { this.init(chart, options); } Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var zoomType = useCanVG ? '' : options.chart.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); this.pinchDown = []; this.lastValidTouch = {}; if (options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e) { var chartPosition, chartX, chartY, ePos; // common IE normalizing e = e || win.event; if (!e.target) { e.target = e.srcElement; } // Framework specific normalizing (#1165) e = washMouseEvent(e); // iOS ePos = e.touches ? e.touches.item(0) : e; // get mouse position this.chartPosition = chartPosition = offset(this.chart.container); // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = e.x; chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * Return the index in the tooltipPoints array, corresponding to pixel position in * the plot area. */ getIndex: function (e) { var chart = this.chart; return chart.inverted ? chart.plotHeight + chart.plotTop - e.chartY : e.chartX - chart.plotLeft; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, point, points, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, j, distance = chart.chartWidth, index = pointer.getIndex(e), anchor; // shared tooltip if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) { points = []; // loop over all series and find the ones with points closest to the mouse i = series.length; for (j = 0; j < i; j++) { if (series[j].visible && series[j].options.enableMouseTracking !== false && !series[j].noSharedTooltip && series[j].tooltipPoints.length) { point = series[j].tooltipPoints[index]; if (point.series) { // not a dummy point, #1544 point._dist = mathAbs(index - point.clientX); distance = mathMin(distance, point._dist); points.push(point); } } } // remove furthest points i = points.length; while (i--) { if (points[i]._dist > distance) { points.splice(i, 1); } } // refresh the tooltip if necessary if (points.length && (points[0].clientX !== pointer.hoverX)) { tooltip.refresh(points, e); pointer.hoverX = points[0].clientX; } } // separate tooltip and general mouse events if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker // get the point point = hoverSeries.tooltipPoints[index]; // a new point is hovered, refresh the tooltip if (point && point !== hoverPoint) { // trigger the events point.onMouseOver(e); } } else if (tooltip && tooltip.followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(); tooltip.hideCrosshairs(); } pointer.hoverX = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart; // Scale each series each(chart.series, function (series) { if (series.xAxis.zoomEnabled) { series.group.attr(attribs); if (series.markerGroup) { series.markerGroup.attr(attribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(attribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { // TODO: implement clipping for inverted charts clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, followTouchMove = chart.tooltip.options.followTouchMove, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, zoomHor = self.zoomHor || self.pinchHor, zoomVert = self.zoomVert || self.pinchVert, hasZoom = zoomHor || zoomVert, selectionMarker = self.selectionMarker, transform = {}, clip = {}; // On touch devices, only proceed to trigger click if a handler is defined if (e.type === 'touchstart' && followTouchMove) { if (self.inClass(e.target, PREFIX + 'tracker')) { if (!chart.runTrackerClick || touchesLength > 1) { e.preventDefault(); } } else if (!chart.runChartClick || touchesLength > 1) { e.preventDefault(); } } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(axis.dataMin), max = axis.toPixels(axis.dataMax), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop }, chart.plotBox); } if (zoomHor) { self.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (zoomVert) { self.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } } }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY; // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside) { if (!this.selectionMarker) { this.selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (this.selectionMarker && zoomHor) { size = chartX - mouseDownX; this.selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (this.selectionMarker && zoomVert) { size = chartY - mouseDownY; this.selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !this.selectionMarker && chartOptions.panning) { chart.pan(chartX); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.x, selectionTop = selectionBox.y, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled) { var horiz = axis.horiz, minPixelPadding = axis.minPixelPadding, selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding), selectionMax = axis.toValue((horiz ? selectionLeft + selectionBox.width : selectionTop + selectionBox.height) - minPixelPadding); if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859 selectionData[axis.xOrY + 'Axis'].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes, max: mathMax(selectionMin, selectionMax) }); runZoom = true; } } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups({ translateX: chart.plotLeft, translateY: chart.plotTop, scaleX: 1, scaleY: 1 }); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { this.drop(e); }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition, hoverSeries = chart.hoverSeries; // Get e.pageX and e.pageY back in MooTools e = washMouseEvent(e); // If we're outside, hide the tooltip if (chartPosition && hoverSeries && hoverSeries.isCartesian && !chart.isInsidePlot(e.pageX - chartPosition.left - chart.plotLeft, e.pageY - chartPosition.top - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { this.reset(); this.chartPosition = null; // also reset the chart position, used in #149 fix }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; // normalize e = this.normalize(e); // #295 e.returnValue = false; if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries; if (series && !series.options.stickyTracking && !this.inClass(e.toElement || e.relatedTarget, PREFIX + 'tooltip')) { series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop, inverted = chart.inverted, chartPosition, plotX, plotY; e = this.normalize(e); e.cancelBubble = true; // IE specific if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { chartPosition = this.chartPosition; plotX = hoverPoint.plotX; plotY = hoverPoint.plotY; // add page position info extend(hoverPoint, { pageX: chartPosition.left + plotLeft + (inverted ? chart.plotWidth - plotY : plotX), pageY: chartPosition.top + plotTop + (inverted ? chart.plotHeight - plotX : plotY) }); // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event hoverPoint.firePointEvent('click', e); // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, onContainerTouchStart: function (e) { var chart = this.chart; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { // Prevent the click pseudo event from firing unless it is set in the options /*if (!chart.runChartClick) { e.preventDefault(); }*/ // Run mouse events and display tooltip etc this.runPointActions(e); this.pinch(e); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchMove: function (e) { if (e.touches.length === 1 || e.touches.length === 2) { this.pinch(e); } }, onDocumentTouchEnd: function (e) { this.drop(e); }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container, events; this._events = events = [ [container, 'onmousedown', 'onContainerMouseDown'], [container, 'onmousemove', 'onContainerMouseMove'], [container, 'onclick', 'onContainerClick'], [container, 'mouseleave', 'onContainerMouseLeave'], [doc, 'mousemove', 'onDocumentMouseMove'], [doc, 'mouseup', 'onDocumentMouseUp'] ]; if (hasTouch) { events.push( [container, 'ontouchstart', 'onContainerTouchStart'], [container, 'ontouchmove', 'onContainerTouchMove'], [doc, 'touchend', 'onDocumentTouchEnd'] ); } each(events, function (eventConfig) { // First, create the callback function that in turn calls the method on Pointer pointer['_' + eventConfig[2]] = function (e) { pointer[eventConfig[2]](e); }; // Now attach the function, either as a direct property or through addEvent if (eventConfig[1].indexOf('on') === 0) { eventConfig[0][eventConfig[1]] = pointer['_' + eventConfig[2]]; } else { addEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]); } }); }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var pointer = this; // Release all DOM events each(pointer._events, function (eventConfig) { if (eventConfig[1].indexOf('on') === 0) { eventConfig[0][eventConfig[1]] = null; // delete breaks oldIE } else { removeEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]); } }); delete pointer._events; // memory and CPU leak clearInterval(pointer.tooltipTimeout); } }; /** * The overview of the chart's series */ function Legend(chart, options) { this.init(chart, options); } Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding = pick(options.padding, 8), itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding; legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.lastLineHeight = 0; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? item.color : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { stroke: symbolColor, fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions) { markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox; if (item.legendGroup) { item.legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = (translateY + checkbox.y + (scrollOffset || 0) + 3); css(checkbox, { left: (alignAttr.translateX + item.legendItemWidth + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } titleHeight = this.title.getBBox().height; this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = options.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series || item, itemOptions = series.options, showCheckbox = itemOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item), ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? li : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); li.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { li.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { item.setVisible(); }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (itemOptions && showCheckbox) { item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, options.itemCheckboxStyle, chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item, 'checkboxClick', { checked: target.checked }, function () { item.select(); } ); }); } } // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.legendItemWidth = options.itemWidth || symbolWidth + symbolPadding + bBox.width + padding + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = bBox.height; // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( horizontal ? legend.itemX - initialItemX : itemWidth, legend.offsetWidth ); }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); legend.clipRect = renderer.clipRect(0, 0, 9999, chart.chartHeight); legend.contentGroup.clip(legend.clipRect); } legend.renderTitle(); // add each series or point allItems = []; each(chart.series, function (serie) { var seriesOptions = serie.options; if (!seriesOptions.showInLegend || defined(seriesOptions.linkedTo)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( serie.legendItems || (seriesOptions.legendType === 'point' ? serie.data : serie) ); }); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items each(allItems, function (item) { legend.renderItem(item); }); // Draw the border legendWidth = options.width || legend.offsetWidth; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); if (legendBorderWidth || legendBackgroundColor) { legendWidth += padding; legendHeight += padding; if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp(null, null, null, legendWidth, legendHeight) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, pageCount, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle if (legendHeight > spaceHeight && !options.useHTML) { this.clipHeight = clipHeight = spaceHeight - 20 - this.titleHeight; this.pageCount = pageCount = mathCeil(legendHeight / clipHeight); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; clipRect.attr({ height: clipHeight }); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipRect.attr({ height: chart.chartHeight }); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pageCount = this.pageCount, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + this.pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -mathMin(clipHeight * (currentPage - 1), this.fullHeight - clipHeight + padding) + 1; this.scrollGroup.animate({ translateY: scrollOffset }); pager.attr({ text: currentPage + '/' + pageCount }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ function Chart() { this.init.apply(this, arguments); } Chart.prototype = { /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data var optionsChart = options.chart, optionsMargin = optionsChart.margin, margin = isObject(optionsMargin) ? optionsMargin : [optionsMargin, optionsMargin, optionsMargin, optionsMargin]; this.optionsMarginTop = pick(optionsChart.marginTop, margin[0]); this.optionsMarginRight = pick(optionsChart.marginRight, margin[1]); this.optionsMarginBottom = pick(optionsChart.marginBottom, margin[2]); this.optionsMarginLeft = pick(optionsChart.marginLeft, margin[3]); var chartEvents = optionsChart.events; this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = 0; chart.counters = new ChartCounters(); chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, axis; /*jslint unused: false*/ axis = new Axis(this, merge(options, { index: this[key].length })); /*jslint unused: true*/ // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(options); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Adjust all axes tick amounts */ adjustTickAmounts: function () { if (this.options.chart.alignTicks !== false) { each(this.axes, function (axis) { axis.adjustTickAmount(); }); } this.maxTicks = null; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed? seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // link stacked series while (i--) { serie = series[i]; if (serie.isDirty && serie.options.stacking) { hasStackedSeries = true; break; } } if (hasStackedSeries) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // handle updated data in the series each(series, function (serie) { if (serie.isDirty) { // prepare the data so axis can read it if (serie.options.legendType === 'point') { redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } if (chart.hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } chart.adjustTickAmounts(); chart.getMargins(); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set if (axis.isDirtyExtremes) { // #821 axis.isDirtyExtremes = false; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', axis.getExtremes()); // #747, #751 }); } if (axis.isDirty || isDirtyBox || hasStackedSeries) { axis.redraw(); isDirtyBox = true; // #792 } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer && pointer.reset) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv; var loadingOptions = options.loading; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '', left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray, axis; // make sure the options are arrays and add some members each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { axis = new Axis(chart, axisOptions); }); chart.adjustTickAmounts(); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (chartX) { var chart = this, xAxis = chart.xAxis[0], mouseDownX = chart.mouseDownX, halfPointRange = xAxis.pointRange / 2, extremes = xAxis.getExtremes(), newMin = xAxis.translate(mouseDownX - chartX, true) + halfPointRange, newMax = xAxis.translate(mouseDownX + chart.plotWidth - chartX, true) - halfPointRange, hoverPoints = chart.hoverPoints; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (xAxis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) { xAxis.setExtremes(newMin, newMax, true, false, { trigger: 'pan' }); } chart.mouseDownX = chartX; // set new reference for next run css(chart.container, { cursor: 'move' }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add() .align(chartTitleOptions, false, 'spacingBox'); } }); }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) chart.containerWidth = adapterRun(renderTo, 'width'); chart.containerHeight = adapterRun(renderTo, 'height'); chart.chartWidth = mathMax(0, optionsChart.width || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(optionsChart.height, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, optionsChart = chart.options.chart, chartWidth, chartHeight, renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, containerId; chart.renderTo = renderTo = optionsChart.renderTo; containerId = PREFIX + idCounter++; if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex]) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly if (!renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0 // #1072 }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; chart.renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, true) : new Renderer(container, chartWidth, chartHeight); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function () { var chart = this, optionsChart = chart.options.chart, spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft, axisOffset, legend = chart.legend, optionsMarginTop = chart.optionsMarginTop, optionsMarginLeft = chart.optionsMarginLeft, optionsMarginRight = chart.optionsMarginRight, optionsMarginBottom = chart.optionsMarginBottom, chartTitleOptions = chart.options.title, chartSubtitleOptions = chart.options.subtitle, legendOptions = chart.options.legend, legendMargin = pick(legendOptions.margin, 10), legendX = legendOptions.x, legendY = legendOptions.y, align = legendOptions.align, verticalAlign = legendOptions.verticalAlign, titleOffset; chart.resetMargins(); axisOffset = chart.axisOffset; // adjust for title and subtitle if ((chart.title || chart.subtitle) && !defined(chart.optionsMarginTop)) { titleOffset = mathMax( (chart.title && !chartTitleOptions.floating && !chartTitleOptions.verticalAlign && chartTitleOptions.y) || 0, (chart.subtitle && !chartSubtitleOptions.floating && !chartSubtitleOptions.verticalAlign && chartSubtitleOptions.y) || 0 ); if (titleOffset) { chart.plotTop = mathMax(chart.plotTop, titleOffset + pick(chartTitleOptions.margin, 15) + spacingTop); } } // adjust for legend if (legend.display && !legendOptions.floating) { if (align === 'right') { // horizontal alignment handled first if (!defined(optionsMarginRight)) { chart.marginRight = mathMax( chart.marginRight, legend.legendWidth - legendX + legendMargin + spacingRight ); } } else if (align === 'left') { if (!defined(optionsMarginLeft)) { chart.plotLeft = mathMax( chart.plotLeft, legend.legendWidth + legendX + legendMargin + spacingLeft ); } } else if (verticalAlign === 'top') { if (!defined(optionsMarginTop)) { chart.plotTop = mathMax( chart.plotTop, legend.legendHeight + legendY + legendMargin + spacingTop ); } } else if (verticalAlign === 'bottom') { if (!defined(optionsMarginBottom)) { chart.marginBottom = mathMax( chart.marginBottom, legend.legendHeight - legendY + legendMargin + spacingBottom ); } } } // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { axis.getOffset(); }); } if (!defined(optionsMarginLeft)) { chart.plotLeft += axisOffset[3]; } if (!defined(optionsMarginTop)) { chart.plotTop += axisOffset[0]; } if (!defined(optionsMarginBottom)) { chart.marginBottom += axisOffset[2]; } if (!defined(optionsMarginRight)) { chart.marginRight += axisOffset[1]; } chart.setChartSize(); }, /** * Add the event handlers necessary for auto resizing * */ initReflow: function () { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, reflowTimeout; function reflow(e) { var width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win; // #805 - MooTools doesn't supply e // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && width && height && (target === win || target === doc)) { if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(reflowTimeout); chart.reflowTimeout = reflowTimeout = setTimeout(function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }, 100); } chart.containerWidth = width; chart.containerHeight = height; } } addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, fireEndResize; // Handle the isResizing counter chart.isResizing += 1; fireEndResize = function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (defined(width)) { chart.chartWidth = chartWidth = mathMax(0, mathRound(width)); chart.hasUserSize = !!chartWidth; } if (defined(height)) { chart.chartHeight = chartHeight = mathMax(0, mathRound(height)); } css(chart.container, { width: chartWidth + PX, height: chartHeight + PX }); chart.setChartSize(true); chart.renderer.setSize(chartWidth, chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // fire endResize and set isResizing back // If animation is disabled, fire without delay if (globalAnimation === false) { fireEndResize(); } else { // else set a timeout with the animation duration setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500); } }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function (skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacingLeft, y: spacingTop, width: chartWidth - spacingLeft - spacingRight, height: chartHeight - spacingTop - spacingBottom }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2); clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this, optionsChart = chart.options.chart, spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft; chart.plotTop = pick(chart.optionsMarginTop, spacingTop); chart.marginRight = pick(chart.optionsMarginRight, spacingRight); chart.marginBottom = pick(chart.optionsMarginBottom, spacingBottom); chart.plotLeft = pick(chart.optionsMarginLeft, spacingLeft); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp(null, null, null, chartWidth - mgn, chartHeight - mgn) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp(null, plotLeft, plotTop, plotWidth, plotHeight) ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options; var labels = options.labels, credits = options.credits, creditsHref; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); // Get margins by pre-rendering axes // set axes scales each(axes, function (axis) { axis.setScale(); }); chart.getMargins(); chart.maxTicks = null; // reset for second pass each(axes, function (axis) { axis.setTickPositions(true); // update to reflect the new margins axis.setMaxTicks(); }); chart.adjustTickAmounts(); chart.getMargins(); // second pass to check for new labels // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { axis.render(); }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } each(chart.series, function (serie) { serie.translate(); serie.setTooltipPoints(); serie.render(); }); // Labels if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } // Credits if (credits.enabled && !chart.credits) { creditsHref = credits.href; chart.credits = renderer.text( credits.text, 0, 0 ) .on('click', function () { if (creditsHref) { location.href = creditsHref; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } // Set flag chart.hasRendered = true; }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: in spite of JSLint's complaints, win == win.top is required /*jslint eqeq: true*/ if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { /*jslint eqeq: false*/ if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options, callback = chart.callback; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set chart.pointer = new Pointer(chart, options); chart.render(); // add canvas chart.renderer.draw(); // run callbacks if (callback) { callback.apply(chart, [chart]); } each(chart.callbacks, function (fn) { fn.apply(chart, [chart]); }); // If the chart was rendered outside the top container, put it back in chart.cloneRenderTo(true); fireEvent(chart, 'load'); } }; // end Chart // Hook for exporting module Chart.prototype.callbacks = []; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if (point.x === UNDEFINED && series) { point.x = x === UNDEFINED ? series.autoIncrement() : x; } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function (options) { var ret, series = this.series, pointArrayMap = series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (typeof options === 'number' || options === null) { ret = { y: options }; } else if (isArray(options)) { ret = {}; // with leading x value if (options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { ret[pointArrayMap[j++]] = options[i++]; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { var point = this; return { x: point.category, y: point.y, key: point.name || point.category, series: point.series, point: point, percentage: point.percentage, total: point.total || point.stackTotal }; }, /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the defalut handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point */ onMouseOver: function (e) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); chart.hoverPoint = point; }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887 this.firePointEvent('mouseOut'); this.setState(); chart.hoverPoint = null; } }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation) { var point = this, series = point.series, graphic = point.graphic, i, data = series.data, chart = series.chart; redraw = pick(redraw, true); // fire the event with a default handler of doing the update point.firePointEvent('update', { options: options }, function () { point.applyOptions(options); // update visuals if (isObject(options)) { series.getAttribs(); if (graphic) { graphic.attr(point.pointAttr[series.state]); } } // record changes in the parallel arrays i = inArray(point, data); series.xData[i] = point.x; series.yData[i] = series.toYData ? series.toYData(point) : point.y; series.zData[i] = point.z; series.options.data[i] = point.options; // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(animation); } }); }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var point = this, series = point.series, chart = series.chart, i, data = series.data; setAnimation(animation, chart); redraw = pick(redraw, true); // fire the event with a default handler of removing the point point.firePointEvent('remove', null, function () { // splice all the parallel arrays i = inArray(point, data); data.splice(i, 1); series.options.data.splice(i, 1); series.xData.splice(i, 1); series.yData.splice(i, 1); series.zData.splice(i, 1); point.destroy(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }); }, /** * Fire an event on the Point object. Must not be renamed to fireEvent, as this * causes a name clash in MooTools * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); }; } fireEvent(this, eventType, eventArgs, defaultFunction); }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state) { var point = this, plotX = point.plotX, plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, newSymbol, pointAttr = point.pointAttr; state = state || NORMAL_STATE; // empty string if ( // already has this state state === point.state || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // point marker's state options is disabled (state && (stateDisabled || (normalDisabled && !markerStateOptions.enabled))) ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr[state].r; point.graphic.attr(merge( pointAttr[state], radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr[state]) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; // Move the existing graphic } else { stateMarkerGraphic.attr({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY) ? 'show' : 'hide'](); } } point.state = state; } }; /** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, colorCounter: 0, init: function (chart, options) { var series = this, eventType, events, linkedTo, chartSeries = chart.series; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // set the data series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123) stableSort(chartSeries, function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, a._i); }); each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); // Linked series linkedTo = options.linkedTo; series.linkedSeries = []; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chartSeries[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; } } }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; if (series.isCartesian) { each(['xAxis', 'yAxis'], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS]) { error(17, true); } }); } }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var series = this, options = series.options, xIncrement = series.xIncrement; xIncrement = pick(xIncrement, options.pointStart, 0); series.pointInterval = pick(series.pointInterval, options.pointInterval, 1); series.xIncrement = xIncrement + series.pointInterval; return xIncrement; }, /** * Divide the series data into segments divided by null values. */ getSegments: function () { var series = this, lastNull = -1, segments = [], i, points = series.points, pointsLength = points.length; if (pointsLength) { // no action required for [] // if connect nulls, just remove null points if (series.options.connectNulls) { i = pointsLength; while (i--) { if (points[i].y === null) { points.splice(i, 1); } } if (points.length) { segments = [points]; } // else, split on null points } else { each(points, function (point, i) { if (point.y === null) { if (i > lastNull + 1) { segments.push(points.slice(lastNull + 1, i)); } lastNull = i; } else if (i === pointsLength - 1) { // last value segments.push(points.slice(lastNull + 1, i + 1)); } }); } } // register it series.segments = segments; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, typeOptions = plotOptions[this.type], options; this.userOptions = itemOptions; options = merge( typeOptions, plotOptions.series, itemOptions ); // the tooltip options are merged between global and series specific options this.tooltipOptions = merge(chartOptions.tooltip, options.tooltip); // Delte marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } return options; }, /** * Get the series' color */ getColor: function () { var options = this.options, userOptions = this.userOptions, defaultColors = this.chart.options.colors, counters = this.chart.counters, color, colorIndex; color = options.color || defaultPlotOptions[this.type].color; if (!color && !options.colorByPoint) { if (defined(userOptions._colorIndex)) { // after Series.update() colorIndex = userOptions._colorIndex; } else { userOptions._colorIndex = counters.color; colorIndex = counters.color++; } color = defaultColors[colorIndex]; } this.color = color; counters.wrapColor(defaultColors.length); }, /** * Get the series' symbol */ getSymbol: function () { var series = this, userOptions = series.userOptions, seriesMarkerOption = series.options.marker, chart = series.chart, defaultSymbols = chart.options.symbols, counters = chart.counters, symbolIndex; series.symbol = seriesMarkerOption.symbol; if (!series.symbol) { if (defined(userOptions._symbolIndex)) { // after Series.update() symbolIndex = userOptions._symbolIndex; } else { userOptions._symbolIndex = counters.symbol; symbolIndex = counters.symbol++; } series.symbol = defaultSymbols[symbolIndex]; } // don't substract radius in image symbols (#604) if (/^url/.test(series.symbol)) { seriesMarkerOption.radius = 0; } counters.wrapSymbol(defaultSymbols.length); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLegendSymbol: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendOptions = legend.options, legendSymbol, symbolWidth = legendOptions.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, baseline = legend.baseline, attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, baseline - 4, L, symbolWidth, baseline - 4 ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, baseline - 4 - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); } }, /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, xData = series.xData, yData = series.yData, zData = series.zData, names = series.names, currentShift = (graph && graph.shift) || 0, dataOptions = seriesOptions.data, point; setAnimation(animation, chart); // Make graph animate sideways if (graph && shift) { graph.shift = currentShift + 1; } if (area) { if (shift) { // #780 area.shift = currentShift + 1; } area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); xData.push(point.x); yData.push(series.toYData ? series.toYData(point) : point.y); zData.push(point.z); if (names) { names[point.x] = point.name; } dataOptions.push(options); // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays // todo: consider series.removePoint(i) method if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); xData.shift(); yData.shift(); zData.shift(); dataOptions.shift(); } } series.getAttribs(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw) { var series = this, oldData = series.points, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, names = xAxis && xAxis.categories && !xAxis.categories.length ? [] : null, i; // reset properties series.xIncrement = null; series.pointRange = xAxis && xAxis.categories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // parallel arrays var xData = [], yData = [], zData = [], dataLength = data ? data.length : [], turboThreshold = options.turboThreshold || 1000, pt, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length, hasToYData = !!series.toYData; // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } /* else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode }*/ } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); xData[i] = pt.x; yData[i] = hasToYData ? series.toYData(pt) : pt.y; zData[i] = pt.z; if (names && pt.name) { names[i] = pt.name; } } } } // Unsorted data is not supported by the line tooltip as well as data grouping and // navigation in Stock charts (#725) if (series.requireSorting && xData.length > 1 && xData[1] < xData[0]) { error(15); } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = data; series.xData = xData; series.yData = yData; series.zData = zData; series.names = names; // destroy old points i = (oldData && oldData.length) || 0; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(false); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; redraw = pick(redraw, true); if (!series.isRemoving) { /* prevent triggering native event in jQuery (calling the remove function from the remove event) */ series.isRemoving = true; // fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function () { // destroy elements series.destroy(); // redraw chart.isDirtyLegend = chart.isDirtyBox = true; if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, cropStart = 0, cropEnd = dataLength, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, isCartesian = series.isCartesian; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { var extremes = xAxis.getExtremes(), min = extremes.min, max = extremes.max; // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (processedXData[i] >= min) { cropStart = mathMax(0, i - 1); break; } } // proceed to find slice end for (; i < dataLength; i++) { if (processedXData[i] > max) { cropEnd = i + 1; break; } } processedXData = processedXData.slice(cropStart, cropEnd); processedYData = processedYData.slice(cropStart, cropEnd); cropped = true; } } // Find the closest distance between processed points for (i = processedXData.length - 1; i > 0; i--) { distance = processedXData[i] - processedXData[i - 1]; if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = closestPointRange || 1; } series.closestPointRange = closestPointRange; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); } } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, isBottomSeries, allStackSeries = yAxis.series, i = allStackSeries.length, placeBetween = options.pointPlacement === 'between', threshold = options.threshold; //nextSeriesDown; // Is it the last visible series? while (i--) { if (allStackSeries[i].visible) { if (allStackSeries[i] === series) { // #809 isBottomSeries = true; } break; } } // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = yAxis.stacks[(yValue < threshold ? '-' : '') + series.stackKey], pointStack, pointStackTotal; // Discard disallowed y values for log axes if (yAxis.isLog && yValue <= 0) { point.y = yValue = null; } // Get the plotX translation point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, placeBetween); // Math.round fixes #591 // Calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { pointStack = stack[xValue]; pointStackTotal = pointStack.total; pointStack.cum = yBottom = pointStack.cum - yValue; // start from top yValue = yBottom + yValue; if (isBottomSeries) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } if (stacking === 'percent') { yBottom = pointStackTotal ? yBottom * 100 / pointStackTotal : 0; yValue = pointStackTotal ? yValue * 100 / pointStackTotal : 0; } point.percentage = pointStackTotal ? point.y * 100 / pointStackTotal : 0; point.total = point.stackTotal = pointStackTotal; point.stackY = yValue; } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ? mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591 UNDEFINED; // Set client related positions for mouse tracking point.clientX = placeBetween ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; } // now that we have the cropped data, build the segments series.getSegments(); }, /** * Memoize tooltip texts and positions */ setTooltipPoints: function (renew) { var series = this, points = [], pointsLength, low, high, xAxis = series.xAxis, axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar point, i, tooltipPoints = []; // a lookup array for each pixel in the x dimension // don't waste resources if tracker is disabled if (series.options.enableMouseTracking === false) { return; } // renew if (renew) { series.tooltipPoints = null; } // concat segments to overcome null values each(series.segments || series.points, function (segment) { points = points.concat(segment); }); // Reverse the points in case the X axis is reversed if (xAxis && xAxis.reversed) { points = points.reverse(); } // Assign each pixel position to the nearest point pointsLength = points.length; for (i = 0; i < pointsLength; i++) { point = points[i]; // Set this range's low to the last range's high plus one low = points[i - 1] ? high + 1 : 0; // Now find the new high high = points[i + 1] ? mathMax(0, mathFloor((point.clientX + (points[i + 1] ? points[i + 1].clientX : axisLength)) / 2)) : axisLength; while (low >= 0 && low <= high) { tooltipPoints[low++] = point; } } series.tooltipPoints = tooltipPoints; }, /** * Format the header of the tooltip */ tooltipHeaderFormatter: function (point) { var series = this, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime', headerFormat = tooltipOptions.headerFormat, n; // Guess the best date format based on the closest point distance (#568) if (isDateTime && !xDateFormat) { for (n in timeUnits) { if (timeUnits[n] >= xAxis.closestPointRange) { xDateFormat = tooltipOptions.dateTimeLabelFormats[n]; break; } } } // Insert the header date format if any if (isDateTime && xDateFormat && isNumber(point.key)) { headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(headerFormat, { point: point, series: series }); }, /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); chart.hoverSeries = null; }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, renderer = chart.renderer, clipRect, markerClipRect, animation = series.options.animation, clipBox = chart.clipBox, inverted = chart.inverted, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } sharedClipKey = '_sharedClip' + animation.duration + animation.easing; // Initialize the animation. Set up the clipping rectangle. if (init) { // If a clipping rectangle with the same properties is currently present in the chart, use that. clipRect = chart[sharedClipKey]; markerClipRect = chart[sharedClipKey + 'm']; if (!clipRect) { chart[sharedClipKey] = clipRect = renderer.clipRect( extend(clipBox, { width: 0 }) ); chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } series.group.clip(clipRect); series.markerGroup.clip(markerClipRect); series.sharedClipKey = sharedClipKey; // Run the animation } else { clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animation.duration); } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { var chart = this.chart, sharedClipKey = this.sharedClipKey, group = this.group; if (group && this.options.clip !== false) { group.clip(chart.clipRect); this.markerGroup.clip(); // no clip } // Remove the shared clipping rectancgle when all series are shown setTimeout(function () { if (sharedClipKey && chart[sharedClipKey]) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } }, 100); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, pointMarkerOptions, enabled, isInside, markerGroup = series.markerGroup; if (seriesMarkerOptions.enabled || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = point.plotX; plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; enabled = (seriesMarkerOptions.enabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = chart.isInsidePlot(plotX, plotY, chart.inverted); // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic .attr({ // Since the marker group isn't clipped, each individual marker must be toggled visibility: isInside ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN }) .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions, negativeColor = seriesOptions.negativeColor, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (point.negative && negativeColor) { point.color = point.fillColor = negativeColor; } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker) { // column, bar, point // if no hover color is given, brighten the normal color pointStateOptionsHover.color = Color(pointStateOptionsHover.color || point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness).get(); } // normal point state inherits series wide normal state pointAttr[NORMAL_STATE] = series.convertAttribs(extend({ color: point.color // #868 }, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // Force the fill to negativeColor on markers if (point.negative && seriesOptions.marker) { pointAttr[NORMAL_STATE].fill = pointAttr[HOVER_STATE].fill = pointAttr[SELECT_STATE].fill = series.convertAttribs({ fillColor: negativeColor }).fill; } // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type; // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, newOptions); // Destroy the series and reinsert methods from the type prototype this.remove(false); extend(this, seriesTypes[newOptions.type || oldType].prototype); this.init(chart, newOptions); if (pick(redraw, true)) { chart.redraw(false); } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(['xAxis', 'yAxis'], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // destroy all SVGElements associated to the series each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker', 'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) { if (series[prop]) { // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } }); // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Draw the data labels */ drawDataLabels: function () { var series = this, seriesOptions = series.options, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, str, dataLabelsGroup; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', series.visible ? VISIBLE : HIDDEN, options.zIndex || 6 ); // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true; // Determine if each data label is enabled pointOptions = point.options && point.options.dataLabels; enabled = generalOptions.enabled || (pointOptions && pointOptions.enabled); // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { rotation = options.rotation; // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color options.style.color = pick(options.color, options.style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, null, null, null, options.useHTML ) .attr(attr) .css(options.style) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }, /** * Align each individual data label */ alignDataLabel: function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -999), plotY = pick(point.plotY, -999), bBox = dataLabel.getBBox(), alignAttr; // the final position; // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (options.rotation) { // Fancy box alignment isn't supported for rotated text alignAttr = { align: options.align, x: alignTo.x + options.x + alignTo.width / 2, y: alignTo.y + options.y + alignTo.height / 2 }; dataLabel[isNew ? 'attr' : 'animate'](alignAttr); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; } // Show or hide based on the final aligned position dataLabel.attr({ visibility: options.crop === false || /*chart.isInsidePlot(alignAttr.x, alignAttr.y) || */chart.isInsidePlot(plotX, plotY, inverted) ? (chart.renderer.isSVG ? 'inherit' : VISIBLE) : HIDDEN }); }, /** * Return the graph path of a segment */ getSegmentPath: function (segment) { var series = this, segmentPath = [], step = series.options.step; // build the segment line each(segment, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint; if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i)); } else { // moveTo or lineTo segmentPath.push(i ? L : M); // step line? if (step && i) { lastPoint = segment[i - 1]; if (step === 'right') { segmentPath.push( lastPoint.plotX, plotY ); } else if (step === 'center') { segmentPath.push( (lastPoint.plotX + plotX) / 2, lastPoint.plotY, (lastPoint.plotX + plotX) / 2, plotY ); } else { segmentPath.push( plotX, lastPoint.plotY ); } } // normal line to next point segmentPath.push( point.plotX, point.plotY ); } }); return segmentPath; }, /** * Get the graph path */ getGraphPath: function () { var series = this, graphPath = [], segmentPath, singlePoints = []; // used in drawTracker // Divide into segments and build graph and area paths each(series.segments, function (segment) { segmentPath = series.getSegmentPath(segment); // add the segment to the graph, or a single point for tracking if (segment.length > 1) { graphPath = graphPath.concat(segmentPath); } else { singlePoints.push(segment[0]); } }); // Record it for use in drawGraph and drawTracker, and return graphPath series.singlePoints = singlePoints; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var series = this, options = this.options, props = [['graph', options.lineColor || this.color]], lineWidth = options.lineWidth, dashStyle = options.dashStyle, graphPath = this.getGraphPath(), negativeColor = options.negativeColor; if (negativeColor) { props.push(['graphNeg', negativeColor]); } // draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { stop(graph); // cancel running animations, #459 graph.animate({ d: graphPath }); } else if (lineWidth && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, zIndex: 1 // #1069 }; if (dashStyle) { attribs.dashstyle = dashStyle; } series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow(!i && options.shadow); } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ clipNeg: function () { var options = this.options, chart = this.chart, renderer = chart.renderer, negativeColor = options.negativeColor, translatedThreshold, posAttr, negAttr, posClip = this.posClip, negClip = this.negClip, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartSizeMax = mathMax(chartWidth, chartHeight), above, below; if (negativeColor && this.graph) { translatedThreshold = mathCeil(this.yAxis.len - this.yAxis.translate(options.threshold || 0)); above = { x: 0, y: 0, width: chartSizeMax, height: translatedThreshold }; below = { x: 0, y: translatedThreshold, width: chartSizeMax, height: chartSizeMax - translatedThreshold }; if (chart.inverted && renderer.isVML) { above = { x: chart.plotWidth - translatedThreshold - chart.plotLeft, y: 0, width: chartWidth, height: chartHeight }; below = { x: translatedThreshold + chart.plotLeft - chartWidth, y: 0, width: chart.plotLeft + translatedThreshold, height: chartWidth }; } if (this.yAxis.reversed) { posAttr = below; negAttr = above; } else { posAttr = above; negAttr = below; } if (posClip) { // update posClip.animate(posAttr); negClip.animate(negAttr); } else { this.posClip = posClip = renderer.clipRect(posAttr); this.graph.clip(posClip); this.negClip = negClip = renderer.clipRect(negAttr); this.graphNeg.clip(negClip); if (this.area) { this.area.clip(posClip); this.areaNeg.clip(negClip); } } } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group, chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Generate it on first call if (isNew) { this[prop] = group = chart.renderer.g(name) .attr({ visibility: visibility, zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); } // Place it on first and subsequent (redraw) calls group[isNew ? 'attr' : 'animate']({ translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }); return group; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, doAnimation = animation && !!series.animate && chart.renderer.isSVG, // this animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE visibility = series.visible ? VISIBLE : HIDDEN, zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (doAnimation) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089) group.inverted = chart.inverted; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.clipNeg(); } // draw the data labels (inn pies they go before the points) series.drawDataLabels(); // draw the points series.drawPoints(); // draw the mouse tracking area if (series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (doAnimation) { series.animate(); } else if (!hasRendered) { series.afterAnimate(); } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); series.setTooltipPoints(true); series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, graphNeg = series.graphNeg, stateOptions = options.states, lineWidth = options.lineWidth, attribs; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + 1; } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); if (graphNeg) { graphNeg.attr(attribs); } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTracker: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = tracker = renderer.path(trackerPath) .attr({ 'class': PREFIX + 'tracker', 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css) .add(series.markerGroup); if (hasTouch) { tracker.on('touchstart', onMouseOver); } } } }; // end Series prototype /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for area */ defaultPlotOptions.area = merge(defaultSeriesOptions, { threshold: 0 // trackByArea: false, // lineColor: null, // overrides color, but lets fillColor be unaltered // fillOpacity: 0.75, // fillColor: null }); /** * AreaSeries object */ var AreaSeries = extendClass(Series, { type: 'area', /** * For stacks, don't split segments on null values. Instead, draw null values with * no marker. Also insert dummy points for any X position that exists in other series * in the stack. */ getSegments: function () { var segments = [], segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, plotX, plotY, points = this.points, i, x; if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue // Create a map where we can quickly look up the points by their X value. for (i = 0; i < points.length; i++) { pointMap[points[i].x] = points[i]; } // Sort the keys (#1651) for (x in stack) { keys.push(+x); } keys.sort(function (a, b) { return a - b; }); each(keys, function (x) { // The point exists, push it to the segment if (pointMap[x]) { segment.push(pointMap[x]); // There is no point for this X value in this series, so we // insert a dummy point in order for the areas to be drawn // correctly. } else { plotX = xAxis.translate(x); plotY = yAxis.toPixels(stack[x].cum, true); segment.push({ y: null, plotX: plotX, clientX: plotX, plotY: plotY, yBottom: plotY, onMouseOver: noop }); } }); if (segment.length) { segments.push(segment); } } else { Series.prototype.getSegments.call(this); segments = this.segments; } this.segments = segments; }, /** * Extend the base Series getSegmentPath method by adding the path for the area. * This path is pushed to the series.areaPath property. */ getSegmentPath: function (segment) { var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path i, options = this.options, segLength = segmentPath.length; if (segLength === 3) { // for animation from 1 to two points areaSegmentPath.push(L, segmentPath[1], segmentPath[2]); } if (options.stacking && !this.closedStacks) { // Follow stack back. Todo: implement areaspline. A general solution could be to // reverse the entire graphPath of the previous series, though may be hard with // splines and with series with different extremes for (i = segment.length - 1; i >= 0; i--) { // step line? if (i < segment.length - 1 && options.step) { areaSegmentPath.push(segment[i + 1].plotX, segment[i].yBottom); } areaSegmentPath.push(segment[i].plotX, segment[i].yBottom); } } else { // follow zero line back this.closeSegment(areaSegmentPath, segment); } this.areaPath = this.areaPath.concat(areaSegmentPath); return segmentPath; }, /** * Extendable method to close the segment path of an area. This is overridden in polar * charts. */ closeSegment: function (path, segment) { var translatedThreshold = this.yAxis.getThreshold(this.options.threshold); path.push( L, segment[segment.length - 1].plotX, translatedThreshold, L, segment[0].plotX, translatedThreshold ); }, /** * Draw the graph and the underlying area. This method calls the Series base * function and adds the area. The areaPath is calculated in the getSegmentPath * method called from Series.prototype.drawGraph. */ drawGraph: function () { // Define or reset areaPath this.areaPath = []; // Call the base method Series.prototype.drawGraph.apply(this); // Define local variables var series = this, areaPath = this.areaPath, options = this.options, negativeColor = options.negativeColor, props = [['area', this.color, options.fillColor]]; // area name, main color, fill color if (negativeColor) { props.push(['areaNeg', options.negativeColor, options.negativeFillColor]); } each(props, function (prop) { var areaKey = prop[0], area = series[areaKey]; // Create or update the area if (area) { // update area.animate({ d: areaPath }); } else { // create series[areaKey] = series.chart.renderer.path(areaPath) .attr({ fill: pick( prop[2], Color(prop[1]).setOpacity(options.fillOpacity || 0.75).get() ), zIndex: 0 // #1069 }).add(series.group); } }); }, /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawLegendSymbol: function (legend, item) { item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 11, legend.options.symbolWidth, 12, 2 ).attr({ zIndex: 3 }).add(item.legendGroup); } }); seriesTypes.area = AreaSeries;/** * Set the default options for spline */ defaultPlotOptions.spline = merge(defaultSeriesOptions); /** * SplineSeries object */ var SplineSeries = extendClass(Series, { type: 'spline', /** * Get the spline segment from a given point's previous neighbour to the given point */ getPointSpline: function (segment, point, i) { var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = segment[i - 1], nextPoint = segment[i + 1], leftContX, leftContY, rightContX, rightContY, ret; // find control points if (lastPoint && nextPoint) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // have the two control points make a straight line through main point correction = ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY; leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are between // neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = mathMax(lastY, plotY); rightContY = 2 * plotY - leftContY; // mirror of left control point } else if (leftContY < lastY && leftContY < plotY) { leftContY = mathMin(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = mathMax(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = mathMin(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // Visualize control points for debugging /* if (leftContX) { this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2) .attr({ stroke: 'red', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'red', 'stroke-width': 1 }) .add(); this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2) .attr({ stroke: 'green', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'green', 'stroke-width': 1 }) .add(); } */ // moveTo or lineTo if (!i) { ret = [M, plotX, plotY]; } else { // curve from last point to this ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } return ret; } }); seriesTypes.spline = SplineSeries; /** * Set the default options for areaspline */ defaultPlotOptions.areaspline = merge(defaultPlotOptions.area); /** * AreaSplineSeries object */ var areaProto = AreaSeries.prototype, AreaSplineSeries = extendClass(SplineSeries, { type: 'areaspline', closedStacks: true, // instead of following the previous graph back, follow the threshold back // Mix in methods from the area series getSegmentPath: areaProto.getSegmentPath, closeSegment: areaProto.closeSegment, drawGraph: areaProto.drawGraph }); seriesTypes.areaspline = AreaSplineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, stickyTracking: false, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', tooltipOutsidePlot: true, requireSorting: false, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color', r: 'borderRadius' }, trackerGroups: ['group', 'dataLabelsGroup'], /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, chart = series.chart, options = series.options, xAxis = this.xAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnIndex, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(chart.series, function (otherSeries) { var otherOptions = otherSeries.options; if (otherSeries.type === series.type && otherSeries.visible && series.options.group === otherOptions.group) { // used in Stock charts navigator series if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = mathMin( mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || 1), xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, optionPointWidth = options.pointWidth, pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 : pointOffsetWidth * options.pointPadding, pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts colIndex = (reversedXAxis ? columnCount - (series.columnIndex || 0) : // #1251 series.columnIndex) || 0, pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) return (series.columnMetrics = { width: pointWidth, offset: pointXOffset }); }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, stacking = options.stacking, borderWidth = options.borderWidth, yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width pointXOffset = metrics.offset; Series.prototype.translate.apply(series); // record the new values each(series.points, function (point) { var plotY = mathMin(mathMax(-999, point.plotY), yAxis.len + 999), // Don't draw too far outside plot area (#1303) yBottom = pick(point.yBottom, translatedThreshold), barX = point.plotX + pointXOffset, barY = mathCeil(mathMin(plotY, yBottom)), barH = mathCeil(mathMax(plotY, yBottom) - barY), stack = yAxis.stacks[(point.y < 0 ? '-' : '') + series.stackKey], shapeArgs; // Record the offset'ed position and width of the bar to be able to align the stacking total correctly if (stacking && series.visible && stack && stack[point.x]) { stack[point.x].setOffset(pointXOffset, barW); } // handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; barY = mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0); // use exact yAxis.translation (#1485) } } point.barX = barX; point.pointWidth = pointWidth; // create shape type and shape args that are reused in drawPoints and drawTracker point.shapeType = 'rect'; point.shapeArgs = shapeArgs = chart.renderer.Element.prototype.crisp.call(0, borderWidth, barX, barY, barW, barH); if (borderWidth % 2) { // correct for shorting in crisp method, visible in stacked columns with 1px border shapeArgs.y -= 1; shapeArgs.height += 1; } }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, options = series.options, renderer = series.chart.renderer, shapeArgs; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; if (graphic) { // update stop(graphic); graphic.animate(merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]) .add(series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ drawTracker: function () { var series = this, pointer = series.chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; series.onMouseOver(); while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); } else { series._hasTracking = true; } }, /** * Override the basic data label alignment by adjusting for the position of the column */ alignDataLabel: function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)), inside = pick(options.inside, !!this.options.stacking); // draw it inside the box? // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (inverted) { alignTo = { x: chart.plotWidth - alignTo.y - alignTo.height, y: chart.plotHeight - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr.scaleY = 1; attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, series.options.animation); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for bar */ defaultPlotOptions.bar = merge(defaultPlotOptions.column); /** * The Bar series class */ var BarSeries = extendClass(ColumnSeries, { type: 'bar', inverted: true }); seriesTypes.bar = BarSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, tooltip: { headerFormat: '<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>', followPointer: true }, stickyTracking: false }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['markerGroup'], drawTracker: ColumnSeries.prototype.drawTracker, setTooltipPoints: noop }); seriesTypes.scatter = ScatterSeries; /** * Set the default options for pie */ defaultPlotOptions.pie = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, center: [null, null], clip: false, colorByPoint: true, // always true for pies dataLabels: { // align: null, // connectorWidth: 1, // connectorColor: point.color, // connectorPadding: 5, distance: 30, enabled: true, formatter: function () { return this.point.name; } // softConnector: true, //y: 0 }, ignoreHiddenPoint: true, //innerSize: 0, legendType: 'point', marker: null, // point options are specified in the base options size: null, showInLegend: false, slicedOffset: 10, states: { hover: { brightness: 0.1, shadow: false } }, stickyTracking: false, tooltip: { followPointer: true } }); /** * Extended point object for pies */ var PiePoint = extendClass(Point, { /** * Initiate the pie slice */ init: function () { Point.prototype.init.apply(this, arguments); var point = this, toggleSlice; // Disallow negative values (#1530) if (point.y < 0) { point.y = null; } //visible: options.visible !== false, extend(point, { visible: point.visible !== false, name: pick(point.name, 'Slice') }); // add event listener for select toggleSlice = function () { point.slice(); }; addEvent(point, 'select', toggleSlice); addEvent(point, 'unselect', toggleSlice); return point; }, /** * Toggle the visibility of the pie slice * @param {Boolean} vis Whether to show the slice or not. If undefined, the * visibility is toggled */ setVisible: function (vis) { var point = this, series = point.series, chart = series.chart, method; // if called without an argument, toggle visibility point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data method = vis ? 'show' : 'hide'; // Show and hide associated elements each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][method](); } }); if (point.legendItem) { chart.legend.colorizeItem(point, vis); } // Handle ignore hidden slices if (!series.isDirty && series.options.ignoreHiddenPoint) { series.isDirty = true; chart.redraw(); } }, /** * Set or toggle whether the slice is cut out from the pie * @param {Boolean} sliced When undefined, the slice state is toggled * @param {Boolean} redraw Whether to redraw the chart. True by default. */ slice: function (sliced, redraw, animation) { var point = this, series = point.series, chart = series.chart, translation; setAnimation(animation, chart); // redraw is true by default redraw = pick(redraw, true); // if called without an argument, toggle point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data translation = sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; point.graphic.animate(translation); if (point.shadowGroup) { point.shadowGroup.animate(translation); } } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, /** * Pies have one color each point */ getColor: noop, /** * Animate the pies in */ animate: function (init) { var series = this, points = series.points, startAngleRad = series.startAngleRad; if (!init) { each(points, function (point) { var graphic = point.graphic, args = point.shapeArgs; if (graphic) { // start values graphic.attr({ r: series.center[3] / 2, // animate from inner radius (#779) start: startAngleRad, end: startAngleRad }); // animate graphic.animate({ r: args.r, start: args.start, end: args.end }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }, /** * Extend the basic setData method by running processData and generatePoints immediately, * in order to access the points from the legend. */ setData: function (data, redraw) { Series.prototype.setData.call(this, data, false); this.processData(); this.generatePoints(); if (pick(redraw, true)) { this.chart.redraw(); } }, /** * Get the center of the pie based on the size and center options relative to the * plot area. Borrowed by the polar and gauge series types. */ getCenter: function () { var options = this.options, chart = this.chart, slicingRoom = 2 * (options.slicedOffset || 0), handleSlicingRoom, plotWidth = chart.plotWidth - 2 * slicingRoom, plotHeight = chart.plotHeight - 2 * slicingRoom, centerOption = options.center, positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0], smallestSize = mathMin(plotWidth, plotHeight), isPercent; return map(positions, function (length, i) { isPercent = /%$/.test(length); handleSlicingRoom = i < 2 || (i === 2 && isPercent); return (isPercent ? // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 4: innerSize, relative to smallestSize [plotWidth, plotHeight, smallestSize, smallestSize][i] * pInt(length) / 100 : length) + (handleSlicingRoom ? slicingRoom : 0); }); }, /** * Do translation for pie slices */ translate: function (positions) { this.generatePoints(); var total = 0, series = this, cumulative = 0, precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, start, end, angle, startAngleRad = series.startAngleRad = mathPI / 180 * ((options.startAngle || 0) % 360 - 90), points = series.points, circ = 2 * mathPI, fraction, radiusX, // the x component of the radius vector for a given point radiusY, labelDistance = options.dataLabels.distance, ignoreHiddenPoint = options.ignoreHiddenPoint, i, len = points.length, point; // Get positions - either an integer or a percentage string must be given. // If positions are passed as a parameter, we're in a recursive loop for adjusting // space for data labels. if (!positions) { series.center = positions = series.getCenter(); } // utility for getting the x value from a given y, used for anticollision logic in data labels series.getX = function (y, left) { angle = math.asin((y - positions[1]) / (positions[2] / 2 + labelDistance)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // get the total sum for (i = 0; i < len; i++) { point = points[i]; total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y; } // Calculate the geometry for each point for (i = 0; i < len; i++) { point = points[i]; // set start and end angle fraction = total ? point.y / total : 0; start = mathRound((startAngleRad + (cumulative * circ)) * precision) / precision; if (!ignoreHiddenPoint || point.visible) { cumulative += fraction; } end = mathRound((startAngleRad + (cumulative * circ)) * precision) / precision; // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: start, end: end }; // center for the sliced out slice angle = (end + start) / 2; if (angle > 0.75 * circ) { angle -= 2 * mathPI; } point.slicedTranslation = { translateX: mathRound(mathCos(angle) * slicedOffset), translateY: mathRound(mathSin(angle) * slicedOffset) }; // set the anchor point for tooltips radiusX = mathCos(angle) * positions[2] / 2; radiusY = mathSin(angle) * positions[2] / 2; point.tooltipPos = [ positions[0] + radiusX * 0.7, positions[1] + radiusY * 0.7 ]; point.half = angle < circ / 4 ? 0 : 1; point.angle = angle; // set the anchor point for data labels connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678 point.labelPos = [ positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a positions[0] + radiusX, // landing point for connector positions[1] + radiusY, // a/a labelDistance < 0 ? // alignment 'center' : point.half ? 'right' : 'left', // alignment angle // center angle ]; // API properties point.percentage = fraction * 100; point.total = total; } this.setTooltipPoints(); }, drawGraph: null, /** * Draw the data points */ drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, groupTranslation, //center, graphic, //group, shadow = series.options.shadow, shadowGroup, shapeArgs; if (shadow && !series.shadowGroup) { series.shadowGroup = renderer.g('shadow') .add(series.group); } // draw the slices each(series.points, function (point) { graphic = point.graphic; shapeArgs = point.shapeArgs; shadowGroup = point.shadowGroup; // put the shadow behind all points if (shadow && !shadowGroup) { shadowGroup = point.shadowGroup = renderer.g('shadow') .add(series.shadowGroup); } // if the point is sliced, use special translation, else use plot area traslation groupTranslation = point.sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; //group.translate(groupTranslation[0], groupTranslation[1]); if (shadowGroup) { shadowGroup.attr(groupTranslation); } // draw the slice if (graphic) { graphic.animate(extend(shapeArgs, groupTranslation)); } else { point.graphic = graphic = renderer.arc(shapeArgs) .setRadialReference(series.center) .attr( point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] ) .attr({ 'stroke-linejoin': 'round' }) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } // detect point specific visibility if (point.visible === false) { point.setVisible(false); } }); }, /** * Override the base drawDataLabels method by pie specific functionality */ drawDataLabels: function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }, sortByAngle = function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }; // get out if not enabled if (!options.enabled && !series._hasPointLabels) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function (point) { if (point.dataLabel) { // it may have been cancelled in the base method (#407) halves[point.half].push(point); } }); // assume equal label heights i = 0; while (!labelHeight && data[i]) { // #1569 labelHeight = data[i] && data[i].dataLabel && (data[i].dataLabel.getBBox().height || 21); // 21 is for #968 i++; } /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, length = points.length, slotIndex; // Sort by angle sortByAngle(points, i - 0.5); // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // build the slots for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) { slots.push(pos); // visualize the slot /* var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver' }) .add(); chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4) .attr({ fill: 'silver' }).add(); } */ } slotsLength = slots.length; // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : VISIBLE; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = naturalY; } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(slotIndex === 0 || slotIndex === slots.length - 1 ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos) { x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility }) .add(series.group); } } else if (connector) { point.connector = connector.destroy(); } }); } } }, /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ verifyDataLabelOverflow: function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; this.translate(center); each(this.points, function (point) { if (point.dataLabel) { point.dataLabel._pos = null; // reset } }); this.drawDataLabels(); // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }, /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ placeDataLabels: function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -999 }); } } }); }, alignDataLabel: noop, /** * Draw point specific tracker objects. Inherit directly from column series. */ drawTracker: ColumnSeries.prototype.drawTracker, /** * Use a simple symbol from column prototype */ drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; // global variables extend(Highcharts, { // Constructors Axis: Axis, Chart: Chart, Color: Color, Legend: Legend, Pointer: Pointer, Point: Point, Tick: Tick, Tooltip: Tooltip, Renderer: Renderer, Series: Series, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, numberFormat: numberFormat, seriesTypes: seriesTypes, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, extend: extend, map: map, merge: merge, pick: pick, splat: splat, extendClass: extendClass, pInt: pInt, wrap: wrap, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); }());
JavaScript
$(function() { $(window).resize(function() { var wh = $(window).height(); var ww = $(window).width(); $('.mki_layer').css({height:wh,width:ww}); $('.mki_status_layer').css({top:((wh/2)-($('.mki_status_layer').outerHeight()/2)-10)}); $('.mki_center_layer').css({left:((ww/2)-225)}); }); $(window).resize(); });
JavaScript
/* Load this script using conditional IE comments if you need to support IE 7 and IE 6. */ window.onload = function() { function addIcon(el, entity) { var html = el.innerHTML; el.innerHTML = '<span style="font-family: \'icomoon\'">' + entity + '</span>' + html; } var icons = { 'icon-battery-low' : '&#xe000;', 'icon-battery' : '&#xe001;', 'icon-battery-full' : '&#xe002;', 'icon-battery-charging' : '&#xe003;', 'icon-plus' : '&#xe004;', 'icon-cross' : '&#xe005;', 'icon-arrow-right' : '&#xe006;', 'icon-arrow-left' : '&#xe007;', 'icon-pencil' : '&#xe008;', 'icon-search' : '&#xe009;', 'icon-grid' : '&#xe00a;', 'icon-list' : '&#xe00b;', 'icon-star' : '&#xe00c;', 'icon-heart' : '&#xe00d;', 'icon-back' : '&#xe00e;', 'icon-forward' : '&#xe00f;', 'icon-map-marker' : '&#xe010;', 'icon-phone' : '&#xe011;', 'icon-home' : '&#xe012;', 'icon-camera' : '&#xe013;', 'icon-arrow-left-2' : '&#xe014;', 'icon-arrow-right-2' : '&#xe015;', 'icon-arrow-up' : '&#xe016;', 'icon-arrow-down' : '&#xe017;', 'icon-refresh' : '&#xe018;', 'icon-refresh-2' : '&#xe019;', 'icon-escape' : '&#xe01a;', 'icon-repeat' : '&#xe01b;', 'icon-loop' : '&#xe01c;', 'icon-shuffle' : '&#xe01d;', 'icon-feed' : '&#xe01e;', 'icon-cog' : '&#xe01f;', 'icon-wrench' : '&#xe020;', 'icon-bars' : '&#xe021;', 'icon-chart' : '&#xe022;', 'icon-stats' : '&#xe023;', 'icon-eye' : '&#xe024;', 'icon-zoom-out' : '&#xe025;', 'icon-zoom-in' : '&#xe026;', 'icon-export' : '&#xe027;', 'icon-user' : '&#xe028;', 'icon-users' : '&#xe029;', 'icon-microphone' : '&#xe02a;', 'icon-mail' : '&#xe02b;', 'icon-comment' : '&#xe02c;', 'icon-trashcan' : '&#xe02d;', 'icon-delete' : '&#xe02e;', 'icon-infinity' : '&#xe02f;', 'icon-key' : '&#xe030;', 'icon-globe' : '&#xe031;', 'icon-thumbs-up' : '&#xe032;', 'icon-thumbs-down' : '&#xe033;', 'icon-tag' : '&#xe034;', 'icon-views' : '&#xe035;', 'icon-warning' : '&#xe036;', 'icon-beta' : '&#xe037;', 'icon-unlocked' : '&#xe038;', 'icon-locked' : '&#xe039;', 'icon-eject' : '&#xe03a;', 'icon-move' : '&#xe03b;', 'icon-expand' : '&#xe03c;', 'icon-cancel' : '&#xe03d;', 'icon-electricity' : '&#xe03e;', 'icon-compass' : '&#xe03f;', 'icon-location' : '&#xe040;', 'icon-directions' : '&#xe041;', 'icon-pin' : '&#xe042;', 'icon-mute' : '&#xe043;', 'icon-volume' : '&#xe044;', 'icon-globe-2' : '&#xe045;', 'icon-pencil-2' : '&#xe046;', 'icon-minus' : '&#xe047;', 'icon-equals' : '&#xe048;', 'icon-list-2' : '&#xe049;', 'icon-flag' : '&#xe04a;', 'icon-info' : '&#xe04b;', 'icon-question' : '&#xe04c;', 'icon-chat' : '&#xe04d;', 'icon-clock' : '&#xe04e;', 'icon-calendar' : '&#xe04f;', 'icon-sun' : '&#xe050;', 'icon-contrast' : '&#xe051;', 'icon-mobile' : '&#xe052;', 'icon-download' : '&#xe053;', 'icon-puzzle' : '&#xe054;', 'icon-music' : '&#xe055;', 'icon-scissors' : '&#xe056;', 'icon-bookmark' : '&#xe057;', 'icon-anchor' : '&#xe058;', 'icon-checkmark' : '&#xe059;', 'icon-phone-2' : '&#xe05a;', 'icon-mobile-2' : '&#xe05b;', 'icon-mouse' : '&#xe05c;', 'icon-directions-2' : '&#xe05d;', 'icon-mail-2' : '&#xe05e;', 'icon-paperplane' : '&#xe05f;', 'icon-pencil-3' : '&#xe060;', 'icon-feather' : '&#xe061;', 'icon-paperclip' : '&#xe062;', 'icon-drawer' : '&#xe063;', 'icon-reply' : '&#xe064;', 'icon-reply-all' : '&#xe065;', 'icon-forward-2' : '&#xe066;', 'icon-user-2' : '&#xe067;', 'icon-users-2' : '&#xe068;', 'icon-user-add' : '&#xe069;', 'icon-vcard' : '&#xe06a;', 'icon-export-2' : '&#xe06b;', 'icon-location-2' : '&#xe06c;', 'icon-map' : '&#xe06d;', 'icon-compass-2' : '&#xe06e;', 'icon-location-3' : '&#xe06f;', 'icon-target' : '&#xe070;', 'icon-share' : '&#xe071;', 'icon-sharable' : '&#xe072;', 'icon-heart-2' : '&#xe073;', 'icon-heart-3' : '&#xe074;', 'icon-star-2' : '&#xe075;', 'icon-star-3' : '&#xe076;', 'icon-thumbs-up-2' : '&#xe077;', 'icon-thumbs-down-2' : '&#xe078;', 'icon-chat-2' : '&#xe079;', 'icon-comment-2' : '&#xe07a;', 'icon-quote' : '&#xe07b;', 'icon-house' : '&#xe07c;', 'icon-popup' : '&#xe07d;', 'icon-search-2' : '&#xe07e;', 'icon-flashlight' : '&#xe07f;', 'icon-printer' : '&#xe080;', 'icon-bell' : '&#xe081;', 'icon-link' : '&#xe082;', 'icon-flag-2' : '&#xe083;', 'icon-cog-2' : '&#xe084;', 'icon-tools' : '&#xe085;', 'icon-trophy' : '&#xe086;', 'icon-tag-2' : '&#xe087;', 'icon-camera-2' : '&#xe088;', 'icon-megaphone' : '&#xe089;', 'icon-moon' : '&#xe08a;', 'icon-palette' : '&#xe08b;', 'icon-leaf' : '&#xe08c;', 'icon-music-2' : '&#xe08d;', 'icon-music-3' : '&#xe08e;', 'icon-new' : '&#xe08f;', 'icon-graduation' : '&#xe090;', 'icon-book' : '&#xe091;', 'icon-newspaper' : '&#xe092;', 'icon-bag' : '&#xe093;', 'icon-airplane' : '&#xe094;', 'icon-lifebuoy' : '&#xe095;', 'icon-eye-2' : '&#xe096;', 'icon-clock-2' : '&#xe097;', 'icon-microphone-2' : '&#xe098;', 'icon-calendar-2' : '&#xe099;', 'icon-bolt' : '&#xe09a;', 'icon-thunder' : '&#xe09b;', 'icon-droplet' : '&#xe09c;', 'icon-cd' : '&#xe09d;', 'icon-briefcase' : '&#xe09e;', 'icon-air' : '&#xe09f;', 'icon-hourglass' : '&#xe0a0;', 'icon-gauge' : '&#xe0a1;', 'icon-language' : '&#xe0a2;', 'icon-network' : '&#xe0a3;', 'icon-key-2' : '&#xe0a4;', 'icon-battery-2' : '&#xe0a5;', 'icon-bucket' : '&#xe0a6;', 'icon-magnet' : '&#xe0a7;', 'icon-drive' : '&#xe0a8;', 'icon-cup' : '&#xe0a9;', 'icon-rocket' : '&#xe0aa;', 'icon-brush' : '&#xe0ab;', 'icon-suitcase' : '&#xe0ac;', 'icon-cone' : '&#xe0ad;', 'icon-earth' : '&#xe0ae;', 'icon-keyboard' : '&#xe0af;', 'icon-browser' : '&#xe0b0;', 'icon-publish' : '&#xe0b1;', 'icon-progress-3' : '&#xe0b2;', 'icon-progress-2' : '&#xe0b3;', 'icon-brogress-1' : '&#xe0b4;', 'icon-progress-0' : '&#xe0b5;', 'icon-sun-2' : '&#xe0b6;', 'icon-sun-3' : '&#xe0b7;', 'icon-adjust' : '&#xe0b8;', 'icon-code' : '&#xe0b9;', 'icon-screen' : '&#xe0ba;', 'icon-infinity-2' : '&#xe0bb;', 'icon-light-bulb' : '&#xe0bc;', 'icon-credit-card' : '&#xe0bd;', 'icon-database' : '&#xe0be;', 'icon-voicemail' : '&#xe0bf;', 'icon-clipboard' : '&#xe0c0;', 'icon-cart' : '&#xe0c1;', 'icon-box' : '&#xe0c2;', 'icon-ticket' : '&#xe0c3;', 'icon-rss' : '&#xe0c4;', 'icon-signal' : '&#xe0c5;', 'icon-thermometer' : '&#xe0c6;', 'icon-droplets' : '&#xe0c7;', 'icon-untitled' : '&#xe0c8;', 'icon-statistics' : '&#xe0c9;', 'icon-pie' : '&#xe0ca;', 'icon-bars-2' : '&#xe0cb;', 'icon-graph' : '&#xe0cc;', 'icon-lock' : '&#xe0cd;', 'icon-lock-open' : '&#xe0ce;', 'icon-logout' : '&#xe0cf;', 'icon-login' : '&#xe0d0;', 'icon-checkmark-2' : '&#xe0d1;', 'icon-cross-2' : '&#xe0d2;', 'icon-minus-2' : '&#xe0d3;', 'icon-plus-2' : '&#xe0d4;', 'icon-cross-3' : '&#xe0d5;', 'icon-minus-3' : '&#xe0d6;', 'icon-plus-3' : '&#xe0d7;', 'icon-cross-4' : '&#xe0d8;', 'icon-minus-4' : '&#xe0d9;', 'icon-plus-4' : '&#xe0da;', 'icon-erase' : '&#xe0db;', 'icon-blocked' : '&#xe0dc;', 'icon-info-2' : '&#xe0dd;', 'icon-info-3' : '&#xe0de;', 'icon-question-2' : '&#xe0df;', 'icon-help' : '&#xe0e0;', 'icon-warning-2' : '&#xe0e1;', 'icon-cycle' : '&#xe0e2;', 'icon-cw' : '&#xe0e3;', 'icon-ccw' : '&#xe0e4;', 'icon-shuffle-2' : '&#xe0e5;', 'icon-arrow' : '&#xe0e6;', 'icon-arrow-2' : '&#xe0e7;', 'icon-retweet' : '&#xe0e8;', 'icon-loop-2' : '&#xe0e9;', 'icon-history' : '&#xe0ea;', 'icon-back-2' : '&#xe0eb;', 'icon-switch' : '&#xe0ec;', 'icon-list-3' : '&#xe0ed;', 'icon-add-to-list' : '&#xe0ee;', 'icon-layout' : '&#xe0ef;', 'icon-list-4' : '&#xe0f0;', 'icon-text' : '&#xe0f1;', 'icon-text-2' : '&#xe0f2;', 'icon-document' : '&#xe0f3;', 'icon-docs' : '&#xe0f4;', 'icon-landscape' : '&#xe0f5;', 'icon-pictures' : '&#xe0f6;', 'icon-video' : '&#xe0f7;', 'icon-music-4' : '&#xe0f8;', 'icon-folder' : '&#xe0f9;', 'icon-archive' : '&#xe0fa;', 'icon-trash' : '&#xe0fb;', 'icon-upload' : '&#xe0fc;', 'icon-download-2' : '&#xe0fd;', 'icon-disk' : '&#xe0fe;', 'icon-install' : '&#xe0ff;', 'icon-cloud' : '&#xe100;', 'icon-upload-2' : '&#xe101;', 'icon-bookmark-2' : '&#xe102;', 'icon-bookmarks' : '&#xe103;', 'icon-book-2' : '&#xe104;', 'icon-play' : '&#xe105;', 'icon-pause' : '&#xe106;', 'icon-record' : '&#xe107;', 'icon-stop' : '&#xe108;', 'icon-next' : '&#xe109;', 'icon-previous' : '&#xe10a;', 'icon-first' : '&#xe10b;', 'icon-last' : '&#xe10c;', 'icon-resize-enlarge' : '&#xe10d;', 'icon-resize-shrink' : '&#xe10e;', 'icon-volume-2' : '&#xe10f;', 'icon-sound' : '&#xe110;', 'icon-mute-2' : '&#xe111;', 'icon-flow-cascade' : '&#xe112;', 'icon-flow-branch' : '&#xe113;', 'icon-flow-tree' : '&#xe114;', 'icon-flow-line' : '&#xe115;', 'icon-flow-parallel' : '&#xe116;', 'icon-arrow-left-3' : '&#xe117;', 'icon-arrow-down-2' : '&#xe118;', 'icon-arrow-up--upload' : '&#xe119;', 'icon-arrow-right-3' : '&#xe11a;', 'icon-arrow-left-4' : '&#xe11b;', 'icon-arrow-down-3' : '&#xe11c;', 'icon-arrow-up-2' : '&#xe11d;', 'icon-arrow-right-4' : '&#xe11e;', 'icon-arrow-left-5' : '&#xe11f;', 'icon-arrow-down-4' : '&#xe120;', 'icon-arrow-up-3' : '&#xe121;', 'icon-arrow-right-5' : '&#xe122;', 'icon-arrow-left-6' : '&#xe123;', 'icon-arrow-down-5' : '&#xe124;', 'icon-arrow-up-4' : '&#xe125;', 'icon-arrow-right-6' : '&#xe126;', 'icon-arrow-left-7' : '&#xe127;', 'icon-arrow-down-6' : '&#xe128;', 'icon-arrow-up-5' : '&#xe129;', 'icon-arrow-right-7' : '&#xe12a;', 'icon-arrow-left-8' : '&#xe12b;', 'icon-arrow-down-7' : '&#xe12c;', 'icon-arrow-up-6' : '&#xe12d;', 'icon-arrow-right-8' : '&#xe12e;', 'icon-arrow-left-9' : '&#xe12f;', 'icon-arrow-down-8' : '&#xe130;', 'icon-arrow-up-7' : '&#xe131;', 'icon-untitled-2' : '&#xe132;', 'icon-arrow-left-10' : '&#xe133;', 'icon-arrow-down-9' : '&#xe134;', 'icon-arrow-up-8' : '&#xe135;', 'icon-arrow-right-9' : '&#xe136;', 'icon-menu' : '&#xe137;', 'icon-ellipsis' : '&#xe138;', 'icon-dots' : '&#xe139;', 'icon-dot' : '&#xe13a;', 'icon-cc' : '&#xe13b;', 'icon-cc-by' : '&#xe13c;', 'icon-cc-nc' : '&#xe13d;', 'icon-cc-nc-eu' : '&#xe13e;', 'icon-cc-nc-jp' : '&#xe13f;', 'icon-cc-sa' : '&#xe140;', 'icon-cc-nd' : '&#xe141;', 'icon-cc-pd' : '&#xe142;', 'icon-cc-zero' : '&#xe143;', 'icon-cc-share' : '&#xe144;', 'icon-cc-share-2' : '&#xe145;', 'icon-daniel-bruce' : '&#xe146;', 'icon-daniel-bruce-2' : '&#xe147;', 'icon-github' : '&#xe148;', 'icon-github-2' : '&#xe149;', 'icon-flickr' : '&#xe14a;', 'icon-flickr-2' : '&#xe14b;', 'icon-vimeo' : '&#xe14c;', 'icon-vimeo-2' : '&#xe14d;', 'icon-twitter' : '&#xe14e;', 'icon-twitter-2' : '&#xe14f;', 'icon-facebook' : '&#xe150;', 'icon-facebook-2' : '&#xe151;', 'icon-facebook-3' : '&#xe152;', 'icon-googleplus' : '&#xe153;', 'icon-googleplus-2' : '&#xe154;', 'icon-pinterest' : '&#xe155;', 'icon-pinterest-2' : '&#xe156;', 'icon-tumblr' : '&#xe157;', 'icon-tumblr-2' : '&#xe158;', 'icon-linkedin' : '&#xe159;', 'icon-linkedin-2' : '&#xe15a;', 'icon-dribbble' : '&#xe15b;', 'icon-dribbble-2' : '&#xe15c;', 'icon-stumbleupon' : '&#xe15d;', 'icon-stumbleupon-2' : '&#xe15e;', 'icon-lastfm' : '&#xe15f;', 'icon-lastfm-2' : '&#xe160;', 'icon-rdio' : '&#xe161;', 'icon-rdio-2' : '&#xe162;', 'icon-spotify' : '&#xe163;', 'icon-spotify-2' : '&#xe164;', 'icon-qq' : '&#xe165;', 'icon-instagram' : '&#xe166;', 'icon-dropbox' : '&#xe167;', 'icon-evernote' : '&#xe168;', 'icon-flattr' : '&#xe169;', 'icon-skype' : '&#xe16a;', 'icon-skype-2' : '&#xe16b;', 'icon-renren' : '&#xe16c;', 'icon-sina-weibo' : '&#xe16d;', 'icon-paypal' : '&#xe16e;', 'icon-picasa' : '&#xe16f;', 'icon-soundcloud' : '&#xe170;', 'icon-mixi' : '&#xe171;', 'icon-behance' : '&#xe172;', 'icon-circles' : '&#xe173;', 'icon-vk' : '&#xe174;', 'icon-smashing' : '&#xe175;', 'icon-home-2' : '&#xe176;', 'icon-home-3' : '&#xe177;', 'icon-home-4' : '&#xe178;', 'icon-office' : '&#xe179;', 'icon-newspaper-2' : '&#xe17a;', 'icon-pencil-4' : '&#xe17b;', 'icon-pencil-5' : '&#xe17c;', 'icon-quill' : '&#xe17d;', 'icon-pen' : '&#xe17e;', 'icon-blog' : '&#xe17f;', 'icon-droplet-2' : '&#xe180;', 'icon-paint-format' : '&#xe181;', 'icon-image' : '&#xe182;', 'icon-image-2' : '&#xe183;', 'icon-images' : '&#xe184;', 'icon-camera-3' : '&#xe185;', 'icon-music-5' : '&#xe186;', 'icon-headphones' : '&#xe187;', 'icon-play-2' : '&#xe188;', 'icon-film' : '&#xe189;', 'icon-camera-4' : '&#xe18a;', 'icon-dice' : '&#xe18b;', 'icon-pacman' : '&#xe18c;', 'icon-spades' : '&#xe18d;', 'icon-clubs' : '&#xe18e;', 'icon-diamonds' : '&#xe18f;', 'icon-pawn' : '&#xe190;', 'icon-bullhorn' : '&#xe191;', 'icon-connection' : '&#xe192;', 'icon-podcast' : '&#xe193;', 'icon-feed-2' : '&#xe194;', 'icon-book-3' : '&#xe195;', 'icon-books' : '&#xe196;', 'icon-library' : '&#xe197;', 'icon-file' : '&#xe198;', 'icon-profile' : '&#xe199;', 'icon-file-2' : '&#xe19a;', 'icon-file-3' : '&#xe19b;', 'icon-file-4' : '&#xe19c;', 'icon-copy' : '&#xe19d;', 'icon-copy-2' : '&#xe19e;', 'icon-copy-3' : '&#xe19f;', 'icon-paste' : '&#xe1a0;', 'icon-paste-2' : '&#xe1a1;', 'icon-paste-3' : '&#xe1a2;', 'icon-stack' : '&#xe1a3;', 'icon-folder-2' : '&#xe1a4;', 'icon-folder-open' : '&#xe1a5;', 'icon-tag-3' : '&#xe1a6;', 'icon-tags' : '&#xe1a7;', 'icon-barcode' : '&#xe1a8;', 'icon-qrcode' : '&#xe1a9;', 'icon-ticket-2' : '&#xe1aa;', 'icon-cart-2' : '&#xe1ab;', 'icon-cart-3' : '&#xe1ac;', 'icon-cart-4' : '&#xe1ad;', 'icon-coin' : '&#xe1ae;', 'icon-credit' : '&#xe1af;', 'icon-calculate' : '&#xe1b0;', 'icon-support' : '&#xe1b1;', 'icon-phone-3' : '&#xe1b2;', 'icon-phone-hang-up' : '&#xe1b3;', 'icon-address-book' : '&#xe1b4;', 'icon-notebook' : '&#xe1b5;', 'icon-envelop' : '&#xe1b6;', 'icon-pushpin' : '&#xe1b7;', 'icon-location-4' : '&#xe1b8;', 'icon-location-5' : '&#xe1b9;', 'icon-compass-3' : '&#xe1ba;', 'icon-map-2' : '&#xe1bb;', 'icon-map-3' : '&#xe1bc;', 'icon-history-2' : '&#xe1bd;', 'icon-clock-3' : '&#xe1be;', 'icon-clock-4' : '&#xe1bf;', 'icon-alarm' : '&#xe1c0;', 'icon-alarm-2' : '&#xe1c1;', 'icon-bell-2' : '&#xe1c2;', 'icon-stopwatch' : '&#xe1c3;', 'icon-calendar-3' : '&#xe1c4;', 'icon-calendar-4' : '&#xe1c5;', 'icon-print' : '&#xe1c6;', 'icon-keyboard-2' : '&#xe1c7;', 'icon-screen-2' : '&#xe1c8;', 'icon-laptop' : '&#xe1c9;', 'icon-mobile-3' : '&#xe1ca;', 'icon-mobile-4' : '&#xe1cb;', 'icon-tablet' : '&#xe1cc;', 'icon-tv' : '&#xe1cd;', 'icon-cabinet' : '&#xe1ce;', 'icon-drawer-2' : '&#xe1cf;', 'icon-drawer-3' : '&#xe1d0;', 'icon-drawer-4' : '&#xe1d1;', 'icon-box-add' : '&#xe1d2;', 'icon-box-remove' : '&#xe1d3;', 'icon-download-3' : '&#xe1d4;', 'icon-upload-3' : '&#xe1d5;', 'icon-disk-2' : '&#xe1d6;', 'icon-storage' : '&#xe1d7;', 'icon-undo' : '&#xe1d8;', 'icon-redo' : '&#xe1d9;', 'icon-flip' : '&#xe1da;', 'icon-flip-2' : '&#xe1db;', 'icon-undo-2' : '&#xe1dc;', 'icon-redo-2' : '&#xe1dd;', 'icon-forward-3' : '&#xe1de;', 'icon-reply-2' : '&#xe1df;', 'icon-bubble' : '&#xe1e0;', 'icon-bubbles' : '&#xe1e1;', 'icon-bubbles-2' : '&#xe1e2;', 'icon-bubble-2' : '&#xe1e3;', 'icon-bubbles-3' : '&#xe1e4;', 'icon-bubbles-4' : '&#xe1e5;', 'icon-user-3' : '&#xe1e6;', 'icon-users-3' : '&#xe1e7;', 'icon-user-4' : '&#xe1e8;', 'icon-users-4' : '&#xe1e9;', 'icon-user-5' : '&#xe1ea;', 'icon-user-6' : '&#xe1eb;', 'icon-quotes-left' : '&#xe1ec;', 'icon-busy' : '&#xe1ed;', 'icon-spinner' : '&#xe1ee;', 'icon-spinner-2' : '&#xe1ef;', 'icon-spinner-3' : '&#xe1f0;', 'icon-spinner-4' : '&#xe1f1;', 'icon-spinner-5' : '&#xe1f2;', 'icon-spinner-6' : '&#xe1f3;', 'icon-binoculars' : '&#xe1f4;', 'icon-search-3' : '&#xe1f5;', 'icon-zoom-in-2' : '&#xe1f6;', 'icon-zoom-out-2' : '&#xe1f7;', 'icon-expand-2' : '&#xe1f8;', 'icon-contract' : '&#xe1f9;', 'icon-expand-3' : '&#xe1fa;', 'icon-contract-2' : '&#xe1fb;', 'icon-key-3' : '&#xe1fc;', 'icon-key-4' : '&#xe1fd;', 'icon-lock-2' : '&#xe1fe;', 'icon-lock-3' : '&#xe1ff;', 'icon-unlocked-2' : '&#xe200;', 'icon-wrench-2' : '&#xe201;', 'icon-settings' : '&#xe202;', 'icon-equalizer' : '&#xe203;', 'icon-cog-3' : '&#xe204;', 'icon-cogs' : '&#xe205;', 'icon-cog-4' : '&#xe206;', 'icon-hammer' : '&#xe207;', 'icon-wand' : '&#xe208;', 'icon-aid' : '&#xe209;', 'icon-bug' : '&#xe20a;', 'icon-pie-2' : '&#xe20b;', 'icon-stats-2' : '&#xe20c;', 'icon-bars-3' : '&#xe20d;', 'icon-bars-4' : '&#xe20e;', 'icon-gift' : '&#xe20f;', 'icon-trophy-2' : '&#xe210;', 'icon-glass' : '&#xe211;', 'icon-mug' : '&#xe212;', 'icon-food' : '&#xe213;', 'icon-leaf-2' : '&#xe214;', 'icon-rocket-2' : '&#xe215;', 'icon-meter' : '&#xe216;', 'icon-meter2' : '&#xe217;', 'icon-dashboard' : '&#xe218;', 'icon-hammer-2' : '&#xe219;', 'icon-fire' : '&#xe21a;', 'icon-lab' : '&#xe21b;', 'icon-magnet-2' : '&#xe21c;', 'icon-remove' : '&#xe21d;', 'icon-remove-2' : '&#xe21e;', 'icon-briefcase-2' : '&#xe21f;', 'icon-airplane-2' : '&#xe220;', 'icon-truck' : '&#xe221;', 'icon-road' : '&#xe222;', 'icon-accessibility' : '&#xe223;', 'icon-target-2' : '&#xe224;', 'icon-shield' : '&#xe225;', 'icon-lightning' : '&#xe226;', 'icon-switch-2' : '&#xe227;', 'icon-power-cord' : '&#xe228;', 'icon-signup' : '&#xe229;', 'icon-list-5' : '&#xe22a;', 'icon-list-6' : '&#xe22b;', 'icon-numbered-list' : '&#xe22c;', 'icon-menu-2' : '&#xe22d;', 'icon-menu-3' : '&#xe22e;', 'icon-tree' : '&#xe22f;', 'icon-cloud-2' : '&#xe230;', 'icon-cloud-download' : '&#xe231;', 'icon-cloud-upload' : '&#xe232;', 'icon-download-4' : '&#xe233;', 'icon-upload-4' : '&#xe234;', 'icon-download-5' : '&#xe235;', 'icon-upload-5' : '&#xe236;', 'icon-globe-3' : '&#xe237;', 'icon-earth-2' : '&#xe238;', 'icon-link-2' : '&#xe239;', 'icon-flag-3' : '&#xe23a;', 'icon-attachment' : '&#xe23b;', 'icon-eye-3' : '&#xe23c;', 'icon-eye-blocked' : '&#xe23d;', 'icon-eye-4' : '&#xe23e;', 'icon-bookmark-3' : '&#xe23f;', 'icon-bookmarks-2' : '&#xe240;', 'icon-brightness-medium' : '&#xe241;', 'icon-brightness-contrast' : '&#xe242;', 'icon-contrast-2' : '&#xe243;', 'icon-star-4' : '&#xe244;', 'icon-star-5' : '&#xe245;', 'icon-star-6' : '&#xe246;', 'icon-heart-4' : '&#xe247;', 'icon-heart-5' : '&#xe248;', 'icon-heart-broken' : '&#xe249;', 'icon-thumbs-up-3' : '&#xe24a;', 'icon-thumbs-up-4' : '&#xe24b;', 'icon-happy' : '&#xe24c;', 'icon-happy-2' : '&#xe24d;', 'icon-smiley' : '&#xe24e;', 'icon-smiley-2' : '&#xe24f;', 'icon-tongue' : '&#xe250;', 'icon-tongue-2' : '&#xe251;', 'icon-sad' : '&#xe252;', 'icon-sad-2' : '&#xe253;', 'icon-wink' : '&#xe254;', 'icon-wink-2' : '&#xe255;', 'icon-grin' : '&#xe256;', 'icon-grin-2' : '&#xe257;', 'icon-cool' : '&#xe258;', 'icon-cool-2' : '&#xe259;', 'icon-angry' : '&#xe25a;', 'icon-angry-2' : '&#xe25b;', 'icon-evil' : '&#xe25c;', 'icon-evil-2' : '&#xe25d;', 'icon-shocked' : '&#xe25e;', 'icon-shocked-2' : '&#xe25f;', 'icon-confused' : '&#xe260;', 'icon-confused-2' : '&#xe261;', 'icon-neutral' : '&#xe262;', 'icon-neutral-2' : '&#xe263;', 'icon-wondering' : '&#xe264;', 'icon-wondering-2' : '&#xe265;', 'icon-point-up' : '&#xe266;', 'icon-point-right' : '&#xe267;', 'icon-point-down' : '&#xe268;', 'icon-point-left' : '&#xe269;', 'icon-warning-3' : '&#xe26a;', 'icon-notification' : '&#xe26b;', 'icon-question-3' : '&#xe26c;', 'icon-info-4' : '&#xe26d;', 'icon-info-5' : '&#xe26e;', 'icon-blocked-2' : '&#xe26f;', 'icon-cancel-circle' : '&#xe270;', 'icon-checkmark-circle' : '&#xe271;', 'icon-spam' : '&#xe272;', 'icon-close' : '&#xe273;', 'icon-checkmark-3' : '&#xe274;', 'icon-checkmark-4' : '&#xe275;', 'icon-spell-check' : '&#xe276;', 'icon-minus-5' : '&#xe277;', 'icon-plus-5' : '&#xe278;', 'icon-enter' : '&#xe279;', 'icon-exit' : '&#xe27a;', 'icon-play-3' : '&#xe27b;', 'icon-pause-2' : '&#xe27c;', 'icon-stop-2' : '&#xe27d;', 'icon-backward' : '&#xe27e;', 'icon-forward-4' : '&#xe27f;', 'icon-play-4' : '&#xe280;', 'icon-pause-3' : '&#xe281;', 'icon-stop-3' : '&#xe282;', 'icon-backward-2' : '&#xe283;', 'icon-forward-5' : '&#xe284;', 'icon-first-2' : '&#xe285;', 'icon-last-2' : '&#xe286;', 'icon-previous-2' : '&#xe287;', 'icon-next-2' : '&#xe288;', 'icon-eject-2' : '&#xe289;', 'icon-volume-high' : '&#xe28a;', 'icon-volume-medium' : '&#xe28b;', 'icon-volume-low' : '&#xe28c;', 'icon-volume-mute' : '&#xe28d;', 'icon-volume-mute-2' : '&#xe28e;', 'icon-volume-increase' : '&#xe28f;', 'icon-volume-decrease' : '&#xe290;', 'icon-loop-3' : '&#xe291;', 'icon-loop-4' : '&#xe292;', 'icon-loop-5' : '&#xe293;', 'icon-shuffle-3' : '&#xe294;', 'icon-arrow-up-left' : '&#xe295;', 'icon-arrow-up-9' : '&#xe296;', 'icon-arrow-up-right' : '&#xe297;', 'icon-arrow-right-10' : '&#xe298;', 'icon-arrow-down-right' : '&#xe299;', 'icon-arrow-down-10' : '&#xe29a;', 'icon-arrow-down-left' : '&#xe29b;', 'icon-arrow-left-11' : '&#xe29c;', 'icon-arrow-up-left-2' : '&#xe29d;', 'icon-arrow-up-10' : '&#xe29e;', 'icon-arrow-up-right-2' : '&#xe29f;', 'icon-arrow-right-11' : '&#xe2a0;', 'icon-arrow-down-right-2' : '&#xe2a1;', 'icon-arrow-down-11' : '&#xe2a2;', 'icon-arrow-down-left-2' : '&#xe2a3;', 'icon-arrow-left-12' : '&#xe2a4;', 'icon-arrow-up-left-3' : '&#xe2a5;', 'icon-arrow-up-11' : '&#xe2a6;', 'icon-arrow-up-right-3' : '&#xe2a7;', 'icon-arrow-right-12' : '&#xe2a8;', 'icon-arrow-down-right-3' : '&#xe2a9;', 'icon-arrow-down-12' : '&#xe2aa;', 'icon-arrow-down-left-3' : '&#xe2ab;', 'icon-arrow-left-13' : '&#xe2ac;', 'icon-tab' : '&#xe2ad;', 'icon-checkbox-checked' : '&#xe2ae;', 'icon-checkbox-unchecked' : '&#xe2af;', 'icon-checkbox-partial' : '&#xe2b0;', 'icon-radio-checked' : '&#xe2b1;', 'icon-radio-unchecked' : '&#xe2b2;', 'icon-crop' : '&#xe2b3;', 'icon-scissors-2' : '&#xe2b4;', 'icon-filter' : '&#xe2b5;', 'icon-filter-2' : '&#xe2b6;', 'icon-font' : '&#xe2b7;', 'icon-text-height' : '&#xe2b8;', 'icon-text-width' : '&#xe2b9;', 'icon-bold' : '&#xe2ba;', 'icon-underline' : '&#xe2bb;', 'icon-italic' : '&#xe2bc;', 'icon-strikethrough' : '&#xe2bd;', 'icon-omega' : '&#xe2be;', 'icon-sigma' : '&#xe2bf;', 'icon-table' : '&#xe2c0;', 'icon-table-2' : '&#xe2c1;', 'icon-insert-template' : '&#xe2c2;', 'icon-pilcrow' : '&#xe2c3;', 'icon-left-to-right' : '&#xe2c4;', 'icon-right-to-left' : '&#xe2c5;', 'icon-paragraph-left' : '&#xe2c6;', 'icon-paragraph-center' : '&#xe2c7;', 'icon-paragraph-right' : '&#xe2c8;', 'icon-paragraph-justify' : '&#xe2c9;', 'icon-paragraph-left-2' : '&#xe2ca;', 'icon-paragraph-center-2' : '&#xe2cb;', 'icon-paragraph-right-2' : '&#xe2cc;', 'icon-paragraph-justify-2' : '&#xe2cd;', 'icon-indent-increase' : '&#xe2ce;', 'icon-indent-decrease' : '&#xe2cf;', 'icon-new-tab' : '&#xe2d0;', 'icon-embed' : '&#xe2d1;', 'icon-code-2' : '&#xe2d2;', 'icon-console' : '&#xe2d3;', 'icon-share-2' : '&#xe2d4;', 'icon-mail-3' : '&#xe2d5;', 'icon-mail-4' : '&#xe2d6;', 'icon-mail-5' : '&#xe2d7;', 'icon-mail-6' : '&#xe2d8;', 'icon-google' : '&#xe2d9;', 'icon-google-plus' : '&#xe2da;', 'icon-google-plus-2' : '&#xe2db;', 'icon-google-plus-3' : '&#xe2dc;', 'icon-google-plus-4' : '&#xe2dd;', 'icon-google-drive' : '&#xe2de;', 'icon-facebook-4' : '&#xe2df;', 'icon-facebook-5' : '&#xe2e0;', 'icon-facebook-6' : '&#xe2e1;', 'icon-instagram-2' : '&#xe2e2;', 'icon-twitter-3' : '&#xe2e3;', 'icon-twitter-4' : '&#xe2e4;', 'icon-twitter-5' : '&#xe2e5;', 'icon-feed-3' : '&#xe2e6;', 'icon-feed-4' : '&#xe2e7;', 'icon-feed-5' : '&#xe2e8;', 'icon-youtube' : '&#xe2e9;', 'icon-youtube-2' : '&#xe2ea;', 'icon-vimeo-3' : '&#xe2eb;', 'icon-vimeo2' : '&#xe2ec;', 'icon-vimeo-4' : '&#xe2ed;', 'icon-lanyrd' : '&#xe2ee;', 'icon-flickr-3' : '&#xe2ef;', 'icon-flickr-4' : '&#xe2f0;', 'icon-flickr-5' : '&#xe2f1;', 'icon-flickr-6' : '&#xe2f2;', 'icon-picassa' : '&#xe2f3;', 'icon-picassa-2' : '&#xe2f4;', 'icon-dribbble-3' : '&#xe2f5;', 'icon-dribbble-4' : '&#xe2f6;', 'icon-dribbble-5' : '&#xe2f7;', 'icon-forrst' : '&#xe2f8;', 'icon-forrst-2' : '&#xe2f9;', 'icon-deviantart' : '&#xe2fa;', 'icon-deviantart-2' : '&#xe2fb;', 'icon-steam' : '&#xe2fc;', 'icon-steam-2' : '&#xe2fd;', 'icon-github-3' : '&#xe2fe;', 'icon-github-4' : '&#xe2ff;', 'icon-github-5' : '&#xe300;', 'icon-github-6' : '&#xe301;', 'icon-github-7' : '&#xe302;', 'icon-wordpress' : '&#xe303;', 'icon-wordpress-2' : '&#xe304;', 'icon-joomla' : '&#xe305;', 'icon-blogger' : '&#xe306;', 'icon-blogger-2' : '&#xe307;', 'icon-tumblr-3' : '&#xe308;', 'icon-tumblr-4' : '&#xe309;', 'icon-yahoo' : '&#xe30a;', 'icon-tux' : '&#xe30b;', 'icon-apple' : '&#xe30c;', 'icon-finder' : '&#xe30d;', 'icon-android' : '&#xe30e;', 'icon-windows' : '&#xe30f;', 'icon-windows8' : '&#xe310;', 'icon-soundcloud-2' : '&#xe311;', 'icon-soundcloud-3' : '&#xe312;', 'icon-skype-3' : '&#xe313;', 'icon-reddit' : '&#xe314;', 'icon-linkedin-3' : '&#xe315;', 'icon-lastfm-3' : '&#xe316;', 'icon-lastfm-4' : '&#xe317;', 'icon-delicious' : '&#xe318;', 'icon-stumbleupon-3' : '&#xe319;', 'icon-stumbleupon-4' : '&#xe31a;', 'icon-stackoverflow' : '&#xe31b;', 'icon-pinterest-3' : '&#xe31c;', 'icon-pinterest-4' : '&#xe31d;', 'icon-xing' : '&#xe31e;', 'icon-xing-2' : '&#xe31f;', 'icon-flattr-2' : '&#xe320;', 'icon-foursquare' : '&#xe321;', 'icon-foursquare-2' : '&#xe322;', 'icon-paypal-2' : '&#xe323;', 'icon-paypal-3' : '&#xe324;', 'icon-paypal-4' : '&#xe325;', 'icon-yelp' : '&#xe326;', 'icon-libreoffice' : '&#xe327;', 'icon-file-pdf' : '&#xe328;', 'icon-file-openoffice' : '&#xe329;', 'icon-file-word' : '&#xe32a;', 'icon-file-excel' : '&#xe32b;', 'icon-file-zip' : '&#xe32c;', 'icon-file-powerpoint' : '&#xe32d;', 'icon-file-xml' : '&#xe32e;', 'icon-file-css' : '&#xe32f;', 'icon-html5' : '&#xe330;', 'icon-html5-2' : '&#xe331;', 'icon-css3' : '&#xe332;', 'icon-chrome' : '&#xe333;', 'icon-firefox' : '&#xe334;', 'icon-IE' : '&#xe335;', 'icon-opera' : '&#xe336;', 'icon-safari' : '&#xe337;', 'icon-IcoMoon' : '&#xe338;', 'icon-warning-4' : '&#xe339;', 'icon-cloud-3' : '&#xe33a;', 'icon-locked-2' : '&#xe33b;', 'icon-inbox' : '&#xe33c;', 'icon-comment-3' : '&#xe33d;', 'icon-mic' : '&#xe33e;', 'icon-envelope' : '&#xe33f;', 'icon-briefcase-3' : '&#xe340;', 'icon-cart-5' : '&#xe341;', 'icon-contrast-3' : '&#xe342;', 'icon-clock-5' : '&#xe343;', 'icon-user-7' : '&#xe344;', 'icon-cog-5' : '&#xe345;', 'icon-music-6' : '&#xe346;', 'icon-twitter-6' : '&#xe347;', 'icon-pencil-6' : '&#xe348;', 'icon-frame' : '&#xe349;', 'icon-switch-3' : '&#xe34a;', 'icon-star-7' : '&#xe34b;', 'icon-key-5' : '&#xe34c;', 'icon-chart-2' : '&#xe34d;', 'icon-apple-2' : '&#xe34e;', 'icon-file-5' : '&#xe34f;', 'icon-plus-6' : '&#xe350;', 'icon-minus-6' : '&#xe351;', 'icon-picture' : '&#xe352;', 'icon-folder-3' : '&#xe353;', 'icon-camera-5' : '&#xe354;', 'icon-search-4' : '&#xe355;', 'icon-dribbble-6' : '&#xe356;', 'icon-forrst-3' : '&#xe357;', 'icon-feed-6' : '&#xe358;', 'icon-blocked-3' : '&#xe359;', 'icon-target-3' : '&#xe35a;', 'icon-play-5' : '&#xe35b;', 'icon-pause-4' : '&#xe35c;', 'icon-bug-2' : '&#xe35d;', 'icon-console-2' : '&#xe35e;', 'icon-film-2' : '&#xe35f;', 'icon-type' : '&#xe360;', 'icon-home-5' : '&#xe361;', 'icon-earth-3' : '&#xe362;', 'icon-location-6' : '&#xe363;', 'icon-info-6' : '&#xe364;', 'icon-eye-5' : '&#xe365;', 'icon-heart-6' : '&#xe366;', 'icon-bookmark-4' : '&#xe367;', 'icon-wrench-3' : '&#xe368;', 'icon-calendar-5' : '&#xe369;', 'icon-window' : '&#xe36a;', 'icon-monitor' : '&#xe36b;', 'icon-mobile-5' : '&#xe36c;', 'icon-droplet-3' : '&#xe36d;', 'icon-mouse-2' : '&#xe36e;', 'icon-refresh-3' : '&#xe36f;', 'icon-location-7' : '&#xe370;', 'icon-tag-4' : '&#xe371;', 'icon-phone-4' : '&#xe372;', 'icon-star-8' : '&#xe373;', 'icon-pointer' : '&#xe374;', 'icon-thumbs-up-5' : '&#xe375;', 'icon-thumbs-down-3' : '&#xe376;', 'icon-headphones-2' : '&#xe377;', 'icon-move-2' : '&#xe378;', 'icon-checkmark-5' : '&#xe379;', 'icon-cancel-2' : '&#xe37a;', 'icon-skype-4' : '&#xe37b;', 'icon-gift-2' : '&#xe37c;', 'icon-cone-2' : '&#xe37d;', 'icon-alarm-3' : '&#xe37e;', 'icon-coffee' : '&#xe37f;', 'icon-basket' : '&#xe380;', 'icon-flag-4' : '&#xe381;', 'icon-ipod' : '&#xe382;', 'icon-trashcan-2' : '&#xe383;', 'icon-bolt-2' : '&#xe384;', 'icon-ampersand' : '&#xe385;', 'icon-compass-4' : '&#xe386;', 'icon-list-7' : '&#xe387;', 'icon-grid-2' : '&#xe388;', 'icon-volume-3' : '&#xe389;', 'icon-volume-4' : '&#xe38a;', 'icon-stats-3' : '&#xe38b;', 'icon-target-4' : '&#xe38c;', 'icon-forward-6' : '&#xe38d;', 'icon-paperclip-2' : '&#xe38e;', 'icon-keyboard-3' : '&#xe38f;', 'icon-crop-2' : '&#xe390;', 'icon-floppy' : '&#xe391;', 'icon-filter-3' : '&#xe392;', 'icon-trophy-3' : '&#xe393;', 'icon-diary' : '&#xe394;', 'icon-address-book-2' : '&#xe395;', 'icon-stop-4' : '&#xe396;', 'icon-smiley-3' : '&#xe397;', 'icon-shit' : '&#xe398;', 'icon-bookmark-5' : '&#xe399;', 'icon-camera-6' : '&#xe39a;', 'icon-lamp' : '&#xe39b;', 'icon-disk-3' : '&#xe39c;', 'icon-button' : '&#xe39d;', 'icon-database-2' : '&#xe39e;', 'icon-credit-card-2' : '&#xe39f;', 'icon-atom' : '&#xe3a0;', 'icon-winsows' : '&#xe3a1;', 'icon-target-5' : '&#xe3a2;', 'icon-battery-3' : '&#xe3a3;', 'icon-code-3' : '&#xe3a4;', 'icon-sunrise' : '&#xe3a5;', 'icon-sun-4' : '&#xe3a6;', 'icon-moon-2' : '&#xe3a7;', 'icon-sun-5' : '&#xe3a8;', 'icon-windy' : '&#xe3a9;', 'icon-wind' : '&#xe3aa;', 'icon-snowflake' : '&#xe3ab;', 'icon-cloudy' : '&#xe3ac;', 'icon-cloud-4' : '&#xe3ad;', 'icon-weather' : '&#xe3ae;', 'icon-weather-2' : '&#xe3af;', 'icon-weather-3' : '&#xe3b0;', 'icon-lines' : '&#xe3b1;', 'icon-cloud-5' : '&#xe3b2;', 'icon-lightning-2' : '&#xe3b3;', 'icon-lightning-3' : '&#xe3b4;', 'icon-rainy' : '&#xe3b5;', 'icon-rainy-2' : '&#xe3b6;', 'icon-windy-2' : '&#xe3b7;', 'icon-windy-3' : '&#xe3b8;', 'icon-snowy' : '&#xe3b9;', 'icon-snowy-2' : '&#xe3ba;', 'icon-snowy-3' : '&#xe3bb;', 'icon-weather-4' : '&#xe3bc;', 'icon-cloudy-2' : '&#xe3bd;', 'icon-cloud-6' : '&#xe3be;', 'icon-lightning-4' : '&#xe3bf;', 'icon-sun-6' : '&#xe3c0;', 'icon-moon-3' : '&#xe3c1;', 'icon-cloudy-3' : '&#xe3c2;', 'icon-cloud-7' : '&#xe3c3;', 'icon-cloud-8' : '&#xe3c4;', 'icon-lightning-5' : '&#xe3c5;', 'icon-rainy-3' : '&#xe3c6;', 'icon-rainy-4' : '&#xe3c7;', 'icon-windy-4' : '&#xe3c8;', 'icon-windy-5' : '&#xe3c9;', 'icon-snowy-4' : '&#xe3ca;', 'icon-snowy-5' : '&#xe3cb;', 'icon-weather-5' : '&#xe3cc;', 'icon-cloudy-4' : '&#xe3cd;', 'icon-lightning-6' : '&#xe3ce;', 'icon-thermometer-2' : '&#xe3cf;', 'icon-compass-5' : '&#xe3d0;', 'icon-none' : '&#xe3d1;', 'icon-Celsius' : '&#xe3d2;', 'icon-Fahrenheit' : '&#xe3d3;', 'icon-chat-3' : '&#xe3d4;', 'icon-chat-alt-stroke' : '&#xe3d5;', 'icon-chat-alt-fill' : '&#xe3d6;', 'icon-comment-alt1-stroke' : '&#xe3d7;', 'icon-comment-alt1-fill' : '&#xe3d8;', 'icon-comment-stroke' : '&#xe3d9;', 'icon-comment-fill' : '&#xe3da;', 'icon-comment-alt2-stroke' : '&#xe3db;', 'icon-comment-alt2-fill' : '&#xe3dc;', 'icon-checkmark-6' : '&#xe3dd;', 'icon-check-alt' : '&#xe3de;', 'icon-x' : '&#xe3df;', 'icon-x-altx-alt' : '&#xe3e0;', 'icon-denied' : '&#xe3e1;', 'icon-cursor' : '&#xe3e2;', 'icon-rss-2' : '&#xe3e3;', 'icon-rss-alt' : '&#xe3e4;', 'icon-wrench-4' : '&#xe3e5;', 'icon-dial' : '&#xe3e6;', 'icon-cog-6' : '&#xe3e7;', 'icon-calendar-6' : '&#xe3e8;', 'icon-calendar-alt-stroke' : '&#xe3e9;', 'icon-calendar-alt-fill' : '&#xe3ea;', 'icon-share-3' : '&#xe3eb;', 'icon-mail-7' : '&#xe3ec;', 'icon-heart-stroke' : '&#xe3ed;', 'icon-heart-fill' : '&#xe3ee;', 'icon-movie' : '&#xe3ef;', 'icon-document-alt-stroke' : '&#xe3f0;', 'icon-document-alt-fill' : '&#xe3f1;', 'icon-document-stroke' : '&#xe3f2;', 'icon-document-fill' : '&#xe3f3;', 'icon-plus-7' : '&#xe3f4;', 'icon-plus-alt' : '&#xe3f5;', 'icon-minus-7' : '&#xe3f6;', 'icon-minus-alt' : '&#xe3f7;', 'icon-pin-2' : '&#xe3f8;', 'icon-link-3' : '&#xe3f9;', 'icon-bolt-3' : '&#xe3fa;', 'icon-move-3' : '&#xe3fb;', 'icon-move-alt1' : '&#xe3fc;', 'icon-move-alt2' : '&#xe3fd;', 'icon-equalizer-2' : '&#xe3fe;', 'icon-award-fill' : '&#xe3ff;', 'icon-award-stroke' : '&#xe400;', 'icon-magnifying-glass' : '&#xe401;', 'icon-trash-stroke' : '&#xe402;', 'icon-trash-fill' : '&#xe403;', 'icon-beaker-alt' : '&#xe404;', 'icon-beaker' : '&#xe405;', 'icon-key-stroke' : '&#xe406;', 'icon-key-fill' : '&#xe407;', 'icon-new-window' : '&#xe408;', 'icon-lightbulb' : '&#xe409;', 'icon-spin-alt' : '&#xe40a;', 'icon-spin' : '&#xe40b;', 'icon-curved-arrow' : '&#xe40c;', 'icon-undo-3' : '&#xe40d;', 'icon-reload' : '&#xe40e;', 'icon-reload-alt' : '&#xe40f;', 'icon-loop-6' : '&#xe410;', 'icon-loop-alt1' : '&#xe411;', 'icon-loop-alt2' : '&#xe412;', 'icon-loop-alt3' : '&#xe413;', 'icon-loop-alt4' : '&#xe414;', 'icon-transfer' : '&#xe415;', 'icon-move-vertical' : '&#xe416;', 'icon-move-vertical-alt1' : '&#xe417;', 'icon-move-vertical-alt2' : '&#xe418;', 'icon-move-horizontal' : '&#xe419;', 'icon-move-horizontal-alt1' : '&#xe41a;', 'icon-move-horizontal-alt2' : '&#xe41b;', 'icon-arrow-left-14' : '&#xe41c;', 'icon-arrow-left-alt1' : '&#xe41d;', 'icon-arrow-left-alt2' : '&#xe41e;', 'icon-arrow-right-13' : '&#xe41f;', 'icon-arrow-right-alt1' : '&#xe420;', 'icon-arrow-right-alt2' : '&#xe421;', 'icon-arrow-up-12' : '&#xe422;', 'icon-arrow-up-alt1' : '&#xe423;', 'icon-arrow-up-alt2' : '&#xe424;', 'icon-arrow-down-13' : '&#xe425;', 'icon-arrow-down-alt1' : '&#xe426;', 'icon-arrow-down-alt2' : '&#xe427;', 'icon-cd-2' : '&#xe428;', 'icon-steering-wheel' : '&#xe429;', 'icon-microphone-3' : '&#xe42a;', 'icon-headphones-3' : '&#xe42b;', 'icon-volume-5' : '&#xe42c;', 'icon-volume-mute-3' : '&#xe42d;', 'icon-play-6' : '&#xe42e;', 'icon-pause-5' : '&#xe42f;', 'icon-stop-5' : '&#xe430;', 'icon-eject-3' : '&#xe431;', 'icon-first-3' : '&#xe432;', 'icon-last-3' : '&#xe433;', 'icon-play-alt' : '&#xe434;', 'icon-fullscreen-exit' : '&#xe435;', 'icon-fullscreen-exit-alt' : '&#xe436;', 'icon-fullscreen' : '&#xe437;', 'icon-fullscreen-alt' : '&#xe438;', 'icon-iphone' : '&#xe439;', 'icon-battery-empty' : '&#xe43a;', 'icon-battery-half' : '&#xe43b;', 'icon-battery-full-2' : '&#xe43c;', 'icon-battery-charging-2' : '&#xe43d;', 'icon-compass-6' : '&#xe43e;', 'icon-box-2' : '&#xe43f;', 'icon-folder-stroke' : '&#xe440;', 'icon-folder-fill' : '&#xe441;', 'icon-at' : '&#xe442;', 'icon-ampersand-2' : '&#xe443;', 'icon-info-7' : '&#xe444;', 'icon-question-mark' : '&#xe445;', 'icon-pilcrow-2' : '&#xe446;', 'icon-hash' : '&#xe447;', 'icon-left-quote' : '&#xe448;', 'icon-right-quote' : '&#xe449;', 'icon-left-quote-alt' : '&#xe44a;', 'icon-right-quote-alt' : '&#xe44b;', 'icon-article' : '&#xe44c;', 'icon-read-more' : '&#xe44d;', 'icon-list-8' : '&#xe44e;', 'icon-list-nested' : '&#xe44f;', 'icon-book-4' : '&#xe450;', 'icon-book-alt' : '&#xe451;', 'icon-book-alt2' : '&#xe452;', 'icon-pen-2' : '&#xe453;', 'icon-pen-alt-stroke' : '&#xe454;', 'icon-pen-alt-fill' : '&#xe455;', 'icon-pen-alt2' : '&#xe456;', 'icon-brush-2' : '&#xe457;', 'icon-brush-alt' : '&#xe458;', 'icon-eyedropper' : '&#xe459;', 'icon-layers-alt' : '&#xe45a;', 'icon-layers' : '&#xe45b;', 'icon-image-3' : '&#xe45c;', 'icon-camera-7' : '&#xe45d;', 'icon-aperture' : '&#xe45e;', 'icon-aperture-alt' : '&#xe45f;', 'icon-chart-3' : '&#xe460;', 'icon-chart-alt' : '&#xe461;', 'icon-bars-5' : '&#xe462;', 'icon-bars-alt' : '&#xe463;', 'icon-eye-6' : '&#xe464;', 'icon-user-8' : '&#xe465;', 'icon-home-6' : '&#xe466;', 'icon-clock-6' : '&#xe467;', 'icon-lock-stroke' : '&#xe468;', 'icon-lock-fill' : '&#xe469;', 'icon-unlock-stroke' : '&#xe46a;', 'icon-unlock-fill' : '&#xe46b;', 'icon-tag-stroke' : '&#xe46c;', 'icon-tag-fill' : '&#xe46d;', 'icon-sun-stroke' : '&#xe46e;', 'icon-sun-fill' : '&#xe46f;', 'icon-moon-stroke' : '&#xe470;', 'icon-moon-fill' : '&#xe471;', 'icon-cloud-9' : '&#xe472;', 'icon-rain' : '&#xe473;', 'icon-umbrella' : '&#xe474;', 'icon-star-9' : '&#xe475;', 'icon-map-pin-stroke' : '&#xe476;', 'icon-map-pin-fill' : '&#xe477;', 'icon-map-pin-alt' : '&#xe478;', 'icon-target-6' : '&#xe479;', 'icon-download-6' : '&#xe47a;', 'icon-upload-6' : '&#xe47b;', 'icon-cloud-download-2' : '&#xe47c;', 'icon-cloud-upload-2' : '&#xe47d;', 'icon-fork' : '&#xe47e;', 'icon-paperclip-3' : '&#xe47f;' }, els = document.getElementsByTagName('*'), i, attr, html, c, el; for (i = 0; i < els.length; i += 1) { el = els[i]; attr = el.getAttribute('data-icon'); if (attr) { addIcon(el, attr); } c = el.className; c = c.match(/icon-[^\s'"]+/); if (c && icons[c[0]]) { addIcon(el, icons[c[0]]); } } };
JavaScript
/** * @summary DataTables * @description Paginate, search and sort HTML tables * @version 1.9.4 * @file jquery.dataTables.js * @author Allan Jardine (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * * @copyright Copyright 2008-2012 Allan Jardine, all rights reserved. * * This source file is free software, under either the GPL v2 license or a * BSD style license, available at: * http://datatables.net/license_gpl2 * http://datatables.net/license_bsd * * This source file is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details. * * For details please refer to: http://www.datatables.net */ /*jslint evil: true, undef: true, browser: true */ /*globals $, jQuery,define,_fnExternApiFunc,_fnInitialise,_fnInitComplete,_fnLanguageCompat,_fnAddColumn,_fnColumnOptions,_fnAddData,_fnCreateTr,_fnGatherData,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnServerParams,_fnAddOptionsHtml,_fnFeatureHtmlTable,_fnScrollDraw,_fnAdjustColumnSizing,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnBuildSearchArray,_fnBuildSearchRow,_fnFilterCreateSearch,_fnDataToSearch,_fnSort,_fnSortAttachListener,_fnSortingClasses,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnFeatureHtmlLength,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnNodeToDataIndex,_fnVisbleColumns,_fnCalculateEnd,_fnConvertToWidth,_fnCalculateColumnWidths,_fnScrollingWidthAdjust,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnDetectType,_fnSettingsFromNode,_fnGetDataMaster,_fnGetTrNodes,_fnGetTdNodes,_fnEscapeRegex,_fnDeleteIndex,_fnReOrderIndex,_fnColumnOrdering,_fnLog,_fnClearTable,_fnSaveState,_fnLoadState,_fnCreateCookie,_fnReadCookie,_fnDetectHeader,_fnGetUniqueThs,_fnScrollBarWidth,_fnApplyToChildren,_fnMap,_fnGetRowData,_fnGetCellData,_fnSetCellData,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnApplyColumnDefs,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnJsonString,_fnRender,_fnNodeToColumnIndex,_fnInfoMacros,_fnBrowserDetect,_fnGetColumns*/ (/** @lends <global> */function( window, document, undefined ) { (function( factory ) { "use strict"; // Define as an AMD module if possible if ( typeof define === 'function' && define.amd ) { define( ['jquery'], factory ); } /* Define using browser globals otherwise * Prevent multiple instantiations if the script is loaded twice */ else if ( jQuery && !jQuery.fn.dataTable ) { factory( jQuery ); } } (/** @lends <global> */function( $ ) { "use strict"; /** * DataTables is a plug-in for the jQuery Javascript library. It is a * highly flexible tool, based upon the foundations of progressive * enhancement, which will add advanced interaction controls to any * HTML table. For a full list of features please refer to * <a href="http://datatables.net">DataTables.net</a>. * * Note that the <i>DataTable</i> object is not a global variable but is * aliased to <i>jQuery.fn.DataTable</i> and <i>jQuery.fn.dataTable</i> through which * it may be accessed. * * @class * @param {object} [oInit={}] Configuration object for DataTables. Options * are defined by {@link DataTable.defaults} * @requires jQuery 1.3+ * * @example * // Basic initialisation * $(document).ready( function { * $('#example').dataTable(); * } ); * * @example * // Initialisation with configuration options - in this case, disable * // pagination and sorting. * $(document).ready( function { * $('#example').dataTable( { * "bPaginate": false, * "bSort": false * } ); * } ); */ var DataTable = function( oInit ) { /** * Add a column to the list used for the table with default values * @param {object} oSettings dataTables settings object * @param {node} nTh The th element for this column * @memberof DataTable#oApi */ function _fnAddColumn( oSettings, nTh ) { var oDefaults = DataTable.defaults.columns; var iCol = oSettings.aoColumns.length; var oCol = $.extend( {}, DataTable.models.oColumn, oDefaults, { "sSortingClass": oSettings.oClasses.sSortable, "sSortingClassJUI": oSettings.oClasses.sSortJUI, "nTh": nTh ? nTh : document.createElement('th'), "sTitle": oDefaults.sTitle ? oDefaults.sTitle : nTh ? nTh.innerHTML : '', "aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol], "mData": oDefaults.mData ? oDefaults.oDefaults : iCol } ); oSettings.aoColumns.push( oCol ); /* Add a column specific filter */ if ( oSettings.aoPreSearchCols[ iCol ] === undefined || oSettings.aoPreSearchCols[ iCol ] === null ) { oSettings.aoPreSearchCols[ iCol ] = $.extend( {}, DataTable.models.oSearch ); } else { var oPre = oSettings.aoPreSearchCols[ iCol ]; /* Don't require that the user must specify bRegex, bSmart or bCaseInsensitive */ if ( oPre.bRegex === undefined ) { oPre.bRegex = true; } if ( oPre.bSmart === undefined ) { oPre.bSmart = true; } if ( oPre.bCaseInsensitive === undefined ) { oPre.bCaseInsensitive = true; } } /* Use the column options function to initialise classes etc */ _fnColumnOptions( oSettings, iCol, null ); } /** * Apply options for a column * @param {object} oSettings dataTables settings object * @param {int} iCol column index to consider * @param {object} oOptions object with sType, bVisible and bSearchable etc * @memberof DataTable#oApi */ function _fnColumnOptions( oSettings, iCol, oOptions ) { var oCol = oSettings.aoColumns[ iCol ]; /* User specified column options */ if ( oOptions !== undefined && oOptions !== null ) { /* Backwards compatibility for mDataProp */ if ( oOptions.mDataProp && !oOptions.mData ) { oOptions.mData = oOptions.mDataProp; } if ( oOptions.sType !== undefined ) { oCol.sType = oOptions.sType; oCol._bAutoType = false; } $.extend( oCol, oOptions ); _fnMap( oCol, oOptions, "sWidth", "sWidthOrig" ); /* iDataSort to be applied (backwards compatibility), but aDataSort will take * priority if defined */ if ( oOptions.iDataSort !== undefined ) { oCol.aDataSort = [ oOptions.iDataSort ]; } _fnMap( oCol, oOptions, "aDataSort" ); } /* Cache the data get and set functions for speed */ var mRender = oCol.mRender ? _fnGetObjectDataFn( oCol.mRender ) : null; var mData = _fnGetObjectDataFn( oCol.mData ); oCol.fnGetData = function (oData, sSpecific) { var innerData = mData( oData, sSpecific ); if ( oCol.mRender && (sSpecific && sSpecific !== '') ) { return mRender( innerData, sSpecific, oData ); } return innerData; }; oCol.fnSetData = _fnSetObjectDataFn( oCol.mData ); /* Feature sorting overrides column specific when off */ if ( !oSettings.oFeatures.bSort ) { oCol.bSortable = false; } /* Check that the class assignment is correct for sorting */ if ( !oCol.bSortable || ($.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) == -1) ) { oCol.sSortingClass = oSettings.oClasses.sSortableNone; oCol.sSortingClassJUI = ""; } else if ( $.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) == -1 ) { oCol.sSortingClass = oSettings.oClasses.sSortable; oCol.sSortingClassJUI = oSettings.oClasses.sSortJUI; } else if ( $.inArray('asc', oCol.asSorting) != -1 && $.inArray('desc', oCol.asSorting) == -1 ) { oCol.sSortingClass = oSettings.oClasses.sSortableAsc; oCol.sSortingClassJUI = oSettings.oClasses.sSortJUIAscAllowed; } else if ( $.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) != -1 ) { oCol.sSortingClass = oSettings.oClasses.sSortableDesc; oCol.sSortingClassJUI = oSettings.oClasses.sSortJUIDescAllowed; } } /** * Adjust the table column widths for new data. Note: you would probably want to * do a redraw after calling this function! * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnAdjustColumnSizing ( oSettings ) { /* Not interested in doing column width calculation if auto-width is disabled */ if ( oSettings.oFeatures.bAutoWidth === false ) { return false; } _fnCalculateColumnWidths( oSettings ); for ( var i=0 , iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { oSettings.aoColumns[i].nTh.style.width = oSettings.aoColumns[i].sWidth; } } /** * Covert the index of a visible column to the index in the data array (take account * of hidden columns) * @param {object} oSettings dataTables settings object * @param {int} iMatch Visible column index to lookup * @returns {int} i the data index * @memberof DataTable#oApi */ function _fnVisibleToColumnIndex( oSettings, iMatch ) { var aiVis = _fnGetColumns( oSettings, 'bVisible' ); return typeof aiVis[iMatch] === 'number' ? aiVis[iMatch] : null; } /** * Covert the index of an index in the data array and convert it to the visible * column index (take account of hidden columns) * @param {int} iMatch Column index to lookup * @param {object} oSettings dataTables settings object * @returns {int} i the data index * @memberof DataTable#oApi */ function _fnColumnIndexToVisible( oSettings, iMatch ) { var aiVis = _fnGetColumns( oSettings, 'bVisible' ); var iPos = $.inArray( iMatch, aiVis ); return iPos !== -1 ? iPos : null; } /** * Get the number of visible columns * @param {object} oSettings dataTables settings object * @returns {int} i the number of visible columns * @memberof DataTable#oApi */ function _fnVisbleColumns( oSettings ) { return _fnGetColumns( oSettings, 'bVisible' ).length; } /** * Get an array of column indexes that match a given property * @param {object} oSettings dataTables settings object * @param {string} sParam Parameter in aoColumns to look for - typically * bVisible or bSearchable * @returns {array} Array of indexes with matched properties * @memberof DataTable#oApi */ function _fnGetColumns( oSettings, sParam ) { var a = []; $.map( oSettings.aoColumns, function(val, i) { if ( val[sParam] ) { a.push( i ); } } ); return a; } /** * Get the sort type based on an input string * @param {string} sData data we wish to know the type of * @returns {string} type (defaults to 'string' if no type can be detected) * @memberof DataTable#oApi */ function _fnDetectType( sData ) { var aTypes = DataTable.ext.aTypes; var iLen = aTypes.length; for ( var i=0 ; i<iLen ; i++ ) { var sType = aTypes[i]( sData ); if ( sType !== null ) { return sType; } } return 'string'; } /** * Figure out how to reorder a display list * @param {object} oSettings dataTables settings object * @returns array {int} aiReturn index list for reordering * @memberof DataTable#oApi */ function _fnReOrderIndex ( oSettings, sColumns ) { var aColumns = sColumns.split(','); var aiReturn = []; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { for ( var j=0 ; j<iLen ; j++ ) { if ( oSettings.aoColumns[i].sName == aColumns[j] ) { aiReturn.push( j ); break; } } } return aiReturn; } /** * Get the column ordering that DataTables expects * @param {object} oSettings dataTables settings object * @returns {string} comma separated list of names * @memberof DataTable#oApi */ function _fnColumnOrdering ( oSettings ) { var sNames = ''; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { sNames += oSettings.aoColumns[i].sName+','; } if ( sNames.length == iLen ) { return ""; } return sNames.slice(0, -1); } /** * Take the column definitions and static columns arrays and calculate how * they relate to column indexes. The callback function will then apply the * definition found for a column to a suitable configuration object. * @param {object} oSettings dataTables settings object * @param {array} aoColDefs The aoColumnDefs array that is to be applied * @param {array} aoCols The aoColumns array that defines columns individually * @param {function} fn Callback function - takes two parameters, the calculated * column index and the definition for that column. * @memberof DataTable#oApi */ function _fnApplyColumnDefs( oSettings, aoColDefs, aoCols, fn ) { var i, iLen, j, jLen, k, kLen; // Column definitions with aTargets if ( aoColDefs ) { /* Loop over the definitions array - loop in reverse so first instance has priority */ for ( i=aoColDefs.length-1 ; i>=0 ; i-- ) { /* Each definition can target multiple columns, as it is an array */ var aTargets = aoColDefs[i].aTargets; if ( !$.isArray( aTargets ) ) { _fnLog( oSettings, 1, 'aTargets must be an array of targets, not a '+(typeof aTargets) ); } for ( j=0, jLen=aTargets.length ; j<jLen ; j++ ) { if ( typeof aTargets[j] === 'number' && aTargets[j] >= 0 ) { /* Add columns that we don't yet know about */ while( oSettings.aoColumns.length <= aTargets[j] ) { _fnAddColumn( oSettings ); } /* Integer, basic index */ fn( aTargets[j], aoColDefs[i] ); } else if ( typeof aTargets[j] === 'number' && aTargets[j] < 0 ) { /* Negative integer, right to left column counting */ fn( oSettings.aoColumns.length+aTargets[j], aoColDefs[i] ); } else if ( typeof aTargets[j] === 'string' ) { /* Class name matching on TH element */ for ( k=0, kLen=oSettings.aoColumns.length ; k<kLen ; k++ ) { if ( aTargets[j] == "_all" || $(oSettings.aoColumns[k].nTh).hasClass( aTargets[j] ) ) { fn( k, aoColDefs[i] ); } } } } } } // Statically defined columns array if ( aoCols ) { for ( i=0, iLen=aoCols.length ; i<iLen ; i++ ) { fn( i, aoCols[i] ); } } } /** * Add a data array to the table, creating DOM node etc. This is the parallel to * _fnGatherData, but for adding rows from a Javascript source, rather than a * DOM source. * @param {object} oSettings dataTables settings object * @param {array} aData data array to be added * @returns {int} >=0 if successful (index of new aoData entry), -1 if failed * @memberof DataTable#oApi */ function _fnAddData ( oSettings, aDataSupplied ) { var oCol; /* Take an independent copy of the data source so we can bash it about as we wish */ var aDataIn = ($.isArray(aDataSupplied)) ? aDataSupplied.slice() : $.extend( true, {}, aDataSupplied ); /* Create the object for storing information about this new row */ var iRow = oSettings.aoData.length; var oData = $.extend( true, {}, DataTable.models.oRow ); oData._aData = aDataIn; oSettings.aoData.push( oData ); /* Create the cells */ var nTd, sThisType; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { oCol = oSettings.aoColumns[i]; /* Use rendered data for filtering / sorting */ if ( typeof oCol.fnRender === 'function' && oCol.bUseRendered && oCol.mData !== null ) { _fnSetCellData( oSettings, iRow, i, _fnRender(oSettings, iRow, i) ); } else { _fnSetCellData( oSettings, iRow, i, _fnGetCellData( oSettings, iRow, i ) ); } /* See if we should auto-detect the column type */ if ( oCol._bAutoType && oCol.sType != 'string' ) { /* Attempt to auto detect the type - same as _fnGatherData() */ var sVarType = _fnGetCellData( oSettings, iRow, i, 'type' ); if ( sVarType !== null && sVarType !== '' ) { sThisType = _fnDetectType( sVarType ); if ( oCol.sType === null ) { oCol.sType = sThisType; } else if ( oCol.sType != sThisType && oCol.sType != "html" ) { /* String is always the 'fallback' option */ oCol.sType = 'string'; } } } } /* Add to the display array */ oSettings.aiDisplayMaster.push( iRow ); /* Create the DOM information */ if ( !oSettings.oFeatures.bDeferRender ) { _fnCreateTr( oSettings, iRow ); } return iRow; } /** * Read in the data from the target table from the DOM * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnGatherData( oSettings ) { var iLoop, i, iLen, j, jLen, jInner, nTds, nTrs, nTd, nTr, aLocalData, iThisIndex, iRow, iRows, iColumn, iColumns, sNodeName, oCol, oData; /* * Process by row first * Add the data object for the whole table - storing the tr node. Note - no point in getting * DOM based data if we are going to go and replace it with Ajax source data. */ if ( oSettings.bDeferLoading || oSettings.sAjaxSource === null ) { nTr = oSettings.nTBody.firstChild; while ( nTr ) { if ( nTr.nodeName.toUpperCase() == "TR" ) { iThisIndex = oSettings.aoData.length; nTr._DT_RowIndex = iThisIndex; oSettings.aoData.push( $.extend( true, {}, DataTable.models.oRow, { "nTr": nTr } ) ); oSettings.aiDisplayMaster.push( iThisIndex ); nTd = nTr.firstChild; jInner = 0; while ( nTd ) { sNodeName = nTd.nodeName.toUpperCase(); if ( sNodeName == "TD" || sNodeName == "TH" ) { _fnSetCellData( oSettings, iThisIndex, jInner, $.trim(nTd.innerHTML) ); jInner++; } nTd = nTd.nextSibling; } } nTr = nTr.nextSibling; } } /* Gather in the TD elements of the Table - note that this is basically the same as * fnGetTdNodes, but that function takes account of hidden columns, which we haven't yet * setup! */ nTrs = _fnGetTrNodes( oSettings ); nTds = []; for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { nTd = nTrs[i].firstChild; while ( nTd ) { sNodeName = nTd.nodeName.toUpperCase(); if ( sNodeName == "TD" || sNodeName == "TH" ) { nTds.push( nTd ); } nTd = nTd.nextSibling; } } /* Now process by column */ for ( iColumn=0, iColumns=oSettings.aoColumns.length ; iColumn<iColumns ; iColumn++ ) { oCol = oSettings.aoColumns[iColumn]; /* Get the title of the column - unless there is a user set one */ if ( oCol.sTitle === null ) { oCol.sTitle = oCol.nTh.innerHTML; } var bAutoType = oCol._bAutoType, bRender = typeof oCol.fnRender === 'function', bClass = oCol.sClass !== null, bVisible = oCol.bVisible, nCell, sThisType, sRendered, sValType; /* A single loop to rule them all (and be more efficient) */ if ( bAutoType || bRender || bClass || !bVisible ) { for ( iRow=0, iRows=oSettings.aoData.length ; iRow<iRows ; iRow++ ) { oData = oSettings.aoData[iRow]; nCell = nTds[ (iRow*iColumns) + iColumn ]; /* Type detection */ if ( bAutoType && oCol.sType != 'string' ) { sValType = _fnGetCellData( oSettings, iRow, iColumn, 'type' ); if ( sValType !== '' ) { sThisType = _fnDetectType( sValType ); if ( oCol.sType === null ) { oCol.sType = sThisType; } else if ( oCol.sType != sThisType && oCol.sType != "html" ) { /* String is always the 'fallback' option */ oCol.sType = 'string'; } } } if ( oCol.mRender ) { // mRender has been defined, so we need to get the value and set it nCell.innerHTML = _fnGetCellData( oSettings, iRow, iColumn, 'display' ); } else if ( oCol.mData !== iColumn ) { // If mData is not the same as the column number, then we need to // get the dev set value. If it is the column, no point in wasting // time setting the value that is already there! nCell.innerHTML = _fnGetCellData( oSettings, iRow, iColumn, 'display' ); } /* Rendering */ if ( bRender ) { sRendered = _fnRender( oSettings, iRow, iColumn ); nCell.innerHTML = sRendered; if ( oCol.bUseRendered ) { /* Use the rendered data for filtering / sorting */ _fnSetCellData( oSettings, iRow, iColumn, sRendered ); } } /* Classes */ if ( bClass ) { nCell.className += ' '+oCol.sClass; } /* Column visibility */ if ( !bVisible ) { oData._anHidden[iColumn] = nCell; nCell.parentNode.removeChild( nCell ); } else { oData._anHidden[iColumn] = null; } if ( oCol.fnCreatedCell ) { oCol.fnCreatedCell.call( oSettings.oInstance, nCell, _fnGetCellData( oSettings, iRow, iColumn, 'display' ), oData._aData, iRow, iColumn ); } } } } /* Row created callbacks */ if ( oSettings.aoRowCreatedCallback.length !== 0 ) { for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { oData = oSettings.aoData[i]; _fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [oData.nTr, oData._aData, i] ); } } } /** * Take a TR element and convert it to an index in aoData * @param {object} oSettings dataTables settings object * @param {node} n the TR element to find * @returns {int} index if the node is found, null if not * @memberof DataTable#oApi */ function _fnNodeToDataIndex( oSettings, n ) { return (n._DT_RowIndex!==undefined) ? n._DT_RowIndex : null; } /** * Take a TD element and convert it into a column data index (not the visible index) * @param {object} oSettings dataTables settings object * @param {int} iRow The row number the TD/TH can be found in * @param {node} n The TD/TH element to find * @returns {int} index if the node is found, -1 if not * @memberof DataTable#oApi */ function _fnNodeToColumnIndex( oSettings, iRow, n ) { var anCells = _fnGetTdNodes( oSettings, iRow ); for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { if ( anCells[i] === n ) { return i; } } return -1; } /** * Get an array of data for a given row from the internal data cache * @param {object} oSettings dataTables settings object * @param {int} iRow aoData row id * @param {string} sSpecific data get type ('type' 'filter' 'sort') * @param {array} aiColumns Array of column indexes to get data from * @returns {array} Data array * @memberof DataTable#oApi */ function _fnGetRowData( oSettings, iRow, sSpecific, aiColumns ) { var out = []; for ( var i=0, iLen=aiColumns.length ; i<iLen ; i++ ) { out.push( _fnGetCellData( oSettings, iRow, aiColumns[i], sSpecific ) ); } return out; } /** * Get the data for a given cell from the internal cache, taking into account data mapping * @param {object} oSettings dataTables settings object * @param {int} iRow aoData row id * @param {int} iCol Column index * @param {string} sSpecific data get type ('display', 'type' 'filter' 'sort') * @returns {*} Cell data * @memberof DataTable#oApi */ function _fnGetCellData( oSettings, iRow, iCol, sSpecific ) { var sData; var oCol = oSettings.aoColumns[iCol]; var oData = oSettings.aoData[iRow]._aData; if ( (sData=oCol.fnGetData( oData, sSpecific )) === undefined ) { if ( oSettings.iDrawError != oSettings.iDraw && oCol.sDefaultContent === null ) { _fnLog( oSettings, 0, "Requested unknown parameter "+ (typeof oCol.mData=='function' ? '{mData function}' : "'"+oCol.mData+"'")+ " from the data source for row "+iRow ); oSettings.iDrawError = oSettings.iDraw; } return oCol.sDefaultContent; } /* When the data source is null, we can use default column data */ if ( sData === null && oCol.sDefaultContent !== null ) { sData = oCol.sDefaultContent; } else if ( typeof sData === 'function' ) { /* If the data source is a function, then we run it and use the return */ return sData(); } if ( sSpecific == 'display' && sData === null ) { return ''; } return sData; } /** * Set the value for a specific cell, into the internal data cache * @param {object} oSettings dataTables settings object * @param {int} iRow aoData row id * @param {int} iCol Column index * @param {*} val Value to set * @memberof DataTable#oApi */ function _fnSetCellData( oSettings, iRow, iCol, val ) { var oCol = oSettings.aoColumns[iCol]; var oData = oSettings.aoData[iRow]._aData; oCol.fnSetData( oData, val ); } // Private variable that is used to match array syntax in the data property object var __reArray = /\[.*?\]$/; /** * Return a function that can be used to get data from a source object, taking * into account the ability to use nested objects as a source * @param {string|int|function} mSource The data source for the object * @returns {function} Data get function * @memberof DataTable#oApi */ function _fnGetObjectDataFn( mSource ) { if ( mSource === null ) { /* Give an empty string for rendering / sorting etc */ return function (data, type) { return null; }; } else if ( typeof mSource === 'function' ) { return function (data, type, extra) { return mSource( data, type, extra ); }; } else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 || mSource.indexOf('[') !== -1) ) { /* If there is a . in the source string then the data source is in a * nested object so we loop over the data for each level to get the next * level down. On each loop we test for undefined, and if found immediately * return. This allows entire objects to be missing and sDefaultContent to * be used if defined, rather than throwing an error */ var fetchData = function (data, type, src) { var a = src.split('.'); var arrayNotation, out, innerSrc; if ( src !== "" ) { for ( var i=0, iLen=a.length ; i<iLen ; i++ ) { // Check if we are dealing with an array notation request arrayNotation = a[i].match(__reArray); if ( arrayNotation ) { a[i] = a[i].replace(__reArray, ''); // Condition allows simply [] to be passed in if ( a[i] !== "" ) { data = data[ a[i] ]; } out = []; // Get the remainder of the nested object to get a.splice( 0, i+1 ); innerSrc = a.join('.'); // Traverse each entry in the array getting the properties requested for ( var j=0, jLen=data.length ; j<jLen ; j++ ) { out.push( fetchData( data[j], type, innerSrc ) ); } // If a string is given in between the array notation indicators, that // is used to join the strings together, otherwise an array is returned var join = arrayNotation[0].substring(1, arrayNotation[0].length-1); data = (join==="") ? out : out.join(join); // The inner call to fetchData has already traversed through the remainder // of the source requested, so we exit from the loop break; } if ( data === null || data[ a[i] ] === undefined ) { return undefined; } data = data[ a[i] ]; } } return data; }; return function (data, type) { return fetchData( data, type, mSource ); }; } else { /* Array or flat object mapping */ return function (data, type) { return data[mSource]; }; } } /** * Return a function that can be used to set data from a source object, taking * into account the ability to use nested objects as a source * @param {string|int|function} mSource The data source for the object * @returns {function} Data set function * @memberof DataTable#oApi */ function _fnSetObjectDataFn( mSource ) { if ( mSource === null ) { /* Nothing to do when the data source is null */ return function (data, val) {}; } else if ( typeof mSource === 'function' ) { return function (data, val) { mSource( data, 'set', val ); }; } else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 || mSource.indexOf('[') !== -1) ) { /* Like the get, we need to get data from a nested object */ var setData = function (data, val, src) { var a = src.split('.'), b; var arrayNotation, o, innerSrc; for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ ) { // Check if we are dealing with an array notation request arrayNotation = a[i].match(__reArray); if ( arrayNotation ) { a[i] = a[i].replace(__reArray, ''); data[ a[i] ] = []; // Get the remainder of the nested object to set so we can recurse b = a.slice(); b.splice( 0, i+1 ); innerSrc = b.join('.'); // Traverse each entry in the array setting the properties requested for ( var j=0, jLen=val.length ; j<jLen ; j++ ) { o = {}; setData( o, val[j], innerSrc ); data[ a[i] ].push( o ); } // The inner call to setData has already traversed through the remainder // of the source and has set the data, thus we can exit here return; } // If the nested object doesn't currently exist - since we are // trying to set the value - create it if ( data[ a[i] ] === null || data[ a[i] ] === undefined ) { data[ a[i] ] = {}; } data = data[ a[i] ]; } // If array notation is used, we just want to strip it and use the property name // and assign the value. If it isn't used, then we get the result we want anyway data[ a[a.length-1].replace(__reArray, '') ] = val; }; return function (data, val) { return setData( data, val, mSource ); }; } else { /* Array or flat object mapping */ return function (data, val) { data[mSource] = val; }; } } /** * Return an array with the full table data * @param {object} oSettings dataTables settings object * @returns array {array} aData Master data array * @memberof DataTable#oApi */ function _fnGetDataMaster ( oSettings ) { var aData = []; var iLen = oSettings.aoData.length; for ( var i=0 ; i<iLen; i++ ) { aData.push( oSettings.aoData[i]._aData ); } return aData; } /** * Nuke the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnClearTable( oSettings ) { oSettings.aoData.splice( 0, oSettings.aoData.length ); oSettings.aiDisplayMaster.splice( 0, oSettings.aiDisplayMaster.length ); oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length ); _fnCalculateEnd( oSettings ); } /** * Take an array of integers (index array) and remove a target integer (value - not * the key!) * @param {array} a Index array to target * @param {int} iTarget value to find * @memberof DataTable#oApi */ function _fnDeleteIndex( a, iTarget ) { var iTargetIndex = -1; for ( var i=0, iLen=a.length ; i<iLen ; i++ ) { if ( a[i] == iTarget ) { iTargetIndex = i; } else if ( a[i] > iTarget ) { a[i]--; } } if ( iTargetIndex != -1 ) { a.splice( iTargetIndex, 1 ); } } /** * Call the developer defined fnRender function for a given cell (row/column) with * the required parameters and return the result. * @param {object} oSettings dataTables settings object * @param {int} iRow aoData index for the row * @param {int} iCol aoColumns index for the column * @returns {*} Return of the developer's fnRender function * @memberof DataTable#oApi */ function _fnRender( oSettings, iRow, iCol ) { var oCol = oSettings.aoColumns[iCol]; return oCol.fnRender( { "iDataRow": iRow, "iDataColumn": iCol, "oSettings": oSettings, "aData": oSettings.aoData[iRow]._aData, "mDataProp": oCol.mData }, _fnGetCellData(oSettings, iRow, iCol, 'display') ); } /** * Create a new TR element (and it's TD children) for a row * @param {object} oSettings dataTables settings object * @param {int} iRow Row to consider * @memberof DataTable#oApi */ function _fnCreateTr ( oSettings, iRow ) { var oData = oSettings.aoData[iRow]; var nTd; if ( oData.nTr === null ) { oData.nTr = document.createElement('tr'); /* Use a private property on the node to allow reserve mapping from the node * to the aoData array for fast look up */ oData.nTr._DT_RowIndex = iRow; /* Special parameters can be given by the data source to be used on the row */ if ( oData._aData.DT_RowId ) { oData.nTr.id = oData._aData.DT_RowId; } if ( oData._aData.DT_RowClass ) { oData.nTr.className = oData._aData.DT_RowClass; } /* Process each column */ for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { var oCol = oSettings.aoColumns[i]; nTd = document.createElement( oCol.sCellType ); /* Render if needed - if bUseRendered is true then we already have the rendered * value in the data source - so can just use that */ nTd.innerHTML = (typeof oCol.fnRender === 'function' && (!oCol.bUseRendered || oCol.mData === null)) ? _fnRender( oSettings, iRow, i ) : _fnGetCellData( oSettings, iRow, i, 'display' ); /* Add user defined class */ if ( oCol.sClass !== null ) { nTd.className = oCol.sClass; } if ( oCol.bVisible ) { oData.nTr.appendChild( nTd ); oData._anHidden[i] = null; } else { oData._anHidden[i] = nTd; } if ( oCol.fnCreatedCell ) { oCol.fnCreatedCell.call( oSettings.oInstance, nTd, _fnGetCellData( oSettings, iRow, i, 'display' ), oData._aData, iRow, i ); } } _fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [oData.nTr, oData._aData, iRow] ); } } /** * Create the HTML header for the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnBuildHead( oSettings ) { var i, nTh, iLen, j, jLen; var iThs = $('th, td', oSettings.nTHead).length; var iCorrector = 0; var jqChildren; /* If there is a header in place - then use it - otherwise it's going to get nuked... */ if ( iThs !== 0 ) { /* We've got a thead from the DOM, so remove hidden columns and apply width to vis cols */ for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { nTh = oSettings.aoColumns[i].nTh; nTh.setAttribute('role', 'columnheader'); if ( oSettings.aoColumns[i].bSortable ) { nTh.setAttribute('tabindex', oSettings.iTabIndex); nTh.setAttribute('aria-controls', oSettings.sTableId); } if ( oSettings.aoColumns[i].sClass !== null ) { $(nTh).addClass( oSettings.aoColumns[i].sClass ); } /* Set the title of the column if it is user defined (not what was auto detected) */ if ( oSettings.aoColumns[i].sTitle != nTh.innerHTML ) { nTh.innerHTML = oSettings.aoColumns[i].sTitle; } } } else { /* We don't have a header in the DOM - so we are going to have to create one */ var nTr = document.createElement( "tr" ); for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { nTh = oSettings.aoColumns[i].nTh; nTh.innerHTML = oSettings.aoColumns[i].sTitle; nTh.setAttribute('tabindex', '0'); if ( oSettings.aoColumns[i].sClass !== null ) { $(nTh).addClass( oSettings.aoColumns[i].sClass ); } nTr.appendChild( nTh ); } $(oSettings.nTHead).html( '' )[0].appendChild( nTr ); _fnDetectHeader( oSettings.aoHeader, oSettings.nTHead ); } /* ARIA role for the rows */ $(oSettings.nTHead).children('tr').attr('role', 'row'); /* Add the extra markup needed by jQuery UI's themes */ if ( oSettings.bJUI ) { for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { nTh = oSettings.aoColumns[i].nTh; var nDiv = document.createElement('div'); nDiv.className = oSettings.oClasses.sSortJUIWrapper; $(nTh).contents().appendTo(nDiv); var nSpan = document.createElement('span'); nSpan.className = oSettings.oClasses.sSortIcon; nDiv.appendChild( nSpan ); nTh.appendChild( nDiv ); } } if ( oSettings.oFeatures.bSort ) { for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bSortable !== false ) { _fnSortAttachListener( oSettings, oSettings.aoColumns[i].nTh, i ); } else { $(oSettings.aoColumns[i].nTh).addClass( oSettings.oClasses.sSortableNone ); } } } /* Deal with the footer - add classes if required */ if ( oSettings.oClasses.sFooterTH !== "" ) { $(oSettings.nTFoot).children('tr').children('th').addClass( oSettings.oClasses.sFooterTH ); } /* Cache the footer elements */ if ( oSettings.nTFoot !== null ) { var anCells = _fnGetUniqueThs( oSettings, null, oSettings.aoFooter ); for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { if ( anCells[i] ) { oSettings.aoColumns[i].nTf = anCells[i]; if ( oSettings.aoColumns[i].sClass ) { $(anCells[i]).addClass( oSettings.aoColumns[i].sClass ); } } } } } /** * Draw the header (or footer) element based on the column visibility states. The * methodology here is to use the layout array from _fnDetectHeader, modified for * the instantaneous column visibility, to construct the new layout. The grid is * traversed over cell at a time in a rows x columns grid fashion, although each * cell insert can cover multiple elements in the grid - which is tracks using the * aApplied array. Cell inserts in the grid will only occur where there isn't * already a cell in that position. * @param {object} oSettings dataTables settings object * @param array {objects} aoSource Layout array from _fnDetectHeader * @param {boolean} [bIncludeHidden=false] If true then include the hidden columns in the calc, * @memberof DataTable#oApi */ function _fnDrawHead( oSettings, aoSource, bIncludeHidden ) { var i, iLen, j, jLen, k, kLen, n, nLocalTr; var aoLocal = []; var aApplied = []; var iColumns = oSettings.aoColumns.length; var iRowspan, iColspan; if ( bIncludeHidden === undefined ) { bIncludeHidden = false; } /* Make a copy of the master layout array, but without the visible columns in it */ for ( i=0, iLen=aoSource.length ; i<iLen ; i++ ) { aoLocal[i] = aoSource[i].slice(); aoLocal[i].nTr = aoSource[i].nTr; /* Remove any columns which are currently hidden */ for ( j=iColumns-1 ; j>=0 ; j-- ) { if ( !oSettings.aoColumns[j].bVisible && !bIncludeHidden ) { aoLocal[i].splice( j, 1 ); } } /* Prep the applied array - it needs an element for each row */ aApplied.push( [] ); } for ( i=0, iLen=aoLocal.length ; i<iLen ; i++ ) { nLocalTr = aoLocal[i].nTr; /* All cells are going to be replaced, so empty out the row */ if ( nLocalTr ) { while( (n = nLocalTr.firstChild) ) { nLocalTr.removeChild( n ); } } for ( j=0, jLen=aoLocal[i].length ; j<jLen ; j++ ) { iRowspan = 1; iColspan = 1; /* Check to see if there is already a cell (row/colspan) covering our target * insert point. If there is, then there is nothing to do. */ if ( aApplied[i][j] === undefined ) { nLocalTr.appendChild( aoLocal[i][j].cell ); aApplied[i][j] = 1; /* Expand the cell to cover as many rows as needed */ while ( aoLocal[i+iRowspan] !== undefined && aoLocal[i][j].cell == aoLocal[i+iRowspan][j].cell ) { aApplied[i+iRowspan][j] = 1; iRowspan++; } /* Expand the cell to cover as many columns as needed */ while ( aoLocal[i][j+iColspan] !== undefined && aoLocal[i][j].cell == aoLocal[i][j+iColspan].cell ) { /* Must update the applied array over the rows for the columns */ for ( k=0 ; k<iRowspan ; k++ ) { aApplied[i+k][j+iColspan] = 1; } iColspan++; } /* Do the actual expansion in the DOM */ aoLocal[i][j].cell.rowSpan = iRowspan; aoLocal[i][j].cell.colSpan = iColspan; } } } } /** * Insert the required TR nodes into the table for display * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnDraw( oSettings ) { /* Provide a pre-callback function which can be used to cancel the draw is false is returned */ var aPreDraw = _fnCallbackFire( oSettings, 'aoPreDrawCallback', 'preDraw', [oSettings] ); if ( $.inArray( false, aPreDraw ) !== -1 ) { _fnProcessingDisplay( oSettings, false ); return; } var i, iLen, n; var anRows = []; var iRowCount = 0; var iStripes = oSettings.asStripeClasses.length; var iOpenRows = oSettings.aoOpenRows.length; oSettings.bDrawing = true; /* Check and see if we have an initial draw position from state saving */ if ( oSettings.iInitDisplayStart !== undefined && oSettings.iInitDisplayStart != -1 ) { if ( oSettings.oFeatures.bServerSide ) { oSettings._iDisplayStart = oSettings.iInitDisplayStart; } else { oSettings._iDisplayStart = (oSettings.iInitDisplayStart >= oSettings.fnRecordsDisplay()) ? 0 : oSettings.iInitDisplayStart; } oSettings.iInitDisplayStart = -1; _fnCalculateEnd( oSettings ); } /* Server-side processing draw intercept */ if ( oSettings.bDeferLoading ) { oSettings.bDeferLoading = false; oSettings.iDraw++; } else if ( !oSettings.oFeatures.bServerSide ) { oSettings.iDraw++; } else if ( !oSettings.bDestroying && !_fnAjaxUpdate( oSettings ) ) { return; } if ( oSettings.aiDisplay.length !== 0 ) { var iStart = oSettings._iDisplayStart; var iEnd = oSettings._iDisplayEnd; if ( oSettings.oFeatures.bServerSide ) { iStart = 0; iEnd = oSettings.aoData.length; } for ( var j=iStart ; j<iEnd ; j++ ) { var aoData = oSettings.aoData[ oSettings.aiDisplay[j] ]; if ( aoData.nTr === null ) { _fnCreateTr( oSettings, oSettings.aiDisplay[j] ); } var nRow = aoData.nTr; /* Remove the old striping classes and then add the new one */ if ( iStripes !== 0 ) { var sStripe = oSettings.asStripeClasses[ iRowCount % iStripes ]; if ( aoData._sRowStripe != sStripe ) { $(nRow).removeClass( aoData._sRowStripe ).addClass( sStripe ); aoData._sRowStripe = sStripe; } } /* Row callback functions - might want to manipulate the row */ _fnCallbackFire( oSettings, 'aoRowCallback', null, [nRow, oSettings.aoData[ oSettings.aiDisplay[j] ]._aData, iRowCount, j] ); anRows.push( nRow ); iRowCount++; /* If there is an open row - and it is attached to this parent - attach it on redraw */ if ( iOpenRows !== 0 ) { for ( var k=0 ; k<iOpenRows ; k++ ) { if ( nRow == oSettings.aoOpenRows[k].nParent ) { anRows.push( oSettings.aoOpenRows[k].nTr ); break; } } } } } else { /* Table is empty - create a row with an empty message in it */ anRows[ 0 ] = document.createElement( 'tr' ); if ( oSettings.asStripeClasses[0] ) { anRows[ 0 ].className = oSettings.asStripeClasses[0]; } var oLang = oSettings.oLanguage; var sZero = oLang.sZeroRecords; if ( oSettings.iDraw == 1 && oSettings.sAjaxSource !== null && !oSettings.oFeatures.bServerSide ) { sZero = oLang.sLoadingRecords; } else if ( oLang.sEmptyTable && oSettings.fnRecordsTotal() === 0 ) { sZero = oLang.sEmptyTable; } var nTd = document.createElement( 'td' ); nTd.setAttribute( 'valign', "top" ); nTd.colSpan = _fnVisbleColumns( oSettings ); nTd.className = oSettings.oClasses.sRowEmpty; nTd.innerHTML = _fnInfoMacros( oSettings, sZero ); anRows[ iRowCount ].appendChild( nTd ); } /* Header and footer callbacks */ _fnCallbackFire( oSettings, 'aoHeaderCallback', 'header', [ $(oSettings.nTHead).children('tr')[0], _fnGetDataMaster( oSettings ), oSettings._iDisplayStart, oSettings.fnDisplayEnd(), oSettings.aiDisplay ] ); _fnCallbackFire( oSettings, 'aoFooterCallback', 'footer', [ $(oSettings.nTFoot).children('tr')[0], _fnGetDataMaster( oSettings ), oSettings._iDisplayStart, oSettings.fnDisplayEnd(), oSettings.aiDisplay ] ); /* * Need to remove any old row from the display - note we can't just empty the tbody using * $().html('') since this will unbind the jQuery event handlers (even although the node * still exists!) - equally we can't use innerHTML, since IE throws an exception. */ var nAddFrag = document.createDocumentFragment(), nRemoveFrag = document.createDocumentFragment(), nBodyPar, nTrs; if ( oSettings.nTBody ) { nBodyPar = oSettings.nTBody.parentNode; nRemoveFrag.appendChild( oSettings.nTBody ); /* When doing infinite scrolling, only remove child rows when sorting, filtering or start * up. When not infinite scroll, always do it. */ if ( !oSettings.oScroll.bInfinite || !oSettings._bInitComplete || oSettings.bSorted || oSettings.bFiltered ) { while( (n = oSettings.nTBody.firstChild) ) { oSettings.nTBody.removeChild( n ); } } /* Put the draw table into the dom */ for ( i=0, iLen=anRows.length ; i<iLen ; i++ ) { nAddFrag.appendChild( anRows[i] ); } oSettings.nTBody.appendChild( nAddFrag ); if ( nBodyPar !== null ) { nBodyPar.appendChild( oSettings.nTBody ); } } /* Call all required callback functions for the end of a draw */ _fnCallbackFire( oSettings, 'aoDrawCallback', 'draw', [oSettings] ); /* Draw is complete, sorting and filtering must be as well */ oSettings.bSorted = false; oSettings.bFiltered = false; oSettings.bDrawing = false; if ( oSettings.oFeatures.bServerSide ) { _fnProcessingDisplay( oSettings, false ); if ( !oSettings._bInitComplete ) { _fnInitComplete( oSettings ); } } } /** * Redraw the table - taking account of the various features which are enabled * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnReDraw( oSettings ) { if ( oSettings.oFeatures.bSort ) { /* Sorting will refilter and draw for us */ _fnSort( oSettings, oSettings.oPreviousSearch ); } else if ( oSettings.oFeatures.bFilter ) { /* Filtering will redraw for us */ _fnFilterComplete( oSettings, oSettings.oPreviousSearch ); } else { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } } /** * Add the options to the page HTML for the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnAddOptionsHtml ( oSettings ) { /* * Create a temporary, empty, div which we can later on replace with what we have generated * we do it this way to rendering the 'options' html offline - speed :-) */ var nHolding = $('<div></div>')[0]; oSettings.nTable.parentNode.insertBefore( nHolding, oSettings.nTable ); /* * All DataTables are wrapped in a div */ oSettings.nTableWrapper = $('<div id="'+oSettings.sTableId+'_wrapper" class="'+oSettings.oClasses.sWrapper+'" role="grid"></div>')[0]; oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling; /* Track where we want to insert the option */ var nInsertNode = oSettings.nTableWrapper; /* Loop over the user set positioning and place the elements as needed */ var aDom = oSettings.sDom.split(''); var nTmp, iPushFeature, cOption, nNewNode, cNext, sAttr, j; for ( var i=0 ; i<aDom.length ; i++ ) { iPushFeature = 0; cOption = aDom[i]; if ( cOption == '<' ) { /* New container div */ nNewNode = $('<div></div>')[0]; /* Check to see if we should append an id and/or a class name to the container */ cNext = aDom[i+1]; if ( cNext == "'" || cNext == '"' ) { sAttr = ""; j = 2; while ( aDom[i+j] != cNext ) { sAttr += aDom[i+j]; j++; } /* Replace jQuery UI constants */ if ( sAttr == "H" ) { sAttr = oSettings.oClasses.sJUIHeader; } else if ( sAttr == "F" ) { sAttr = oSettings.oClasses.sJUIFooter; } /* The attribute can be in the format of "#id.class", "#id" or "class" This logic * breaks the string into parts and applies them as needed */ if ( sAttr.indexOf('.') != -1 ) { var aSplit = sAttr.split('.'); nNewNode.id = aSplit[0].substr(1, aSplit[0].length-1); nNewNode.className = aSplit[1]; } else if ( sAttr.charAt(0) == "#" ) { nNewNode.id = sAttr.substr(1, sAttr.length-1); } else { nNewNode.className = sAttr; } i += j; /* Move along the position array */ } nInsertNode.appendChild( nNewNode ); nInsertNode = nNewNode; } else if ( cOption == '>' ) { /* End container div */ nInsertNode = nInsertNode.parentNode; } else if ( cOption == 'l' && oSettings.oFeatures.bPaginate && oSettings.oFeatures.bLengthChange ) { /* Length */ nTmp = _fnFeatureHtmlLength( oSettings ); iPushFeature = 1; } else if ( cOption == 'f' && oSettings.oFeatures.bFilter ) { /* Filter */ nTmp = _fnFeatureHtmlFilter( oSettings ); iPushFeature = 1; } else if ( cOption == 'r' && oSettings.oFeatures.bProcessing ) { /* pRocessing */ nTmp = _fnFeatureHtmlProcessing( oSettings ); iPushFeature = 1; } else if ( cOption == 't' ) { /* Table */ nTmp = _fnFeatureHtmlTable( oSettings ); iPushFeature = 1; } else if ( cOption == 'i' && oSettings.oFeatures.bInfo ) { /* Info */ nTmp = _fnFeatureHtmlInfo( oSettings ); iPushFeature = 1; } else if ( cOption == 'p' && oSettings.oFeatures.bPaginate ) { /* Pagination */ nTmp = _fnFeatureHtmlPaginate( oSettings ); iPushFeature = 1; } else if ( DataTable.ext.aoFeatures.length !== 0 ) { /* Plug-in features */ var aoFeatures = DataTable.ext.aoFeatures; for ( var k=0, kLen=aoFeatures.length ; k<kLen ; k++ ) { if ( cOption == aoFeatures[k].cFeature ) { nTmp = aoFeatures[k].fnInit( oSettings ); if ( nTmp ) { iPushFeature = 1; } break; } } } /* Add to the 2D features array */ if ( iPushFeature == 1 && nTmp !== null ) { if ( typeof oSettings.aanFeatures[cOption] !== 'object' ) { oSettings.aanFeatures[cOption] = []; } oSettings.aanFeatures[cOption].push( nTmp ); nInsertNode.appendChild( nTmp ); } } /* Built our DOM structure - replace the holding div with what we want */ nHolding.parentNode.replaceChild( oSettings.nTableWrapper, nHolding ); } /** * Use the DOM source to create up an array of header cells. The idea here is to * create a layout grid (array) of rows x columns, which contains a reference * to the cell that that point in the grid (regardless of col/rowspan), such that * any column / row could be removed and the new grid constructed * @param array {object} aLayout Array to store the calculated layout in * @param {node} nThead The header/footer element for the table * @memberof DataTable#oApi */ function _fnDetectHeader ( aLayout, nThead ) { var nTrs = $(nThead).children('tr'); var nTr, nCell; var i, k, l, iLen, jLen, iColShifted, iColumn, iColspan, iRowspan; var bUnique; var fnShiftCol = function ( a, i, j ) { var k = a[i]; while ( k[j] ) { j++; } return j; }; aLayout.splice( 0, aLayout.length ); /* We know how many rows there are in the layout - so prep it */ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { aLayout.push( [] ); } /* Calculate a layout array */ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { nTr = nTrs[i]; iColumn = 0; /* For every cell in the row... */ nCell = nTr.firstChild; while ( nCell ) { if ( nCell.nodeName.toUpperCase() == "TD" || nCell.nodeName.toUpperCase() == "TH" ) { /* Get the col and rowspan attributes from the DOM and sanitise them */ iColspan = nCell.getAttribute('colspan') * 1; iRowspan = nCell.getAttribute('rowspan') * 1; iColspan = (!iColspan || iColspan===0 || iColspan===1) ? 1 : iColspan; iRowspan = (!iRowspan || iRowspan===0 || iRowspan===1) ? 1 : iRowspan; /* There might be colspan cells already in this row, so shift our target * accordingly */ iColShifted = fnShiftCol( aLayout, i, iColumn ); /* Cache calculation for unique columns */ bUnique = iColspan === 1 ? true : false; /* If there is col / rowspan, copy the information into the layout grid */ for ( l=0 ; l<iColspan ; l++ ) { for ( k=0 ; k<iRowspan ; k++ ) { aLayout[i+k][iColShifted+l] = { "cell": nCell, "unique": bUnique }; aLayout[i+k].nTr = nTr; } } } nCell = nCell.nextSibling; } } } /** * Get an array of unique th elements, one for each column * @param {object} oSettings dataTables settings object * @param {node} nHeader automatically detect the layout from this node - optional * @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional * @returns array {node} aReturn list of unique th's * @memberof DataTable#oApi */ function _fnGetUniqueThs ( oSettings, nHeader, aLayout ) { var aReturn = []; if ( !aLayout ) { aLayout = oSettings.aoHeader; if ( nHeader ) { aLayout = []; _fnDetectHeader( aLayout, nHeader ); } } for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ ) { for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ ) { if ( aLayout[i][j].unique && (!aReturn[j] || !oSettings.bSortCellsTop) ) { aReturn[j] = aLayout[i][j].cell; } } } return aReturn; } /** * Update the table using an Ajax call * @param {object} oSettings dataTables settings object * @returns {boolean} Block the table drawing or not * @memberof DataTable#oApi */ function _fnAjaxUpdate( oSettings ) { if ( oSettings.bAjaxDataGet ) { oSettings.iDraw++; _fnProcessingDisplay( oSettings, true ); var iColumns = oSettings.aoColumns.length; var aoData = _fnAjaxParameters( oSettings ); _fnServerParams( oSettings, aoData ); oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, aoData, function(json) { _fnAjaxUpdateDraw( oSettings, json ); }, oSettings ); return false; } else { return true; } } /** * Build up the parameters in an object needed for a server-side processing request * @param {object} oSettings dataTables settings object * @returns {bool} block the table drawing or not * @memberof DataTable#oApi */ function _fnAjaxParameters( oSettings ) { var iColumns = oSettings.aoColumns.length; var aoData = [], mDataProp, aaSort, aDataSort; var i, j; aoData.push( { "name": "sEcho", "value": oSettings.iDraw } ); aoData.push( { "name": "iColumns", "value": iColumns } ); aoData.push( { "name": "sColumns", "value": _fnColumnOrdering(oSettings) } ); aoData.push( { "name": "iDisplayStart", "value": oSettings._iDisplayStart } ); aoData.push( { "name": "iDisplayLength", "value": oSettings.oFeatures.bPaginate !== false ? oSettings._iDisplayLength : -1 } ); for ( i=0 ; i<iColumns ; i++ ) { mDataProp = oSettings.aoColumns[i].mData; aoData.push( { "name": "mDataProp_"+i, "value": typeof(mDataProp)==="function" ? 'function' : mDataProp } ); } /* Filtering */ if ( oSettings.oFeatures.bFilter !== false ) { aoData.push( { "name": "sSearch", "value": oSettings.oPreviousSearch.sSearch } ); aoData.push( { "name": "bRegex", "value": oSettings.oPreviousSearch.bRegex } ); for ( i=0 ; i<iColumns ; i++ ) { aoData.push( { "name": "sSearch_"+i, "value": oSettings.aoPreSearchCols[i].sSearch } ); aoData.push( { "name": "bRegex_"+i, "value": oSettings.aoPreSearchCols[i].bRegex } ); aoData.push( { "name": "bSearchable_"+i, "value": oSettings.aoColumns[i].bSearchable } ); } } /* Sorting */ if ( oSettings.oFeatures.bSort !== false ) { var iCounter = 0; aaSort = ( oSettings.aaSortingFixed !== null ) ? oSettings.aaSortingFixed.concat( oSettings.aaSorting ) : oSettings.aaSorting.slice(); for ( i=0 ; i<aaSort.length ; i++ ) { aDataSort = oSettings.aoColumns[ aaSort[i][0] ].aDataSort; for ( j=0 ; j<aDataSort.length ; j++ ) { aoData.push( { "name": "iSortCol_"+iCounter, "value": aDataSort[j] } ); aoData.push( { "name": "sSortDir_"+iCounter, "value": aaSort[i][1] } ); iCounter++; } } aoData.push( { "name": "iSortingCols", "value": iCounter } ); for ( i=0 ; i<iColumns ; i++ ) { aoData.push( { "name": "bSortable_"+i, "value": oSettings.aoColumns[i].bSortable } ); } } return aoData; } /** * Add Ajax parameters from plug-ins * @param {object} oSettings dataTables settings object * @param array {objects} aoData name/value pairs to send to the server * @memberof DataTable#oApi */ function _fnServerParams( oSettings, aoData ) { _fnCallbackFire( oSettings, 'aoServerParams', 'serverParams', [aoData] ); } /** * Data the data from the server (nuking the old) and redraw the table * @param {object} oSettings dataTables settings object * @param {object} json json data return from the server. * @param {string} json.sEcho Tracking flag for DataTables to match requests * @param {int} json.iTotalRecords Number of records in the data set, not accounting for filtering * @param {int} json.iTotalDisplayRecords Number of records in the data set, accounting for filtering * @param {array} json.aaData The data to display on this page * @param {string} [json.sColumns] Column ordering (sName, comma separated) * @memberof DataTable#oApi */ function _fnAjaxUpdateDraw ( oSettings, json ) { if ( json.sEcho !== undefined ) { /* Protect against old returns over-writing a new one. Possible when you get * very fast interaction, and later queries are completed much faster */ if ( json.sEcho*1 < oSettings.iDraw ) { return; } else { oSettings.iDraw = json.sEcho * 1; } } if ( !oSettings.oScroll.bInfinite || (oSettings.oScroll.bInfinite && (oSettings.bSorted || oSettings.bFiltered)) ) { _fnClearTable( oSettings ); } oSettings._iRecordsTotal = parseInt(json.iTotalRecords, 10); oSettings._iRecordsDisplay = parseInt(json.iTotalDisplayRecords, 10); /* Determine if reordering is required */ var sOrdering = _fnColumnOrdering(oSettings); var bReOrder = (json.sColumns !== undefined && sOrdering !== "" && json.sColumns != sOrdering ); var aiIndex; if ( bReOrder ) { aiIndex = _fnReOrderIndex( oSettings, json.sColumns ); } var aData = _fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ); for ( var i=0, iLen=aData.length ; i<iLen ; i++ ) { if ( bReOrder ) { /* If we need to re-order, then create a new array with the correct order and add it */ var aDataSorted = []; for ( var j=0, jLen=oSettings.aoColumns.length ; j<jLen ; j++ ) { aDataSorted.push( aData[i][ aiIndex[j] ] ); } _fnAddData( oSettings, aDataSorted ); } else { /* No re-order required, sever got it "right" - just straight add */ _fnAddData( oSettings, aData[i] ); } } oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); oSettings.bAjaxDataGet = false; _fnDraw( oSettings ); oSettings.bAjaxDataGet = true; _fnProcessingDisplay( oSettings, false ); } /** * Generate the node required for filtering text * @returns {node} Filter control element * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnFeatureHtmlFilter ( oSettings ) { var oPreviousSearch = oSettings.oPreviousSearch; var sSearchStr = oSettings.oLanguage.sSearch; sSearchStr = (sSearchStr.indexOf('_INPUT_') !== -1) ? sSearchStr.replace('_INPUT_', '<input type="text" />') : sSearchStr==="" ? '<input type="text" />' : sSearchStr+' <input type="text" />'; var nFilter = document.createElement( 'div' ); nFilter.className = oSettings.oClasses.sFilter; nFilter.innerHTML = '<label>'+sSearchStr+'</label>'; if ( !oSettings.aanFeatures.f ) { nFilter.id = oSettings.sTableId+'_filter'; } var jqFilter = $('input[type="text"]', nFilter); // Store a reference to the input element, so other input elements could be // added to the filter wrapper if needed (submit button for example) nFilter._DT_Input = jqFilter[0]; jqFilter.val( oPreviousSearch.sSearch.replace('"','&quot;') ); jqFilter.bind( 'keyup.DT', function(e) { /* Update all other filter input elements for the new display */ var n = oSettings.aanFeatures.f; var val = this.value==="" ? "" : this.value; // mental IE8 fix :-( for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { if ( n[i] != $(this).parents('div.dataTables_filter')[0] ) { $(n[i]._DT_Input).val( val ); } } /* Now do the filter */ if ( val != oPreviousSearch.sSearch ) { _fnFilterComplete( oSettings, { "sSearch": val, "bRegex": oPreviousSearch.bRegex, "bSmart": oPreviousSearch.bSmart , "bCaseInsensitive": oPreviousSearch.bCaseInsensitive } ); } } ); jqFilter .attr('aria-controls', oSettings.sTableId) .bind( 'keypress.DT', function(e) { /* Prevent form submission */ if ( e.keyCode == 13 ) { return false; } } ); return nFilter; } /** * Filter the table using both the global filter and column based filtering * @param {object} oSettings dataTables settings object * @param {object} oSearch search information * @param {int} [iForce] force a research of the master array (1) or not (undefined or 0) * @memberof DataTable#oApi */ function _fnFilterComplete ( oSettings, oInput, iForce ) { var oPrevSearch = oSettings.oPreviousSearch; var aoPrevSearch = oSettings.aoPreSearchCols; var fnSaveFilter = function ( oFilter ) { /* Save the filtering values */ oPrevSearch.sSearch = oFilter.sSearch; oPrevSearch.bRegex = oFilter.bRegex; oPrevSearch.bSmart = oFilter.bSmart; oPrevSearch.bCaseInsensitive = oFilter.bCaseInsensitive; }; /* In server-side processing all filtering is done by the server, so no point hanging around here */ if ( !oSettings.oFeatures.bServerSide ) { /* Global filter */ _fnFilter( oSettings, oInput.sSearch, iForce, oInput.bRegex, oInput.bSmart, oInput.bCaseInsensitive ); fnSaveFilter( oInput ); /* Now do the individual column filter */ for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ) { _fnFilterColumn( oSettings, aoPrevSearch[i].sSearch, i, aoPrevSearch[i].bRegex, aoPrevSearch[i].bSmart, aoPrevSearch[i].bCaseInsensitive ); } /* Custom filtering */ _fnFilterCustom( oSettings ); } else { fnSaveFilter( oInput ); } /* Tell the draw function we have been filtering */ oSettings.bFiltered = true; $(oSettings.oInstance).trigger('filter', oSettings); /* Redraw the table */ oSettings._iDisplayStart = 0; _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); /* Rebuild search array 'offline' */ _fnBuildSearchArray( oSettings, 0 ); } /** * Apply custom filtering functions * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnFilterCustom( oSettings ) { var afnFilters = DataTable.ext.afnFiltering; var aiFilterColumns = _fnGetColumns( oSettings, 'bSearchable' ); for ( var i=0, iLen=afnFilters.length ; i<iLen ; i++ ) { var iCorrector = 0; for ( var j=0, jLen=oSettings.aiDisplay.length ; j<jLen ; j++ ) { var iDisIndex = oSettings.aiDisplay[j-iCorrector]; var bTest = afnFilters[i]( oSettings, _fnGetRowData( oSettings, iDisIndex, 'filter', aiFilterColumns ), iDisIndex ); /* Check if we should use this row based on the filtering function */ if ( !bTest ) { oSettings.aiDisplay.splice( j-iCorrector, 1 ); iCorrector++; } } } } /** * Filter the table on a per-column basis * @param {object} oSettings dataTables settings object * @param {string} sInput string to filter on * @param {int} iColumn column to filter * @param {bool} bRegex treat search string as a regular expression or not * @param {bool} bSmart use smart filtering or not * @param {bool} bCaseInsensitive Do case insenstive matching or not * @memberof DataTable#oApi */ function _fnFilterColumn ( oSettings, sInput, iColumn, bRegex, bSmart, bCaseInsensitive ) { if ( sInput === "" ) { return; } var iIndexCorrector = 0; var rpSearch = _fnFilterCreateSearch( sInput, bRegex, bSmart, bCaseInsensitive ); for ( var i=oSettings.aiDisplay.length-1 ; i>=0 ; i-- ) { var sData = _fnDataToSearch( _fnGetCellData( oSettings, oSettings.aiDisplay[i], iColumn, 'filter' ), oSettings.aoColumns[iColumn].sType ); if ( ! rpSearch.test( sData ) ) { oSettings.aiDisplay.splice( i, 1 ); iIndexCorrector++; } } } /** * Filter the data table based on user input and draw the table * @param {object} oSettings dataTables settings object * @param {string} sInput string to filter on * @param {int} iForce optional - force a research of the master array (1) or not (undefined or 0) * @param {bool} bRegex treat as a regular expression or not * @param {bool} bSmart perform smart filtering or not * @param {bool} bCaseInsensitive Do case insenstive matching or not * @memberof DataTable#oApi */ function _fnFilter( oSettings, sInput, iForce, bRegex, bSmart, bCaseInsensitive ) { var i; var rpSearch = _fnFilterCreateSearch( sInput, bRegex, bSmart, bCaseInsensitive ); var oPrevSearch = oSettings.oPreviousSearch; /* Check if we are forcing or not - optional parameter */ if ( !iForce ) { iForce = 0; } /* Need to take account of custom filtering functions - always filter */ if ( DataTable.ext.afnFiltering.length !== 0 ) { iForce = 1; } /* * If the input is blank - we want the full data set */ if ( sInput.length <= 0 ) { oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length); oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); } else { /* * We are starting a new search or the new search string is smaller * then the old one (i.e. delete). Search from the master array */ if ( oSettings.aiDisplay.length == oSettings.aiDisplayMaster.length || oPrevSearch.sSearch.length > sInput.length || iForce == 1 || sInput.indexOf(oPrevSearch.sSearch) !== 0 ) { /* Nuke the old display array - we are going to rebuild it */ oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length); /* Force a rebuild of the search array */ _fnBuildSearchArray( oSettings, 1 ); /* Search through all records to populate the search array * The the oSettings.aiDisplayMaster and asDataSearch arrays have 1 to 1 * mapping */ for ( i=0 ; i<oSettings.aiDisplayMaster.length ; i++ ) { if ( rpSearch.test(oSettings.asDataSearch[i]) ) { oSettings.aiDisplay.push( oSettings.aiDisplayMaster[i] ); } } } else { /* Using old search array - refine it - do it this way for speed * Don't have to search the whole master array again */ var iIndexCorrector = 0; /* Search the current results */ for ( i=0 ; i<oSettings.asDataSearch.length ; i++ ) { if ( ! rpSearch.test(oSettings.asDataSearch[i]) ) { oSettings.aiDisplay.splice( i-iIndexCorrector, 1 ); iIndexCorrector++; } } } } } /** * Create an array which can be quickly search through * @param {object} oSettings dataTables settings object * @param {int} iMaster use the master data array - optional * @memberof DataTable#oApi */ function _fnBuildSearchArray ( oSettings, iMaster ) { if ( !oSettings.oFeatures.bServerSide ) { /* Clear out the old data */ oSettings.asDataSearch = []; var aiFilterColumns = _fnGetColumns( oSettings, 'bSearchable' ); var aiIndex = (iMaster===1) ? oSettings.aiDisplayMaster : oSettings.aiDisplay; for ( var i=0, iLen=aiIndex.length ; i<iLen ; i++ ) { oSettings.asDataSearch[i] = _fnBuildSearchRow( oSettings, _fnGetRowData( oSettings, aiIndex[i], 'filter', aiFilterColumns ) ); } } } /** * Create a searchable string from a single data row * @param {object} oSettings dataTables settings object * @param {array} aData Row data array to use for the data to search * @memberof DataTable#oApi */ function _fnBuildSearchRow( oSettings, aData ) { var sSearch = aData.join(' '); /* If it looks like there is an HTML entity in the string, attempt to decode it */ if ( sSearch.indexOf('&') !== -1 ) { sSearch = $('<div>').html(sSearch).text(); } // Strip newline characters return sSearch.replace( /[\n\r]/g, " " ); } /** * Build a regular expression object suitable for searching a table * @param {string} sSearch string to search for * @param {bool} bRegex treat as a regular expression or not * @param {bool} bSmart perform smart filtering or not * @param {bool} bCaseInsensitive Do case insensitive matching or not * @returns {RegExp} constructed object * @memberof DataTable#oApi */ function _fnFilterCreateSearch( sSearch, bRegex, bSmart, bCaseInsensitive ) { var asSearch, sRegExpString; if ( bSmart ) { /* Generate the regular expression to use. Something along the lines of: * ^(?=.*?\bone\b)(?=.*?\btwo\b)(?=.*?\bthree\b).*$ */ asSearch = bRegex ? sSearch.split( ' ' ) : _fnEscapeRegex( sSearch ).split( ' ' ); sRegExpString = '^(?=.*?'+asSearch.join( ')(?=.*?' )+').*$'; return new RegExp( sRegExpString, bCaseInsensitive ? "i" : "" ); } else { sSearch = bRegex ? sSearch : _fnEscapeRegex( sSearch ); return new RegExp( sSearch, bCaseInsensitive ? "i" : "" ); } } /** * Convert raw data into something that the user can search on * @param {string} sData data to be modified * @param {string} sType data type * @returns {string} search string * @memberof DataTable#oApi */ function _fnDataToSearch ( sData, sType ) { if ( typeof DataTable.ext.ofnSearch[sType] === "function" ) { return DataTable.ext.ofnSearch[sType]( sData ); } else if ( sData === null ) { return ''; } else if ( sType == "html" ) { return sData.replace(/[\r\n]/g," ").replace( /<.*?>/g, "" ); } else if ( typeof sData === "string" ) { return sData.replace(/[\r\n]/g," "); } return sData; } /** * scape a string such that it can be used in a regular expression * @param {string} sVal string to escape * @returns {string} escaped string * @memberof DataTable#oApi */ function _fnEscapeRegex ( sVal ) { var acEscape = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^', '-' ]; var reReplace = new RegExp( '(\\' + acEscape.join('|\\') + ')', 'g' ); return sVal.replace(reReplace, '\\$1'); } /** * Generate the node required for the info display * @param {object} oSettings dataTables settings object * @returns {node} Information element * @memberof DataTable#oApi */ function _fnFeatureHtmlInfo ( oSettings ) { var nInfo = document.createElement( 'div' ); nInfo.className = oSettings.oClasses.sInfo; /* Actions that are to be taken once only for this feature */ if ( !oSettings.aanFeatures.i ) { /* Add draw callback */ oSettings.aoDrawCallback.push( { "fn": _fnUpdateInfo, "sName": "information" } ); /* Add id */ nInfo.id = oSettings.sTableId+'_info'; } oSettings.nTable.setAttribute( 'aria-describedby', oSettings.sTableId+'_info' ); return nInfo; } /** * Update the information elements in the display * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnUpdateInfo ( oSettings ) { /* Show information about the table */ if ( !oSettings.oFeatures.bInfo || oSettings.aanFeatures.i.length === 0 ) { return; } var oLang = oSettings.oLanguage, iStart = oSettings._iDisplayStart+1, iEnd = oSettings.fnDisplayEnd(), iMax = oSettings.fnRecordsTotal(), iTotal = oSettings.fnRecordsDisplay(), sOut; if ( iTotal === 0 ) { /* Empty record set */ sOut = oLang.sInfoEmpty; } else { /* Normal record set */ sOut = oLang.sInfo; } if ( iTotal != iMax ) { /* Record set after filtering */ sOut += ' ' + oLang.sInfoFiltered; } // Convert the macros sOut += oLang.sInfoPostFix; sOut = _fnInfoMacros( oSettings, sOut ); if ( oLang.fnInfoCallback !== null ) { sOut = oLang.fnInfoCallback.call( oSettings.oInstance, oSettings, iStart, iEnd, iMax, iTotal, sOut ); } var n = oSettings.aanFeatures.i; for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { $(n[i]).html( sOut ); } } function _fnInfoMacros ( oSettings, str ) { var iStart = oSettings._iDisplayStart+1, sStart = oSettings.fnFormatNumber( iStart ), iEnd = oSettings.fnDisplayEnd(), sEnd = oSettings.fnFormatNumber( iEnd ), iTotal = oSettings.fnRecordsDisplay(), sTotal = oSettings.fnFormatNumber( iTotal ), iMax = oSettings.fnRecordsTotal(), sMax = oSettings.fnFormatNumber( iMax ); // When infinite scrolling, we are always starting at 1. _iDisplayStart is used only // internally if ( oSettings.oScroll.bInfinite ) { sStart = oSettings.fnFormatNumber( 1 ); } return str. replace(/_START_/g, sStart). replace(/_END_/g, sEnd). replace(/_TOTAL_/g, sTotal). replace(/_MAX_/g, sMax); } /** * Draw the table for the first time, adding all required features * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnInitialise ( oSettings ) { var i, iLen, iAjaxStart=oSettings.iInitDisplayStart; /* Ensure that the table data is fully initialised */ if ( oSettings.bInitialised === false ) { setTimeout( function(){ _fnInitialise( oSettings ); }, 200 ); return; } /* Show the display HTML options */ _fnAddOptionsHtml( oSettings ); /* Build and draw the header / footer for the table */ _fnBuildHead( oSettings ); _fnDrawHead( oSettings, oSettings.aoHeader ); if ( oSettings.nTFoot ) { _fnDrawHead( oSettings, oSettings.aoFooter ); } /* Okay to show that something is going on now */ _fnProcessingDisplay( oSettings, true ); /* Calculate sizes for columns */ if ( oSettings.oFeatures.bAutoWidth ) { _fnCalculateColumnWidths( oSettings ); } for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { if ( oSettings.aoColumns[i].sWidth !== null ) { oSettings.aoColumns[i].nTh.style.width = _fnStringToCss( oSettings.aoColumns[i].sWidth ); } } /* If there is default sorting required - let's do it. The sort function will do the * drawing for us. Otherwise we draw the table regardless of the Ajax source - this allows * the table to look initialised for Ajax sourcing data (show 'loading' message possibly) */ if ( oSettings.oFeatures.bSort ) { _fnSort( oSettings ); } else if ( oSettings.oFeatures.bFilter ) { _fnFilterComplete( oSettings, oSettings.oPreviousSearch ); } else { oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } /* if there is an ajax source load the data */ if ( oSettings.sAjaxSource !== null && !oSettings.oFeatures.bServerSide ) { var aoData = []; _fnServerParams( oSettings, aoData ); oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, aoData, function(json) { var aData = (oSettings.sAjaxDataProp !== "") ? _fnGetObjectDataFn( oSettings.sAjaxDataProp )(json) : json; /* Got the data - add it to the table */ for ( i=0 ; i<aData.length ; i++ ) { _fnAddData( oSettings, aData[i] ); } /* Reset the init display for cookie saving. We've already done a filter, and * therefore cleared it before. So we need to make it appear 'fresh' */ oSettings.iInitDisplayStart = iAjaxStart; if ( oSettings.oFeatures.bSort ) { _fnSort( oSettings ); } else { oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } _fnProcessingDisplay( oSettings, false ); _fnInitComplete( oSettings, json ); }, oSettings ); return; } /* Server-side processing initialisation complete is done at the end of _fnDraw */ if ( !oSettings.oFeatures.bServerSide ) { _fnProcessingDisplay( oSettings, false ); _fnInitComplete( oSettings ); } } /** * Draw the table for the first time, adding all required features * @param {object} oSettings dataTables settings object * @param {object} [json] JSON from the server that completed the table, if using Ajax source * with client-side processing (optional) * @memberof DataTable#oApi */ function _fnInitComplete ( oSettings, json ) { oSettings._bInitComplete = true; _fnCallbackFire( oSettings, 'aoInitComplete', 'init', [oSettings, json] ); } /** * Language compatibility - when certain options are given, and others aren't, we * need to duplicate the values over, in order to provide backwards compatibility * with older language files. * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnLanguageCompat( oLanguage ) { var oDefaults = DataTable.defaults.oLanguage; /* Backwards compatibility - if there is no sEmptyTable given, then use the same as * sZeroRecords - assuming that is given. */ if ( !oLanguage.sEmptyTable && oLanguage.sZeroRecords && oDefaults.sEmptyTable === "No data available in table" ) { _fnMap( oLanguage, oLanguage, 'sZeroRecords', 'sEmptyTable' ); } /* Likewise with loading records */ if ( !oLanguage.sLoadingRecords && oLanguage.sZeroRecords && oDefaults.sLoadingRecords === "Loading..." ) { _fnMap( oLanguage, oLanguage, 'sZeroRecords', 'sLoadingRecords' ); } } /** * Generate the node required for user display length changing * @param {object} oSettings dataTables settings object * @returns {node} Display length feature node * @memberof DataTable#oApi */ function _fnFeatureHtmlLength ( oSettings ) { if ( oSettings.oScroll.bInfinite ) { return null; } /* This can be overruled by not using the _MENU_ var/macro in the language variable */ var sName = 'name="'+oSettings.sTableId+'_length"'; var sStdMenu = '<select size="1" '+sName+'>'; var i, iLen; var aLengthMenu = oSettings.aLengthMenu; if ( aLengthMenu.length == 2 && typeof aLengthMenu[0] === 'object' && typeof aLengthMenu[1] === 'object' ) { for ( i=0, iLen=aLengthMenu[0].length ; i<iLen ; i++ ) { sStdMenu += '<option value="'+aLengthMenu[0][i]+'">'+aLengthMenu[1][i]+'</option>'; } } else { for ( i=0, iLen=aLengthMenu.length ; i<iLen ; i++ ) { sStdMenu += '<option value="'+aLengthMenu[i]+'">'+aLengthMenu[i]+'</option>'; } } sStdMenu += '</select>'; var nLength = document.createElement( 'div' ); if ( !oSettings.aanFeatures.l ) { nLength.id = oSettings.sTableId+'_length'; } nLength.className = oSettings.oClasses.sLength; nLength.innerHTML = '<label>'+oSettings.oLanguage.sLengthMenu.replace( '_MENU_', sStdMenu )+'</label>'; /* * Set the length to the current display length - thanks to Andrea Pavlovic for this fix, * and Stefan Skopnik for fixing the fix! */ $('select option[value="'+oSettings._iDisplayLength+'"]', nLength).attr("selected", true); $('select', nLength).bind( 'change.DT', function(e) { var iVal = $(this).val(); /* Update all other length options for the new display */ var n = oSettings.aanFeatures.l; for ( i=0, iLen=n.length ; i<iLen ; i++ ) { if ( n[i] != this.parentNode ) { $('select', n[i]).val( iVal ); } } /* Redraw the table */ oSettings._iDisplayLength = parseInt(iVal, 10); _fnCalculateEnd( oSettings ); /* If we have space to show extra rows (backing up from the end point - then do so */ if ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() ) { oSettings._iDisplayStart = oSettings.fnDisplayEnd() - oSettings._iDisplayLength; if ( oSettings._iDisplayStart < 0 ) { oSettings._iDisplayStart = 0; } } if ( oSettings._iDisplayLength == -1 ) { oSettings._iDisplayStart = 0; } _fnDraw( oSettings ); } ); $('select', nLength).attr('aria-controls', oSettings.sTableId); return nLength; } /** * Recalculate the end point based on the start point * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnCalculateEnd( oSettings ) { if ( oSettings.oFeatures.bPaginate === false ) { oSettings._iDisplayEnd = oSettings.aiDisplay.length; } else { /* Set the end point of the display - based on how many elements there are * still to display */ if ( oSettings._iDisplayStart + oSettings._iDisplayLength > oSettings.aiDisplay.length || oSettings._iDisplayLength == -1 ) { oSettings._iDisplayEnd = oSettings.aiDisplay.length; } else { oSettings._iDisplayEnd = oSettings._iDisplayStart + oSettings._iDisplayLength; } } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Note that most of the paging logic is done in * DataTable.ext.oPagination */ /** * Generate the node required for default pagination * @param {object} oSettings dataTables settings object * @returns {node} Pagination feature node * @memberof DataTable#oApi */ function _fnFeatureHtmlPaginate ( oSettings ) { if ( oSettings.oScroll.bInfinite ) { return null; } var nPaginate = document.createElement( 'div' ); nPaginate.className = oSettings.oClasses.sPaging+oSettings.sPaginationType; DataTable.ext.oPagination[ oSettings.sPaginationType ].fnInit( oSettings, nPaginate, function( oSettings ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } ); /* Add a draw callback for the pagination on first instance, to update the paging display */ if ( !oSettings.aanFeatures.p ) { oSettings.aoDrawCallback.push( { "fn": function( oSettings ) { DataTable.ext.oPagination[ oSettings.sPaginationType ].fnUpdate( oSettings, function( oSettings ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } ); }, "sName": "pagination" } ); } return nPaginate; } /** * Alter the display settings to change the page * @param {object} oSettings dataTables settings object * @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last" * or page number to jump to (integer) * @returns {bool} true page has changed, false - no change (no effect) eg 'first' on page 1 * @memberof DataTable#oApi */ function _fnPageChange ( oSettings, mAction ) { var iOldStart = oSettings._iDisplayStart; if ( typeof mAction === "number" ) { oSettings._iDisplayStart = mAction * oSettings._iDisplayLength; if ( oSettings._iDisplayStart > oSettings.fnRecordsDisplay() ) { oSettings._iDisplayStart = 0; } } else if ( mAction == "first" ) { oSettings._iDisplayStart = 0; } else if ( mAction == "previous" ) { oSettings._iDisplayStart = oSettings._iDisplayLength>=0 ? oSettings._iDisplayStart - oSettings._iDisplayLength : 0; /* Correct for under-run */ if ( oSettings._iDisplayStart < 0 ) { oSettings._iDisplayStart = 0; } } else if ( mAction == "next" ) { if ( oSettings._iDisplayLength >= 0 ) { /* Make sure we are not over running the display array */ if ( oSettings._iDisplayStart + oSettings._iDisplayLength < oSettings.fnRecordsDisplay() ) { oSettings._iDisplayStart += oSettings._iDisplayLength; } } else { oSettings._iDisplayStart = 0; } } else if ( mAction == "last" ) { if ( oSettings._iDisplayLength >= 0 ) { var iPages = parseInt( (oSettings.fnRecordsDisplay()-1) / oSettings._iDisplayLength, 10 ) + 1; oSettings._iDisplayStart = (iPages-1) * oSettings._iDisplayLength; } else { oSettings._iDisplayStart = 0; } } else { _fnLog( oSettings, 0, "Unknown paging action: "+mAction ); } $(oSettings.oInstance).trigger('page', oSettings); return iOldStart != oSettings._iDisplayStart; } /** * Generate the node required for the processing node * @param {object} oSettings dataTables settings object * @returns {node} Processing element * @memberof DataTable#oApi */ function _fnFeatureHtmlProcessing ( oSettings ) { var nProcessing = document.createElement( 'div' ); if ( !oSettings.aanFeatures.r ) { nProcessing.id = oSettings.sTableId+'_processing'; } nProcessing.innerHTML = oSettings.oLanguage.sProcessing; nProcessing.className = oSettings.oClasses.sProcessing; oSettings.nTable.parentNode.insertBefore( nProcessing, oSettings.nTable ); return nProcessing; } /** * Display or hide the processing indicator * @param {object} oSettings dataTables settings object * @param {bool} bShow Show the processing indicator (true) or not (false) * @memberof DataTable#oApi */ function _fnProcessingDisplay ( oSettings, bShow ) { if ( oSettings.oFeatures.bProcessing ) { var an = oSettings.aanFeatures.r; for ( var i=0, iLen=an.length ; i<iLen ; i++ ) { an[i].style.visibility = bShow ? "visible" : "hidden"; } } $(oSettings.oInstance).trigger('processing', [oSettings, bShow]); } /** * Add any control elements for the table - specifically scrolling * @param {object} oSettings dataTables settings object * @returns {node} Node to add to the DOM * @memberof DataTable#oApi */ function _fnFeatureHtmlTable ( oSettings ) { /* Check if scrolling is enabled or not - if not then leave the DOM unaltered */ if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY === "" ) { return oSettings.nTable; } /* * The HTML structure that we want to generate in this function is: * div - nScroller * div - nScrollHead * div - nScrollHeadInner * table - nScrollHeadTable * thead - nThead * div - nScrollBody * table - oSettings.nTable * thead - nTheadSize * tbody - nTbody * div - nScrollFoot * div - nScrollFootInner * table - nScrollFootTable * tfoot - nTfoot */ var nScroller = document.createElement('div'), nScrollHead = document.createElement('div'), nScrollHeadInner = document.createElement('div'), nScrollBody = document.createElement('div'), nScrollFoot = document.createElement('div'), nScrollFootInner = document.createElement('div'), nScrollHeadTable = oSettings.nTable.cloneNode(false), nScrollFootTable = oSettings.nTable.cloneNode(false), nThead = oSettings.nTable.getElementsByTagName('thead')[0], nTfoot = oSettings.nTable.getElementsByTagName('tfoot').length === 0 ? null : oSettings.nTable.getElementsByTagName('tfoot')[0], oClasses = oSettings.oClasses; nScrollHead.appendChild( nScrollHeadInner ); nScrollFoot.appendChild( nScrollFootInner ); nScrollBody.appendChild( oSettings.nTable ); nScroller.appendChild( nScrollHead ); nScroller.appendChild( nScrollBody ); nScrollHeadInner.appendChild( nScrollHeadTable ); nScrollHeadTable.appendChild( nThead ); if ( nTfoot !== null ) { nScroller.appendChild( nScrollFoot ); nScrollFootInner.appendChild( nScrollFootTable ); nScrollFootTable.appendChild( nTfoot ); } nScroller.className = oClasses.sScrollWrapper; nScrollHead.className = oClasses.sScrollHead; nScrollHeadInner.className = oClasses.sScrollHeadInner; nScrollBody.className = oClasses.sScrollBody; nScrollFoot.className = oClasses.sScrollFoot; nScrollFootInner.className = oClasses.sScrollFootInner; if ( oSettings.oScroll.bAutoCss ) { nScrollHead.style.overflow = "hidden"; nScrollHead.style.position = "relative"; nScrollFoot.style.overflow = "hidden"; nScrollBody.style.overflow = "auto"; } nScrollHead.style.border = "0"; nScrollHead.style.width = "100%"; nScrollFoot.style.border = "0"; nScrollHeadInner.style.width = oSettings.oScroll.sXInner !== "" ? oSettings.oScroll.sXInner : "100%"; /* will be overwritten */ /* Modify attributes to respect the clones */ nScrollHeadTable.removeAttribute('id'); nScrollHeadTable.style.marginLeft = "0"; oSettings.nTable.style.marginLeft = "0"; if ( nTfoot !== null ) { nScrollFootTable.removeAttribute('id'); nScrollFootTable.style.marginLeft = "0"; } /* Move caption elements from the body to the header, footer or leave where it is * depending on the configuration. Note that the DTD says there can be only one caption */ var nCaption = $(oSettings.nTable).children('caption'); if ( nCaption.length > 0 ) { nCaption = nCaption[0]; if ( nCaption._captionSide === "top" ) { nScrollHeadTable.appendChild( nCaption ); } else if ( nCaption._captionSide === "bottom" && nTfoot ) { nScrollFootTable.appendChild( nCaption ); } } /* * Sizing */ /* When x-scrolling add the width and a scroller to move the header with the body */ if ( oSettings.oScroll.sX !== "" ) { nScrollHead.style.width = _fnStringToCss( oSettings.oScroll.sX ); nScrollBody.style.width = _fnStringToCss( oSettings.oScroll.sX ); if ( nTfoot !== null ) { nScrollFoot.style.width = _fnStringToCss( oSettings.oScroll.sX ); } /* When the body is scrolled, then we also want to scroll the headers */ $(nScrollBody).scroll( function (e) { nScrollHead.scrollLeft = this.scrollLeft; if ( nTfoot !== null ) { nScrollFoot.scrollLeft = this.scrollLeft; } } ); } /* When yscrolling, add the height */ if ( oSettings.oScroll.sY !== "" ) { nScrollBody.style.height = _fnStringToCss( oSettings.oScroll.sY ); } /* Redraw - align columns across the tables */ oSettings.aoDrawCallback.push( { "fn": _fnScrollDraw, "sName": "scrolling" } ); /* Infinite scrolling event handlers */ if ( oSettings.oScroll.bInfinite ) { $(nScrollBody).scroll( function() { /* Use a blocker to stop scrolling from loading more data while other data is still loading */ if ( !oSettings.bDrawing && $(this).scrollTop() !== 0 ) { /* Check if we should load the next data set */ if ( $(this).scrollTop() + $(this).height() > $(oSettings.nTable).height() - oSettings.oScroll.iLoadGap ) { /* Only do the redraw if we have to - we might be at the end of the data */ if ( oSettings.fnDisplayEnd() < oSettings.fnRecordsDisplay() ) { _fnPageChange( oSettings, 'next' ); _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } } } } ); } oSettings.nScrollHead = nScrollHead; oSettings.nScrollFoot = nScrollFoot; return nScroller; } /** * Update the various tables for resizing. It's a bit of a pig this function, but * basically the idea to: * 1. Re-create the table inside the scrolling div * 2. Take live measurements from the DOM * 3. Apply the measurements * 4. Clean up * @param {object} o dataTables settings object * @returns {node} Node to add to the DOM * @memberof DataTable#oApi */ function _fnScrollDraw ( o ) { var nScrollHeadInner = o.nScrollHead.getElementsByTagName('div')[0], nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0], nScrollBody = o.nTable.parentNode, i, iLen, j, jLen, anHeadToSize, anHeadSizers, anFootSizers, anFootToSize, oStyle, iVis, nTheadSize, nTfootSize, iWidth, aApplied=[], aAppliedFooter=[], iSanityWidth, nScrollFootInner = (o.nTFoot !== null) ? o.nScrollFoot.getElementsByTagName('div')[0] : null, nScrollFootTable = (o.nTFoot !== null) ? nScrollFootInner.getElementsByTagName('table')[0] : null, ie67 = o.oBrowser.bScrollOversize, zeroOut = function(nSizer) { oStyle = nSizer.style; oStyle.paddingTop = "0"; oStyle.paddingBottom = "0"; oStyle.borderTopWidth = "0"; oStyle.borderBottomWidth = "0"; oStyle.height = 0; }; /* * 1. Re-create the table inside the scrolling div */ /* Remove the old minimised thead and tfoot elements in the inner table */ $(o.nTable).children('thead, tfoot').remove(); /* Clone the current header and footer elements and then place it into the inner table */ nTheadSize = $(o.nTHead).clone()[0]; o.nTable.insertBefore( nTheadSize, o.nTable.childNodes[0] ); anHeadToSize = o.nTHead.getElementsByTagName('tr'); anHeadSizers = nTheadSize.getElementsByTagName('tr'); if ( o.nTFoot !== null ) { nTfootSize = $(o.nTFoot).clone()[0]; o.nTable.insertBefore( nTfootSize, o.nTable.childNodes[1] ); anFootToSize = o.nTFoot.getElementsByTagName('tr'); anFootSizers = nTfootSize.getElementsByTagName('tr'); } /* * 2. Take live measurements from the DOM - do not alter the DOM itself! */ /* Remove old sizing and apply the calculated column widths * Get the unique column headers in the newly created (cloned) header. We want to apply the * calculated sizes to this header */ if ( o.oScroll.sX === "" ) { nScrollBody.style.width = '100%'; nScrollHeadInner.parentNode.style.width = '100%'; } var nThs = _fnGetUniqueThs( o, nTheadSize ); for ( i=0, iLen=nThs.length ; i<iLen ; i++ ) { iVis = _fnVisibleToColumnIndex( o, i ); nThs[i].style.width = o.aoColumns[iVis].sWidth; } if ( o.nTFoot !== null ) { _fnApplyToChildren( function(n) { n.style.width = ""; }, anFootSizers ); } // If scroll collapse is enabled, when we put the headers back into the body for sizing, we // will end up forcing the scrollbar to appear, making our measurements wrong for when we // then hide it (end of this function), so add the header height to the body scroller. if ( o.oScroll.bCollapse && o.oScroll.sY !== "" ) { nScrollBody.style.height = (nScrollBody.offsetHeight + o.nTHead.offsetHeight)+"px"; } /* Size the table as a whole */ iSanityWidth = $(o.nTable).outerWidth(); if ( o.oScroll.sX === "" ) { /* No x scrolling */ o.nTable.style.width = "100%"; /* I know this is rubbish - but IE7 will make the width of the table when 100% include * the scrollbar - which is shouldn't. When there is a scrollbar we need to take this * into account. */ if ( ie67 && ($('tbody', nScrollBody).height() > nScrollBody.offsetHeight || $(nScrollBody).css('overflow-y') == "scroll") ) { o.nTable.style.width = _fnStringToCss( $(o.nTable).outerWidth() - o.oScroll.iBarWidth); } } else { if ( o.oScroll.sXInner !== "" ) { /* x scroll inner has been given - use it */ o.nTable.style.width = _fnStringToCss(o.oScroll.sXInner); } else if ( iSanityWidth == $(nScrollBody).width() && $(nScrollBody).height() < $(o.nTable).height() ) { /* There is y-scrolling - try to take account of the y scroll bar */ o.nTable.style.width = _fnStringToCss( iSanityWidth-o.oScroll.iBarWidth ); if ( $(o.nTable).outerWidth() > iSanityWidth-o.oScroll.iBarWidth ) { /* Not possible to take account of it */ o.nTable.style.width = _fnStringToCss( iSanityWidth ); } } else { /* All else fails */ o.nTable.style.width = _fnStringToCss( iSanityWidth ); } } /* Recalculate the sanity width - now that we've applied the required width, before it was * a temporary variable. This is required because the column width calculation is done * before this table DOM is created. */ iSanityWidth = $(o.nTable).outerWidth(); /* We want the hidden header to have zero height, so remove padding and borders. Then * set the width based on the real headers */ // Apply all styles in one pass. Invalidates layout only once because we don't read any // DOM properties. _fnApplyToChildren( zeroOut, anHeadSizers ); // Read all widths in next pass. Forces layout only once because we do not change // any DOM properties. _fnApplyToChildren( function(nSizer) { aApplied.push( _fnStringToCss( $(nSizer).width() ) ); }, anHeadSizers ); // Apply all widths in final pass. Invalidates layout only once because we do not // read any DOM properties. _fnApplyToChildren( function(nToSize, i) { nToSize.style.width = aApplied[i]; }, anHeadToSize ); $(anHeadSizers).height(0); /* Same again with the footer if we have one */ if ( o.nTFoot !== null ) { _fnApplyToChildren( zeroOut, anFootSizers ); _fnApplyToChildren( function(nSizer) { aAppliedFooter.push( _fnStringToCss( $(nSizer).width() ) ); }, anFootSizers ); _fnApplyToChildren( function(nToSize, i) { nToSize.style.width = aAppliedFooter[i]; }, anFootToSize ); $(anFootSizers).height(0); } /* * 3. Apply the measurements */ /* "Hide" the header and footer that we used for the sizing. We want to also fix their width * to what they currently are */ _fnApplyToChildren( function(nSizer, i) { nSizer.innerHTML = ""; nSizer.style.width = aApplied[i]; }, anHeadSizers ); if ( o.nTFoot !== null ) { _fnApplyToChildren( function(nSizer, i) { nSizer.innerHTML = ""; nSizer.style.width = aAppliedFooter[i]; }, anFootSizers ); } /* Sanity check that the table is of a sensible width. If not then we are going to get * misalignment - try to prevent this by not allowing the table to shrink below its min width */ if ( $(o.nTable).outerWidth() < iSanityWidth ) { /* The min width depends upon if we have a vertical scrollbar visible or not */ var iCorrection = ((nScrollBody.scrollHeight > nScrollBody.offsetHeight || $(nScrollBody).css('overflow-y') == "scroll")) ? iSanityWidth+o.oScroll.iBarWidth : iSanityWidth; /* IE6/7 are a law unto themselves... */ if ( ie67 && (nScrollBody.scrollHeight > nScrollBody.offsetHeight || $(nScrollBody).css('overflow-y') == "scroll") ) { o.nTable.style.width = _fnStringToCss( iCorrection-o.oScroll.iBarWidth ); } /* Apply the calculated minimum width to the table wrappers */ nScrollBody.style.width = _fnStringToCss( iCorrection ); o.nScrollHead.style.width = _fnStringToCss( iCorrection ); if ( o.nTFoot !== null ) { o.nScrollFoot.style.width = _fnStringToCss( iCorrection ); } /* And give the user a warning that we've stopped the table getting too small */ if ( o.oScroll.sX === "" ) { _fnLog( o, 1, "The table cannot fit into the current element which will cause column"+ " misalignment. The table has been drawn at its minimum possible width." ); } else if ( o.oScroll.sXInner !== "" ) { _fnLog( o, 1, "The table cannot fit into the current element which will cause column"+ " misalignment. Increase the sScrollXInner value or remove it to allow automatic"+ " calculation" ); } } else { nScrollBody.style.width = _fnStringToCss( '100%' ); o.nScrollHead.style.width = _fnStringToCss( '100%' ); if ( o.nTFoot !== null ) { o.nScrollFoot.style.width = _fnStringToCss( '100%' ); } } /* * 4. Clean up */ if ( o.oScroll.sY === "" ) { /* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting * the scrollbar height from the visible display, rather than adding it on. We need to * set the height in order to sort this. Don't want to do it in any other browsers. */ if ( ie67 ) { nScrollBody.style.height = _fnStringToCss( o.nTable.offsetHeight+o.oScroll.iBarWidth ); } } if ( o.oScroll.sY !== "" && o.oScroll.bCollapse ) { nScrollBody.style.height = _fnStringToCss( o.oScroll.sY ); var iExtra = (o.oScroll.sX !== "" && o.nTable.offsetWidth > nScrollBody.offsetWidth) ? o.oScroll.iBarWidth : 0; if ( o.nTable.offsetHeight < nScrollBody.offsetHeight ) { nScrollBody.style.height = _fnStringToCss( o.nTable.offsetHeight+iExtra ); } } /* Finally set the width's of the header and footer tables */ var iOuterWidth = $(o.nTable).outerWidth(); nScrollHeadTable.style.width = _fnStringToCss( iOuterWidth ); nScrollHeadInner.style.width = _fnStringToCss( iOuterWidth ); // Figure out if there are scrollbar present - if so then we need a the header and footer to // provide a bit more space to allow "overflow" scrolling (i.e. past the scrollbar) var bScrolling = $(o.nTable).height() > nScrollBody.clientHeight || $(nScrollBody).css('overflow-y') == "scroll"; nScrollHeadInner.style.paddingRight = bScrolling ? o.oScroll.iBarWidth+"px" : "0px"; if ( o.nTFoot !== null ) { nScrollFootTable.style.width = _fnStringToCss( iOuterWidth ); nScrollFootInner.style.width = _fnStringToCss( iOuterWidth ); nScrollFootInner.style.paddingRight = bScrolling ? o.oScroll.iBarWidth+"px" : "0px"; } /* Adjust the position of the header in case we loose the y-scrollbar */ $(nScrollBody).scroll(); /* If sorting or filtering has occurred, jump the scrolling back to the top */ if ( o.bSorted || o.bFiltered ) { nScrollBody.scrollTop = 0; } } /** * Apply a given function to the display child nodes of an element array (typically * TD children of TR rows * @param {function} fn Method to apply to the objects * @param array {nodes} an1 List of elements to look through for display children * @param array {nodes} an2 Another list (identical structure to the first) - optional * @memberof DataTable#oApi */ function _fnApplyToChildren( fn, an1, an2 ) { var index=0, i=0, iLen=an1.length; var nNode1, nNode2; while ( i < iLen ) { nNode1 = an1[i].firstChild; nNode2 = an2 ? an2[i].firstChild : null; while ( nNode1 ) { if ( nNode1.nodeType === 1 ) { if ( an2 ) { fn( nNode1, nNode2, index ); } else { fn( nNode1, index ); } index++; } nNode1 = nNode1.nextSibling; nNode2 = an2 ? nNode2.nextSibling : null; } i++; } } /** * Convert a CSS unit width to pixels (e.g. 2em) * @param {string} sWidth width to be converted * @param {node} nParent parent to get the with for (required for relative widths) - optional * @returns {int} iWidth width in pixels * @memberof DataTable#oApi */ function _fnConvertToWidth ( sWidth, nParent ) { if ( !sWidth || sWidth === null || sWidth === '' ) { return 0; } if ( !nParent ) { nParent = document.body; } var iWidth; var nTmp = document.createElement( "div" ); nTmp.style.width = _fnStringToCss( sWidth ); nParent.appendChild( nTmp ); iWidth = nTmp.offsetWidth; nParent.removeChild( nTmp ); return ( iWidth ); } /** * Calculate the width of columns for the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnCalculateColumnWidths ( oSettings ) { var iTableWidth = oSettings.nTable.offsetWidth; var iUserInputs = 0; var iTmpWidth; var iVisibleColumns = 0; var iColums = oSettings.aoColumns.length; var i, iIndex, iCorrector, iWidth; var oHeaders = $('th', oSettings.nTHead); var widthAttr = oSettings.nTable.getAttribute('width'); var nWrapper = oSettings.nTable.parentNode; /* Convert any user input sizes into pixel sizes */ for ( i=0 ; i<iColums ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { iVisibleColumns++; if ( oSettings.aoColumns[i].sWidth !== null ) { iTmpWidth = _fnConvertToWidth( oSettings.aoColumns[i].sWidthOrig, nWrapper ); if ( iTmpWidth !== null ) { oSettings.aoColumns[i].sWidth = _fnStringToCss( iTmpWidth ); } iUserInputs++; } } } /* If the number of columns in the DOM equals the number that we have to process in * DataTables, then we can use the offsets that are created by the web-browser. No custom * sizes can be set in order for this to happen, nor scrolling used */ if ( iColums == oHeaders.length && iUserInputs === 0 && iVisibleColumns == iColums && oSettings.oScroll.sX === "" && oSettings.oScroll.sY === "" ) { for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { iTmpWidth = $(oHeaders[i]).width(); if ( iTmpWidth !== null ) { oSettings.aoColumns[i].sWidth = _fnStringToCss( iTmpWidth ); } } } else { /* Otherwise we are going to have to do some calculations to get the width of each column. * Construct a 1 row table with the widest node in the data, and any user defined widths, * then insert it into the DOM and allow the browser to do all the hard work of * calculating table widths. */ var nCalcTmp = oSettings.nTable.cloneNode( false ), nTheadClone = oSettings.nTHead.cloneNode(true), nBody = document.createElement( 'tbody' ), nTr = document.createElement( 'tr' ), nDivSizing; nCalcTmp.removeAttribute( "id" ); nCalcTmp.appendChild( nTheadClone ); if ( oSettings.nTFoot !== null ) { nCalcTmp.appendChild( oSettings.nTFoot.cloneNode(true) ); _fnApplyToChildren( function(n) { n.style.width = ""; }, nCalcTmp.getElementsByTagName('tr') ); } nCalcTmp.appendChild( nBody ); nBody.appendChild( nTr ); /* Remove any sizing that was previously applied by the styles */ var jqColSizing = $('thead th', nCalcTmp); if ( jqColSizing.length === 0 ) { jqColSizing = $('tbody tr:eq(0)>td', nCalcTmp); } /* Apply custom sizing to the cloned header */ var nThs = _fnGetUniqueThs( oSettings, nTheadClone ); iCorrector = 0; for ( i=0 ; i<iColums ; i++ ) { var oColumn = oSettings.aoColumns[i]; if ( oColumn.bVisible && oColumn.sWidthOrig !== null && oColumn.sWidthOrig !== "" ) { nThs[i-iCorrector].style.width = _fnStringToCss( oColumn.sWidthOrig ); } else if ( oColumn.bVisible ) { nThs[i-iCorrector].style.width = ""; } else { iCorrector++; } } /* Find the biggest td for each column and put it into the table */ for ( i=0 ; i<iColums ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { var nTd = _fnGetWidestNode( oSettings, i ); if ( nTd !== null ) { nTd = nTd.cloneNode(true); if ( oSettings.aoColumns[i].sContentPadding !== "" ) { nTd.innerHTML += oSettings.aoColumns[i].sContentPadding; } nTr.appendChild( nTd ); } } } /* Build the table and 'display' it */ nWrapper.appendChild( nCalcTmp ); /* When scrolling (X or Y) we want to set the width of the table as appropriate. However, * when not scrolling leave the table width as it is. This results in slightly different, * but I think correct behaviour */ if ( oSettings.oScroll.sX !== "" && oSettings.oScroll.sXInner !== "" ) { nCalcTmp.style.width = _fnStringToCss(oSettings.oScroll.sXInner); } else if ( oSettings.oScroll.sX !== "" ) { nCalcTmp.style.width = ""; if ( $(nCalcTmp).width() < nWrapper.offsetWidth ) { nCalcTmp.style.width = _fnStringToCss( nWrapper.offsetWidth ); } } else if ( oSettings.oScroll.sY !== "" ) { nCalcTmp.style.width = _fnStringToCss( nWrapper.offsetWidth ); } else if ( widthAttr ) { nCalcTmp.style.width = _fnStringToCss( widthAttr ); } nCalcTmp.style.visibility = "hidden"; /* Scrolling considerations */ _fnScrollingWidthAdjust( oSettings, nCalcTmp ); /* Read the width's calculated by the browser and store them for use by the caller. We * first of all try to use the elements in the body, but it is possible that there are * no elements there, under which circumstances we use the header elements */ var oNodes = $("tbody tr:eq(0)", nCalcTmp).children(); if ( oNodes.length === 0 ) { oNodes = _fnGetUniqueThs( oSettings, $('thead', nCalcTmp)[0] ); } /* Browsers need a bit of a hand when a width is assigned to any columns when * x-scrolling as they tend to collapse the table to the min-width, even if * we sent the column widths. So we need to keep track of what the table width * should be by summing the user given values, and the automatic values */ if ( oSettings.oScroll.sX !== "" ) { var iTotal = 0; iCorrector = 0; for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { if ( oSettings.aoColumns[i].sWidthOrig === null ) { iTotal += $(oNodes[iCorrector]).outerWidth(); } else { iTotal += parseInt(oSettings.aoColumns[i].sWidth.replace('px',''), 10) + ($(oNodes[iCorrector]).outerWidth() - $(oNodes[iCorrector]).width()); } iCorrector++; } } nCalcTmp.style.width = _fnStringToCss( iTotal ); oSettings.nTable.style.width = _fnStringToCss( iTotal ); } iCorrector = 0; for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { iWidth = $(oNodes[iCorrector]).width(); if ( iWidth !== null && iWidth > 0 ) { oSettings.aoColumns[i].sWidth = _fnStringToCss( iWidth ); } iCorrector++; } } var cssWidth = $(nCalcTmp).css('width'); oSettings.nTable.style.width = (cssWidth.indexOf('%') !== -1) ? cssWidth : _fnStringToCss( $(nCalcTmp).outerWidth() ); nCalcTmp.parentNode.removeChild( nCalcTmp ); } if ( widthAttr ) { oSettings.nTable.style.width = _fnStringToCss( widthAttr ); } } /** * Adjust a table's width to take account of scrolling * @param {object} oSettings dataTables settings object * @param {node} n table node * @memberof DataTable#oApi */ function _fnScrollingWidthAdjust ( oSettings, n ) { if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY !== "" ) { /* When y-scrolling only, we want to remove the width of the scroll bar so the table * + scroll bar will fit into the area avaialble. */ var iOrigWidth = $(n).width(); n.style.width = _fnStringToCss( $(n).outerWidth()-oSettings.oScroll.iBarWidth ); } else if ( oSettings.oScroll.sX !== "" ) { /* When x-scrolling both ways, fix the table at it's current size, without adjusting */ n.style.width = _fnStringToCss( $(n).outerWidth() ); } } /** * Get the widest node * @param {object} oSettings dataTables settings object * @param {int} iCol column of interest * @returns {node} widest table node * @memberof DataTable#oApi */ function _fnGetWidestNode( oSettings, iCol ) { var iMaxIndex = _fnGetMaxLenString( oSettings, iCol ); if ( iMaxIndex < 0 ) { return null; } if ( oSettings.aoData[iMaxIndex].nTr === null ) { var n = document.createElement('td'); n.innerHTML = _fnGetCellData( oSettings, iMaxIndex, iCol, '' ); return n; } return _fnGetTdNodes(oSettings, iMaxIndex)[iCol]; } /** * Get the maximum strlen for each data column * @param {object} oSettings dataTables settings object * @param {int} iCol column of interest * @returns {string} max string length for each column * @memberof DataTable#oApi */ function _fnGetMaxLenString( oSettings, iCol ) { var iMax = -1; var iMaxIndex = -1; for ( var i=0 ; i<oSettings.aoData.length ; i++ ) { var s = _fnGetCellData( oSettings, i, iCol, 'display' )+""; s = s.replace( /<.*?>/g, "" ); if ( s.length > iMax ) { iMax = s.length; iMaxIndex = i; } } return iMaxIndex; } /** * Append a CSS unit (only if required) to a string * @param {array} aArray1 first array * @param {array} aArray2 second array * @returns {int} 0 if match, 1 if length is different, 2 if no match * @memberof DataTable#oApi */ function _fnStringToCss( s ) { if ( s === null ) { return "0px"; } if ( typeof s == 'number' ) { if ( s < 0 ) { return "0px"; } return s+"px"; } /* Check if the last character is not 0-9 */ var c = s.charCodeAt( s.length-1 ); if (c < 0x30 || c > 0x39) { return s; } return s+"px"; } /** * Get the width of a scroll bar in this browser being used * @returns {int} width in pixels * @memberof DataTable#oApi */ function _fnScrollBarWidth () { var inner = document.createElement('p'); var style = inner.style; style.width = "100%"; style.height = "200px"; style.padding = "0px"; var outer = document.createElement('div'); style = outer.style; style.position = "absolute"; style.top = "0px"; style.left = "0px"; style.visibility = "hidden"; style.width = "200px"; style.height = "150px"; style.padding = "0px"; style.overflow = "hidden"; outer.appendChild(inner); document.body.appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if ( w1 == w2 ) { w2 = outer.clientWidth; } document.body.removeChild(outer); return (w1 - w2); } /** * Change the order of the table * @param {object} oSettings dataTables settings object * @param {bool} bApplyClasses optional - should we apply classes or not * @memberof DataTable#oApi */ function _fnSort ( oSettings, bApplyClasses ) { var i, iLen, j, jLen, k, kLen, sDataType, nTh, aaSort = [], aiOrig = [], oSort = DataTable.ext.oSort, aoData = oSettings.aoData, aoColumns = oSettings.aoColumns, oAria = oSettings.oLanguage.oAria; /* No sorting required if server-side or no sorting array */ if ( !oSettings.oFeatures.bServerSide && (oSettings.aaSorting.length !== 0 || oSettings.aaSortingFixed !== null) ) { aaSort = ( oSettings.aaSortingFixed !== null ) ? oSettings.aaSortingFixed.concat( oSettings.aaSorting ) : oSettings.aaSorting.slice(); /* If there is a sorting data type, and a function belonging to it, then we need to * get the data from the developer's function and apply it for this column */ for ( i=0 ; i<aaSort.length ; i++ ) { var iColumn = aaSort[i][0]; var iVisColumn = _fnColumnIndexToVisible( oSettings, iColumn ); sDataType = oSettings.aoColumns[ iColumn ].sSortDataType; if ( DataTable.ext.afnSortData[sDataType] ) { var aData = DataTable.ext.afnSortData[sDataType].call( oSettings.oInstance, oSettings, iColumn, iVisColumn ); if ( aData.length === aoData.length ) { for ( j=0, jLen=aoData.length ; j<jLen ; j++ ) { _fnSetCellData( oSettings, j, iColumn, aData[j] ); } } else { _fnLog( oSettings, 0, "Returned data sort array (col "+iColumn+") is the wrong length" ); } } } /* Create a value - key array of the current row positions such that we can use their * current position during the sort, if values match, in order to perform stable sorting */ for ( i=0, iLen=oSettings.aiDisplayMaster.length ; i<iLen ; i++ ) { aiOrig[ oSettings.aiDisplayMaster[i] ] = i; } /* Build an internal data array which is specific to the sort, so we can get and prep * the data to be sorted only once, rather than needing to do it every time the sorting * function runs. This make the sorting function a very simple comparison */ var iSortLen = aaSort.length; var fnSortFormat, aDataSort; for ( i=0, iLen=aoData.length ; i<iLen ; i++ ) { for ( j=0 ; j<iSortLen ; j++ ) { aDataSort = aoColumns[ aaSort[j][0] ].aDataSort; for ( k=0, kLen=aDataSort.length ; k<kLen ; k++ ) { sDataType = aoColumns[ aDataSort[k] ].sType; fnSortFormat = oSort[ (sDataType ? sDataType : 'string')+"-pre" ]; aoData[i]._aSortData[ aDataSort[k] ] = fnSortFormat ? fnSortFormat( _fnGetCellData( oSettings, i, aDataSort[k], 'sort' ) ) : _fnGetCellData( oSettings, i, aDataSort[k], 'sort' ); } } } /* Do the sort - here we want multi-column sorting based on a given data source (column) * and sorting function (from oSort) in a certain direction. It's reasonably complex to * follow on it's own, but this is what we want (example two column sorting): * fnLocalSorting = function(a,b){ * var iTest; * iTest = oSort['string-asc']('data11', 'data12'); * if (iTest !== 0) * return iTest; * iTest = oSort['numeric-desc']('data21', 'data22'); * if (iTest !== 0) * return iTest; * return oSort['numeric-asc']( aiOrig[a], aiOrig[b] ); * } * Basically we have a test for each sorting column, if the data in that column is equal, * test the next column. If all columns match, then we use a numeric sort on the row * positions in the original data array to provide a stable sort. */ oSettings.aiDisplayMaster.sort( function ( a, b ) { var k, l, lLen, iTest, aDataSort, sDataType; for ( k=0 ; k<iSortLen ; k++ ) { aDataSort = aoColumns[ aaSort[k][0] ].aDataSort; for ( l=0, lLen=aDataSort.length ; l<lLen ; l++ ) { sDataType = aoColumns[ aDataSort[l] ].sType; iTest = oSort[ (sDataType ? sDataType : 'string')+"-"+aaSort[k][1] ]( aoData[a]._aSortData[ aDataSort[l] ], aoData[b]._aSortData[ aDataSort[l] ] ); if ( iTest !== 0 ) { return iTest; } } } return oSort['numeric-asc']( aiOrig[a], aiOrig[b] ); } ); } /* Alter the sorting classes to take account of the changes */ if ( (bApplyClasses === undefined || bApplyClasses) && !oSettings.oFeatures.bDeferRender ) { _fnSortingClasses( oSettings ); } for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { var sTitle = aoColumns[i].sTitle.replace( /<.*?>/g, "" ); nTh = aoColumns[i].nTh; nTh.removeAttribute('aria-sort'); nTh.removeAttribute('aria-label'); /* In ARIA only the first sorting column can be marked as sorting - no multi-sort option */ if ( aoColumns[i].bSortable ) { if ( aaSort.length > 0 && aaSort[0][0] == i ) { nTh.setAttribute('aria-sort', aaSort[0][1]=="asc" ? "ascending" : "descending" ); var nextSort = (aoColumns[i].asSorting[ aaSort[0][2]+1 ]) ? aoColumns[i].asSorting[ aaSort[0][2]+1 ] : aoColumns[i].asSorting[0]; nTh.setAttribute('aria-label', sTitle+ (nextSort=="asc" ? oAria.sSortAscending : oAria.sSortDescending) ); } else { nTh.setAttribute('aria-label', sTitle+ (aoColumns[i].asSorting[0]=="asc" ? oAria.sSortAscending : oAria.sSortDescending) ); } } else { nTh.setAttribute('aria-label', sTitle); } } /* Tell the draw function that we have sorted the data */ oSettings.bSorted = true; $(oSettings.oInstance).trigger('sort', oSettings); /* Copy the master data into the draw array and re-draw */ if ( oSettings.oFeatures.bFilter ) { /* _fnFilter() will redraw the table for us */ _fnFilterComplete( oSettings, oSettings.oPreviousSearch, 1 ); } else { oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); oSettings._iDisplayStart = 0; /* reset display back to page 0 */ _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } } /** * Attach a sort handler (click) to a node * @param {object} oSettings dataTables settings object * @param {node} nNode node to attach the handler to * @param {int} iDataIndex column sorting index * @param {function} [fnCallback] callback function * @memberof DataTable#oApi */ function _fnSortAttachListener ( oSettings, nNode, iDataIndex, fnCallback ) { _fnBindAction( nNode, {}, function (e) { /* If the column is not sortable - don't to anything */ if ( oSettings.aoColumns[iDataIndex].bSortable === false ) { return; } /* * This is a little bit odd I admit... I declare a temporary function inside the scope of * _fnBuildHead and the click handler in order that the code presented here can be used * twice - once for when bProcessing is enabled, and another time for when it is * disabled, as we need to perform slightly different actions. * Basically the issue here is that the Javascript engine in modern browsers don't * appear to allow the rendering engine to update the display while it is still executing * it's thread (well - it does but only after long intervals). This means that the * 'processing' display doesn't appear for a table sort. To break the js thread up a bit * I force an execution break by using setTimeout - but this breaks the expected * thread continuation for the end-developer's point of view (their code would execute * too early), so we only do it when we absolutely have to. */ var fnInnerSorting = function () { var iColumn, iNextSort; /* If the shift key is pressed then we are multiple column sorting */ if ( e.shiftKey ) { /* Are we already doing some kind of sort on this column? */ var bFound = false; for ( var i=0 ; i<oSettings.aaSorting.length ; i++ ) { if ( oSettings.aaSorting[i][0] == iDataIndex ) { bFound = true; iColumn = oSettings.aaSorting[i][0]; iNextSort = oSettings.aaSorting[i][2]+1; if ( !oSettings.aoColumns[iColumn].asSorting[iNextSort] ) { /* Reached the end of the sorting options, remove from multi-col sort */ oSettings.aaSorting.splice( i, 1 ); } else { /* Move onto next sorting direction */ oSettings.aaSorting[i][1] = oSettings.aoColumns[iColumn].asSorting[iNextSort]; oSettings.aaSorting[i][2] = iNextSort; } break; } } /* No sort yet - add it in */ if ( bFound === false ) { oSettings.aaSorting.push( [ iDataIndex, oSettings.aoColumns[iDataIndex].asSorting[0], 0 ] ); } } else { /* If no shift key then single column sort */ if ( oSettings.aaSorting.length == 1 && oSettings.aaSorting[0][0] == iDataIndex ) { iColumn = oSettings.aaSorting[0][0]; iNextSort = oSettings.aaSorting[0][2]+1; if ( !oSettings.aoColumns[iColumn].asSorting[iNextSort] ) { iNextSort = 0; } oSettings.aaSorting[0][1] = oSettings.aoColumns[iColumn].asSorting[iNextSort]; oSettings.aaSorting[0][2] = iNextSort; } else { oSettings.aaSorting.splice( 0, oSettings.aaSorting.length ); oSettings.aaSorting.push( [ iDataIndex, oSettings.aoColumns[iDataIndex].asSorting[0], 0 ] ); } } /* Run the sort */ _fnSort( oSettings ); }; /* /fnInnerSorting */ if ( !oSettings.oFeatures.bProcessing ) { fnInnerSorting(); } else { _fnProcessingDisplay( oSettings, true ); setTimeout( function() { fnInnerSorting(); if ( !oSettings.oFeatures.bServerSide ) { _fnProcessingDisplay( oSettings, false ); } }, 0 ); } /* Call the user specified callback function - used for async user interaction */ if ( typeof fnCallback == 'function' ) { fnCallback( oSettings ); } } ); } /** * Set the sorting classes on the header, Note: it is safe to call this function * when bSort and bSortClasses are false * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnSortingClasses( oSettings ) { var i, iLen, j, jLen, iFound; var aaSort, sClass; var iColumns = oSettings.aoColumns.length; var oClasses = oSettings.oClasses; for ( i=0 ; i<iColumns ; i++ ) { if ( oSettings.aoColumns[i].bSortable ) { $(oSettings.aoColumns[i].nTh).removeClass( oClasses.sSortAsc +" "+ oClasses.sSortDesc + " "+ oSettings.aoColumns[i].sSortingClass ); } } if ( oSettings.aaSortingFixed !== null ) { aaSort = oSettings.aaSortingFixed.concat( oSettings.aaSorting ); } else { aaSort = oSettings.aaSorting.slice(); } /* Apply the required classes to the header */ for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bSortable ) { sClass = oSettings.aoColumns[i].sSortingClass; iFound = -1; for ( j=0 ; j<aaSort.length ; j++ ) { if ( aaSort[j][0] == i ) { sClass = ( aaSort[j][1] == "asc" ) ? oClasses.sSortAsc : oClasses.sSortDesc; iFound = j; break; } } $(oSettings.aoColumns[i].nTh).addClass( sClass ); if ( oSettings.bJUI ) { /* jQuery UI uses extra markup */ var jqSpan = $("span."+oClasses.sSortIcon, oSettings.aoColumns[i].nTh); jqSpan.removeClass(oClasses.sSortJUIAsc +" "+ oClasses.sSortJUIDesc +" "+ oClasses.sSortJUI +" "+ oClasses.sSortJUIAscAllowed +" "+ oClasses.sSortJUIDescAllowed ); var sSpanClass; if ( iFound == -1 ) { sSpanClass = oSettings.aoColumns[i].sSortingClassJUI; } else if ( aaSort[iFound][1] == "asc" ) { sSpanClass = oClasses.sSortJUIAsc; } else { sSpanClass = oClasses.sSortJUIDesc; } jqSpan.addClass( sSpanClass ); } } else { /* No sorting on this column, so add the base class. This will have been assigned by * _fnAddColumn */ $(oSettings.aoColumns[i].nTh).addClass( oSettings.aoColumns[i].sSortingClass ); } } /* * Apply the required classes to the table body * Note that this is given as a feature switch since it can significantly slow down a sort * on large data sets (adding and removing of classes is always slow at the best of times..) * Further to this, note that this code is admittedly fairly ugly. It could be made a lot * simpler using jQuery selectors and add/removeClass, but that is significantly slower * (on the order of 5 times slower) - hence the direct DOM manipulation here. * Note that for deferred drawing we do use jQuery - the reason being that taking the first * row found to see if the whole column needs processed can miss classes since the first * column might be new. */ sClass = oClasses.sSortColumn; if ( oSettings.oFeatures.bSort && oSettings.oFeatures.bSortClasses ) { var nTds = _fnGetTdNodes( oSettings ); /* Determine what the sorting class for each column should be */ var iClass, iTargetCol; var asClasses = []; for (i = 0; i < iColumns; i++) { asClasses.push(""); } for (i = 0, iClass = 1; i < aaSort.length; i++) { iTargetCol = parseInt( aaSort[i][0], 10 ); asClasses[iTargetCol] = sClass + iClass; if ( iClass < 3 ) { iClass++; } } /* Make changes to the classes for each cell as needed */ var reClass = new RegExp(sClass + "[123]"); var sTmpClass, sCurrentClass, sNewClass; for ( i=0, iLen=nTds.length; i<iLen; i++ ) { /* Determine which column we're looking at */ iTargetCol = i % iColumns; /* What is the full list of classes now */ sCurrentClass = nTds[i].className; /* What sorting class should be applied? */ sNewClass = asClasses[iTargetCol]; /* What would the new full list be if we did a replacement? */ sTmpClass = sCurrentClass.replace(reClass, sNewClass); if ( sTmpClass != sCurrentClass ) { /* We changed something */ nTds[i].className = $.trim( sTmpClass ); } else if ( sNewClass.length > 0 && sCurrentClass.indexOf(sNewClass) == -1 ) { /* We need to add a class */ nTds[i].className = sCurrentClass + " " + sNewClass; } } } } /** * Save the state of a table in a cookie such that the page can be reloaded * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnSaveState ( oSettings ) { if ( !oSettings.oFeatures.bStateSave || oSettings.bDestroying ) { return; } /* Store the interesting variables */ var i, iLen, bInfinite=oSettings.oScroll.bInfinite; var oState = { "iCreate": new Date().getTime(), "iStart": (bInfinite ? 0 : oSettings._iDisplayStart), "iEnd": (bInfinite ? oSettings._iDisplayLength : oSettings._iDisplayEnd), "iLength": oSettings._iDisplayLength, "aaSorting": $.extend( true, [], oSettings.aaSorting ), "oSearch": $.extend( true, {}, oSettings.oPreviousSearch ), "aoSearchCols": $.extend( true, [], oSettings.aoPreSearchCols ), "abVisCols": [] }; for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { oState.abVisCols.push( oSettings.aoColumns[i].bVisible ); } _fnCallbackFire( oSettings, "aoStateSaveParams", 'stateSaveParams', [oSettings, oState] ); oSettings.fnStateSave.call( oSettings.oInstance, oSettings, oState ); } /** * Attempt to load a saved table state from a cookie * @param {object} oSettings dataTables settings object * @param {object} oInit DataTables init object so we can override settings * @memberof DataTable#oApi */ function _fnLoadState ( oSettings, oInit ) { if ( !oSettings.oFeatures.bStateSave ) { return; } var oData = oSettings.fnStateLoad.call( oSettings.oInstance, oSettings ); if ( !oData ) { return; } /* Allow custom and plug-in manipulation functions to alter the saved data set and * cancelling of loading by returning false */ var abStateLoad = _fnCallbackFire( oSettings, 'aoStateLoadParams', 'stateLoadParams', [oSettings, oData] ); if ( $.inArray( false, abStateLoad ) !== -1 ) { return; } /* Store the saved state so it might be accessed at any time */ oSettings.oLoadedState = $.extend( true, {}, oData ); /* Restore key features */ oSettings._iDisplayStart = oData.iStart; oSettings.iInitDisplayStart = oData.iStart; oSettings._iDisplayEnd = oData.iEnd; oSettings._iDisplayLength = oData.iLength; oSettings.aaSorting = oData.aaSorting.slice(); oSettings.saved_aaSorting = oData.aaSorting.slice(); /* Search filtering */ $.extend( oSettings.oPreviousSearch, oData.oSearch ); $.extend( true, oSettings.aoPreSearchCols, oData.aoSearchCols ); /* Column visibility state * Pass back visibility settings to the init handler, but to do not here override * the init object that the user might have passed in */ oInit.saved_aoColumns = []; for ( var i=0 ; i<oData.abVisCols.length ; i++ ) { oInit.saved_aoColumns[i] = {}; oInit.saved_aoColumns[i].bVisible = oData.abVisCols[i]; } _fnCallbackFire( oSettings, 'aoStateLoaded', 'stateLoaded', [oSettings, oData] ); } /** * Create a new cookie with a value to store the state of a table * @param {string} sName name of the cookie to create * @param {string} sValue the value the cookie should take * @param {int} iSecs duration of the cookie * @param {string} sBaseName sName is made up of the base + file name - this is the base * @param {function} fnCallback User definable function to modify the cookie * @memberof DataTable#oApi */ function _fnCreateCookie ( sName, sValue, iSecs, sBaseName, fnCallback ) { var date = new Date(); date.setTime( date.getTime()+(iSecs*1000) ); /* * Shocking but true - it would appear IE has major issues with having the path not having * a trailing slash on it. We need the cookie to be available based on the path, so we * have to append the file name to the cookie name. Appalling. Thanks to vex for adding the * patch to use at least some of the path */ var aParts = window.location.pathname.split('/'); var sNameFile = sName + '_' + aParts.pop().replace(/[\/:]/g,"").toLowerCase(); var sFullCookie, oData; if ( fnCallback !== null ) { oData = (typeof $.parseJSON === 'function') ? $.parseJSON( sValue ) : eval( '('+sValue+')' ); sFullCookie = fnCallback( sNameFile, oData, date.toGMTString(), aParts.join('/')+"/" ); } else { sFullCookie = sNameFile + "=" + encodeURIComponent(sValue) + "; expires=" + date.toGMTString() +"; path=" + aParts.join('/')+"/"; } /* Are we going to go over the cookie limit of 4KiB? If so, try to delete a cookies * belonging to DataTables. */ var aCookies =document.cookie.split(';'), iNewCookieLen = sFullCookie.split(';')[0].length, aOldCookies = []; if ( iNewCookieLen+document.cookie.length+10 > 4096 ) /* Magic 10 for padding */ { for ( var i=0, iLen=aCookies.length ; i<iLen ; i++ ) { if ( aCookies[i].indexOf( sBaseName ) != -1 ) { /* It's a DataTables cookie, so eval it and check the time stamp */ var aSplitCookie = aCookies[i].split('='); try { oData = eval( '('+decodeURIComponent(aSplitCookie[1])+')' ); if ( oData && oData.iCreate ) { aOldCookies.push( { "name": aSplitCookie[0], "time": oData.iCreate } ); } } catch( e ) {} } } // Make sure we delete the oldest ones first aOldCookies.sort( function (a, b) { return b.time - a.time; } ); // Eliminate as many old DataTables cookies as we need to while ( iNewCookieLen + document.cookie.length + 10 > 4096 ) { if ( aOldCookies.length === 0 ) { // Deleted all DT cookies and still not enough space. Can't state save return; } var old = aOldCookies.pop(); document.cookie = old.name+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path="+ aParts.join('/') + "/"; } } document.cookie = sFullCookie; } /** * Read an old cookie to get a cookie with an old table state * @param {string} sName name of the cookie to read * @returns {string} contents of the cookie - or null if no cookie with that name found * @memberof DataTable#oApi */ function _fnReadCookie ( sName ) { var aParts = window.location.pathname.split('/'), sNameEQ = sName + '_' + aParts[aParts.length-1].replace(/[\/:]/g,"").toLowerCase() + '=', sCookieContents = document.cookie.split(';'); for( var i=0 ; i<sCookieContents.length ; i++ ) { var c = sCookieContents[i]; while (c.charAt(0)==' ') { c = c.substring(1,c.length); } if (c.indexOf(sNameEQ) === 0) { return decodeURIComponent( c.substring(sNameEQ.length,c.length) ); } } return null; } /** * Return the settings object for a particular table * @param {node} nTable table we are using as a dataTable * @returns {object} Settings object - or null if not found * @memberof DataTable#oApi */ function _fnSettingsFromNode ( nTable ) { for ( var i=0 ; i<DataTable.settings.length ; i++ ) { if ( DataTable.settings[i].nTable === nTable ) { return DataTable.settings[i]; } } return null; } /** * Return an array with the TR nodes for the table * @param {object} oSettings dataTables settings object * @returns {array} TR array * @memberof DataTable#oApi */ function _fnGetTrNodes ( oSettings ) { var aNodes = []; var aoData = oSettings.aoData; for ( var i=0, iLen=aoData.length ; i<iLen ; i++ ) { if ( aoData[i].nTr !== null ) { aNodes.push( aoData[i].nTr ); } } return aNodes; } /** * Return an flat array with all TD nodes for the table, or row * @param {object} oSettings dataTables settings object * @param {int} [iIndividualRow] aoData index to get the nodes for - optional * if not given then the return array will contain all nodes for the table * @returns {array} TD array * @memberof DataTable#oApi */ function _fnGetTdNodes ( oSettings, iIndividualRow ) { var anReturn = []; var iCorrector; var anTds, nTd; var iRow, iRows=oSettings.aoData.length, iColumn, iColumns, oData, sNodeName, iStart=0, iEnd=iRows; /* Allow the collection to be limited to just one row */ if ( iIndividualRow !== undefined ) { iStart = iIndividualRow; iEnd = iIndividualRow+1; } for ( iRow=iStart ; iRow<iEnd ; iRow++ ) { oData = oSettings.aoData[iRow]; if ( oData.nTr !== null ) { /* get the TD child nodes - taking into account text etc nodes */ anTds = []; nTd = oData.nTr.firstChild; while ( nTd ) { sNodeName = nTd.nodeName.toLowerCase(); if ( sNodeName == 'td' || sNodeName == 'th' ) { anTds.push( nTd ); } nTd = nTd.nextSibling; } iCorrector = 0; for ( iColumn=0, iColumns=oSettings.aoColumns.length ; iColumn<iColumns ; iColumn++ ) { if ( oSettings.aoColumns[iColumn].bVisible ) { anReturn.push( anTds[iColumn-iCorrector] ); } else { anReturn.push( oData._anHidden[iColumn] ); iCorrector++; } } } } return anReturn; } /** * Log an error message * @param {object} oSettings dataTables settings object * @param {int} iLevel log error messages, or display them to the user * @param {string} sMesg error message * @memberof DataTable#oApi */ function _fnLog( oSettings, iLevel, sMesg ) { var sAlert = (oSettings===null) ? "DataTables warning: "+sMesg : "DataTables warning (table id = '"+oSettings.sTableId+"'): "+sMesg; if ( iLevel === 0 ) { if ( DataTable.ext.sErrMode == 'alert' ) { alert( sAlert ); } else { throw new Error(sAlert); } return; } else if ( window.console && console.log ) { console.log( sAlert ); } } /** * See if a property is defined on one object, if so assign it to the other object * @param {object} oRet target object * @param {object} oSrc source object * @param {string} sName property * @param {string} [sMappedName] name to map too - optional, sName used if not given * @memberof DataTable#oApi */ function _fnMap( oRet, oSrc, sName, sMappedName ) { if ( sMappedName === undefined ) { sMappedName = sName; } if ( oSrc[sName] !== undefined ) { oRet[sMappedName] = oSrc[sName]; } } /** * Extend objects - very similar to jQuery.extend, but deep copy objects, and shallow * copy arrays. The reason we need to do this, is that we don't want to deep copy array * init values (such as aaSorting) since the dev wouldn't be able to override them, but * we do want to deep copy arrays. * @param {object} oOut Object to extend * @param {object} oExtender Object from which the properties will be applied to oOut * @returns {object} oOut Reference, just for convenience - oOut === the return. * @memberof DataTable#oApi * @todo This doesn't take account of arrays inside the deep copied objects. */ function _fnExtend( oOut, oExtender ) { var val; for ( var prop in oExtender ) { if ( oExtender.hasOwnProperty(prop) ) { val = oExtender[prop]; if ( typeof oInit[prop] === 'object' && val !== null && $.isArray(val) === false ) { $.extend( true, oOut[prop], val ); } else { oOut[prop] = val; } } } return oOut; } /** * Bind an event handers to allow a click or return key to activate the callback. * This is good for accessibility since a return on the keyboard will have the * same effect as a click, if the element has focus. * @param {element} n Element to bind the action to * @param {object} oData Data object to pass to the triggered function * @param {function} fn Callback function for when the event is triggered * @memberof DataTable#oApi */ function _fnBindAction( n, oData, fn ) { $(n) .bind( 'click.DT', oData, function (e) { n.blur(); // Remove focus outline for mouse users fn(e); } ) .bind( 'keypress.DT', oData, function (e){ if ( e.which === 13 ) { fn(e); } } ) .bind( 'selectstart.DT', function () { /* Take the brutal approach to cancelling text selection */ return false; } ); } /** * Register a callback function. Easily allows a callback function to be added to * an array store of callback functions that can then all be called together. * @param {object} oSettings dataTables settings object * @param {string} sStore Name of the array storage for the callbacks in oSettings * @param {function} fn Function to be called back * @param {string} sName Identifying name for the callback (i.e. a label) * @memberof DataTable#oApi */ function _fnCallbackReg( oSettings, sStore, fn, sName ) { if ( fn ) { oSettings[sStore].push( { "fn": fn, "sName": sName } ); } } /** * Fire callback functions and trigger events. Note that the loop over the callback * array store is done backwards! Further note that you do not want to fire off triggers * in time sensitive applications (for example cell creation) as its slow. * @param {object} oSettings dataTables settings object * @param {string} sStore Name of the array storage for the callbacks in oSettings * @param {string} sTrigger Name of the jQuery custom event to trigger. If null no trigger * is fired * @param {array} aArgs Array of arguments to pass to the callback function / trigger * @memberof DataTable#oApi */ function _fnCallbackFire( oSettings, sStore, sTrigger, aArgs ) { var aoStore = oSettings[sStore]; var aRet =[]; for ( var i=aoStore.length-1 ; i>=0 ; i-- ) { aRet.push( aoStore[i].fn.apply( oSettings.oInstance, aArgs ) ); } if ( sTrigger !== null ) { $(oSettings.oInstance).trigger(sTrigger, aArgs); } return aRet; } /** * JSON stringify. If JSON.stringify it provided by the browser, json2.js or any other * library, then we use that as it is fast, safe and accurate. If the function isn't * available then we need to built it ourselves - the inspiration for this function comes * from Craig Buckler ( http://www.sitepoint.com/javascript-json-serialization/ ). It is * not perfect and absolutely should not be used as a replacement to json2.js - but it does * do what we need, without requiring a dependency for DataTables. * @param {object} o JSON object to be converted * @returns {string} JSON string * @memberof DataTable#oApi */ var _fnJsonString = (window.JSON) ? JSON.stringify : function( o ) { /* Not an object or array */ var sType = typeof o; if (sType !== "object" || o === null) { // simple data type if (sType === "string") { o = '"'+o+'"'; } return o+""; } /* If object or array, need to recurse over it */ var sProp, mValue, json = [], bArr = $.isArray(o); for (sProp in o) { mValue = o[sProp]; sType = typeof mValue; if (sType === "string") { mValue = '"'+mValue+'"'; } else if (sType === "object" && mValue !== null) { mValue = _fnJsonString(mValue); } json.push((bArr ? "" : '"'+sProp+'":') + mValue); } return (bArr ? "[" : "{") + json + (bArr ? "]" : "}"); }; /** * From some browsers (specifically IE6/7) we need special handling to work around browser * bugs - this function is used to detect when these workarounds are needed. * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnBrowserDetect( oSettings ) { /* IE6/7 will oversize a width 100% element inside a scrolling element, to include the * width of the scrollbar, while other browsers ensure the inner element is contained * without forcing scrolling */ var n = $( '<div style="position:absolute; top:0; left:0; height:1px; width:1px; overflow:hidden">'+ '<div style="position:absolute; top:1px; left:1px; width:100px; overflow:scroll;">'+ '<div id="DT_BrowserTest" style="width:100%; height:10px;"></div>'+ '</div>'+ '</div>')[0]; document.body.appendChild( n ); oSettings.oBrowser.bScrollOversize = $('#DT_BrowserTest', n)[0].offsetWidth === 100 ? true : false; document.body.removeChild( n ); } /** * Perform a jQuery selector action on the table's TR elements (from the tbody) and * return the resulting jQuery object. * @param {string|node|jQuery} sSelector jQuery selector or node collection to act on * @param {object} [oOpts] Optional parameters for modifying the rows to be included * @param {string} [oOpts.filter=none] Select TR elements that meet the current filter * criterion ("applied") or all TR elements (i.e. no filter). * @param {string} [oOpts.order=current] Order of the TR elements in the processed array. * Can be either 'current', whereby the current sorting of the table is used, or * 'original' whereby the original order the data was read into the table is used. * @param {string} [oOpts.page=all] Limit the selection to the currently displayed page * ("current") or not ("all"). If 'current' is given, then order is assumed to be * 'current' and filter is 'applied', regardless of what they might be given as. * @returns {object} jQuery object, filtered by the given selector. * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Highlight every second row * oTable.$('tr:odd').css('backgroundColor', 'blue'); * } ); * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Filter to rows with 'Webkit' in them, add a background colour and then * // remove the filter, thus highlighting the 'Webkit' rows only. * oTable.fnFilter('Webkit'); * oTable.$('tr', {"filter": "applied"}).css('backgroundColor', 'blue'); * oTable.fnFilter(''); * } ); */ this.$ = function ( sSelector, oOpts ) { var i, iLen, a = [], tr; var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var aoData = oSettings.aoData; var aiDisplay = oSettings.aiDisplay; var aiDisplayMaster = oSettings.aiDisplayMaster; if ( !oOpts ) { oOpts = {}; } oOpts = $.extend( {}, { "filter": "none", // applied "order": "current", // "original" "page": "all" // current }, oOpts ); // Current page implies that order=current and fitler=applied, since it is fairly // senseless otherwise if ( oOpts.page == 'current' ) { for ( i=oSettings._iDisplayStart, iLen=oSettings.fnDisplayEnd() ; i<iLen ; i++ ) { tr = aoData[ aiDisplay[i] ].nTr; if ( tr ) { a.push( tr ); } } } else if ( oOpts.order == "current" && oOpts.filter == "none" ) { for ( i=0, iLen=aiDisplayMaster.length ; i<iLen ; i++ ) { tr = aoData[ aiDisplayMaster[i] ].nTr; if ( tr ) { a.push( tr ); } } } else if ( oOpts.order == "current" && oOpts.filter == "applied" ) { for ( i=0, iLen=aiDisplay.length ; i<iLen ; i++ ) { tr = aoData[ aiDisplay[i] ].nTr; if ( tr ) { a.push( tr ); } } } else if ( oOpts.order == "original" && oOpts.filter == "none" ) { for ( i=0, iLen=aoData.length ; i<iLen ; i++ ) { tr = aoData[ i ].nTr ; if ( tr ) { a.push( tr ); } } } else if ( oOpts.order == "original" && oOpts.filter == "applied" ) { for ( i=0, iLen=aoData.length ; i<iLen ; i++ ) { tr = aoData[ i ].nTr; if ( $.inArray( i, aiDisplay ) !== -1 && tr ) { a.push( tr ); } } } else { _fnLog( oSettings, 1, "Unknown selection options" ); } /* We need to filter on the TR elements and also 'find' in their descendants * to make the selector act like it would in a full table - so we need * to build both results and then combine them together */ var jqA = $(a); var jqTRs = jqA.filter( sSelector ); var jqDescendants = jqA.find( sSelector ); return $( [].concat($.makeArray(jqTRs), $.makeArray(jqDescendants)) ); }; /** * Almost identical to $ in operation, but in this case returns the data for the matched * rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes * rather than any descendants, so the data can be obtained for the row/cell. If matching * rows are found, the data returned is the original data array/object that was used to * create the row (or a generated array if from a DOM source). * * This method is often useful in-combination with $ where both functions are given the * same parameters and the array indexes will match identically. * @param {string|node|jQuery} sSelector jQuery selector or node collection to act on * @param {object} [oOpts] Optional parameters for modifying the rows to be included * @param {string} [oOpts.filter=none] Select elements that meet the current filter * criterion ("applied") or all elements (i.e. no filter). * @param {string} [oOpts.order=current] Order of the data in the processed array. * Can be either 'current', whereby the current sorting of the table is used, or * 'original' whereby the original order the data was read into the table is used. * @param {string} [oOpts.page=all] Limit the selection to the currently displayed page * ("current") or not ("all"). If 'current' is given, then order is assumed to be * 'current' and filter is 'applied', regardless of what they might be given as. * @returns {array} Data for the matched elements. If any elements, as a result of the * selector, were not TR, TD or TH elements in the DataTable, they will have a null * entry in the array. * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Get the data from the first row in the table * var data = oTable._('tr:first'); * * // Do something useful with the data * alert( "First cell is: "+data[0] ); * } ); * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Filter to 'Webkit' and get all data for * oTable.fnFilter('Webkit'); * var data = oTable._('tr', {"filter": "applied"}); * * // Do something with the data * alert( data.length+" rows matched the filter" ); * } ); */ this._ = function ( sSelector, oOpts ) { var aOut = []; var i, iLen, iIndex; var aTrs = this.$( sSelector, oOpts ); for ( i=0, iLen=aTrs.length ; i<iLen ; i++ ) { aOut.push( this.fnGetData(aTrs[i]) ); } return aOut; }; /** * Add a single new row or multiple rows of data to the table. Please note * that this is suitable for client-side processing only - if you are using * server-side processing (i.e. "bServerSide": true), then to add data, you * must add it to the data source, i.e. the server-side, through an Ajax call. * @param {array|object} mData The data to be added to the table. This can be: * <ul> * <li>1D array of data - add a single row with the data provided</li> * <li>2D array of arrays - add multiple rows in a single call</li> * <li>object - data object when using <i>mData</i></li> * <li>array of objects - multiple data objects when using <i>mData</i></li> * </ul> * @param {bool} [bRedraw=true] redraw the table or not * @returns {array} An array of integers, representing the list of indexes in * <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to * the table. * @dtopt API * * @example * // Global var for counter * var giCount = 2; * * $(document).ready(function() { * $('#example').dataTable(); * } ); * * function fnClickAddRow() { * $('#example').dataTable().fnAddData( [ * giCount+".1", * giCount+".2", * giCount+".3", * giCount+".4" ] * ); * * giCount++; * } */ this.fnAddData = function( mData, bRedraw ) { if ( mData.length === 0 ) { return []; } var aiReturn = []; var iTest; /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); /* Check if we want to add multiple rows or not */ if ( typeof mData[0] === "object" && mData[0] !== null ) { for ( var i=0 ; i<mData.length ; i++ ) { iTest = _fnAddData( oSettings, mData[i] ); if ( iTest == -1 ) { return aiReturn; } aiReturn.push( iTest ); } } else { iTest = _fnAddData( oSettings, mData ); if ( iTest == -1 ) { return aiReturn; } aiReturn.push( iTest ); } oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); if ( bRedraw === undefined || bRedraw ) { _fnReDraw( oSettings ); } return aiReturn; }; /** * This function will make DataTables recalculate the column sizes, based on the data * contained in the table and the sizes applied to the columns (in the DOM, CSS or * through the sWidth parameter). This can be useful when the width of the table's * parent element changes (for example a window resize). * @param {boolean} [bRedraw=true] Redraw the table or not, you will typically want to * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable( { * "sScrollY": "200px", * "bPaginate": false * } ); * * $(window).bind('resize', function () { * oTable.fnAdjustColumnSizing(); * } ); * } ); */ this.fnAdjustColumnSizing = function ( bRedraw ) { var oSettings = _fnSettingsFromNode(this[DataTable.ext.iApiIndex]); _fnAdjustColumnSizing( oSettings ); if ( bRedraw === undefined || bRedraw ) { this.fnDraw( false ); } else if ( oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "" ) { /* If not redrawing, but scrolling, we want to apply the new column sizes anyway */ this.oApi._fnScrollDraw(oSettings); } }; /** * Quickly and simply clear a table * @param {bool} [bRedraw=true] redraw the table or not * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...) * oTable.fnClearTable(); * } ); */ this.fnClearTable = function( bRedraw ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); _fnClearTable( oSettings ); if ( bRedraw === undefined || bRedraw ) { _fnDraw( oSettings ); } }; /** * The exact opposite of 'opening' a row, this function will close any rows which * are currently 'open'. * @param {node} nTr the table row to 'close' * @returns {int} 0 on success, or 1 if failed (can't find the row) * @dtopt API * * @example * $(document).ready(function() { * var oTable; * * // 'open' an information row when a row is clicked on * $('#example tbody tr').click( function () { * if ( oTable.fnIsOpen(this) ) { * oTable.fnClose( this ); * } else { * oTable.fnOpen( this, "Temporary row opened", "info_row" ); * } * } ); * * oTable = $('#example').dataTable(); * } ); */ this.fnClose = function( nTr ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); for ( var i=0 ; i<oSettings.aoOpenRows.length ; i++ ) { if ( oSettings.aoOpenRows[i].nParent == nTr ) { var nTrParent = oSettings.aoOpenRows[i].nTr.parentNode; if ( nTrParent ) { /* Remove it if it is currently on display */ nTrParent.removeChild( oSettings.aoOpenRows[i].nTr ); } oSettings.aoOpenRows.splice( i, 1 ); return 0; } } return 1; }; /** * Remove a row for the table * @param {mixed} mTarget The index of the row from aoData to be deleted, or * the TR element you want to delete * @param {function|null} [fnCallBack] Callback function * @param {bool} [bRedraw=true] Redraw the table or not * @returns {array} The row that was deleted * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Immediately remove the first row * oTable.fnDeleteRow( 0 ); * } ); */ this.fnDeleteRow = function( mTarget, fnCallBack, bRedraw ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var i, iLen, iAODataIndex; iAODataIndex = (typeof mTarget === 'object') ? _fnNodeToDataIndex(oSettings, mTarget) : mTarget; /* Return the data array from this row */ var oData = oSettings.aoData.splice( iAODataIndex, 1 ); /* Update the _DT_RowIndex parameter */ for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { oSettings.aoData[i].nTr._DT_RowIndex = i; } } /* Remove the target row from the search array */ var iDisplayIndex = $.inArray( iAODataIndex, oSettings.aiDisplay ); oSettings.asDataSearch.splice( iDisplayIndex, 1 ); /* Delete from the display arrays */ _fnDeleteIndex( oSettings.aiDisplayMaster, iAODataIndex ); _fnDeleteIndex( oSettings.aiDisplay, iAODataIndex ); /* If there is a user callback function - call it */ if ( typeof fnCallBack === "function" ) { fnCallBack.call( this, oSettings, oData ); } /* Check for an 'overflow' they case for displaying the table */ if ( oSettings._iDisplayStart >= oSettings.fnRecordsDisplay() ) { oSettings._iDisplayStart -= oSettings._iDisplayLength; if ( oSettings._iDisplayStart < 0 ) { oSettings._iDisplayStart = 0; } } if ( bRedraw === undefined || bRedraw ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } return oData; }; /** * Restore the table to it's original state in the DOM by removing all of DataTables * enhancements, alterations to the DOM structure of the table and event listeners. * @param {boolean} [bRemove=false] Completely remove the table from the DOM * @dtopt API * * @example * $(document).ready(function() { * // This example is fairly pointless in reality, but shows how fnDestroy can be used * var oTable = $('#example').dataTable(); * oTable.fnDestroy(); * } ); */ this.fnDestroy = function ( bRemove ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var nOrig = oSettings.nTableWrapper.parentNode; var nBody = oSettings.nTBody; var i, iLen; bRemove = (bRemove===undefined) ? false : bRemove; /* Flag to note that the table is currently being destroyed - no action should be taken */ oSettings.bDestroying = true; /* Fire off the destroy callbacks for plug-ins etc */ _fnCallbackFire( oSettings, "aoDestroyCallback", "destroy", [oSettings] ); /* If the table is not being removed, restore the hidden columns */ if ( !bRemove ) { for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { if ( oSettings.aoColumns[i].bVisible === false ) { this.fnSetColumnVis( i, true ); } } } /* Blitz all DT events */ $(oSettings.nTableWrapper).find('*').andSelf().unbind('.DT'); /* If there is an 'empty' indicator row, remove it */ $('tbody>tr>td.'+oSettings.oClasses.sRowEmpty, oSettings.nTable).parent().remove(); /* When scrolling we had to break the table up - restore it */ if ( oSettings.nTable != oSettings.nTHead.parentNode ) { $(oSettings.nTable).children('thead').remove(); oSettings.nTable.appendChild( oSettings.nTHead ); } if ( oSettings.nTFoot && oSettings.nTable != oSettings.nTFoot.parentNode ) { $(oSettings.nTable).children('tfoot').remove(); oSettings.nTable.appendChild( oSettings.nTFoot ); } /* Remove the DataTables generated nodes, events and classes */ oSettings.nTable.parentNode.removeChild( oSettings.nTable ); $(oSettings.nTableWrapper).remove(); oSettings.aaSorting = []; oSettings.aaSortingFixed = []; _fnSortingClasses( oSettings ); $(_fnGetTrNodes( oSettings )).removeClass( oSettings.asStripeClasses.join(' ') ); $('th, td', oSettings.nTHead).removeClass( [ oSettings.oClasses.sSortable, oSettings.oClasses.sSortableAsc, oSettings.oClasses.sSortableDesc, oSettings.oClasses.sSortableNone ].join(' ') ); if ( oSettings.bJUI ) { $('th span.'+oSettings.oClasses.sSortIcon + ', td span.'+oSettings.oClasses.sSortIcon, oSettings.nTHead).remove(); $('th, td', oSettings.nTHead).each( function () { var jqWrapper = $('div.'+oSettings.oClasses.sSortJUIWrapper, this); var kids = jqWrapper.contents(); $(this).append( kids ); jqWrapper.remove(); } ); } /* Add the TR elements back into the table in their original order */ if ( !bRemove && oSettings.nTableReinsertBefore ) { nOrig.insertBefore( oSettings.nTable, oSettings.nTableReinsertBefore ); } else if ( !bRemove ) { nOrig.appendChild( oSettings.nTable ); } for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { nBody.appendChild( oSettings.aoData[i].nTr ); } } /* Restore the width of the original table */ if ( oSettings.oFeatures.bAutoWidth === true ) { oSettings.nTable.style.width = _fnStringToCss(oSettings.sDestroyWidth); } /* If the were originally stripe classes - then we add them back here. Note * this is not fool proof (for example if not all rows had stripe classes - but * it's a good effort without getting carried away */ iLen = oSettings.asDestroyStripes.length; if (iLen) { var anRows = $(nBody).children('tr'); for ( i=0 ; i<iLen ; i++ ) { anRows.filter(':nth-child(' + iLen + 'n + ' + i + ')').addClass( oSettings.asDestroyStripes[i] ); } } /* Remove the settings object from the settings array */ for ( i=0, iLen=DataTable.settings.length ; i<iLen ; i++ ) { if ( DataTable.settings[i] == oSettings ) { DataTable.settings.splice( i, 1 ); } } /* End it all */ oSettings = null; oInit = null; }; /** * Redraw the table * @param {bool} [bComplete=true] Re-filter and resort (if enabled) the table before the draw. * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Re-draw the table - you wouldn't want to do it here, but it's an example :-) * oTable.fnDraw(); * } ); */ this.fnDraw = function( bComplete ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); if ( bComplete === false ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } else { _fnReDraw( oSettings ); } }; /** * Filter the input based on data * @param {string} sInput String to filter the table on * @param {int|null} [iColumn] Column to limit filtering to * @param {bool} [bRegex=false] Treat as regular expression or not * @param {bool} [bSmart=true] Perform smart filtering or not * @param {bool} [bShowGlobal=true] Show the input global filter in it's input box(es) * @param {bool} [bCaseInsensitive=true] Do case-insensitive matching (true) or not (false) * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Sometime later - filter... * oTable.fnFilter( 'test string' ); * } ); */ this.fnFilter = function( sInput, iColumn, bRegex, bSmart, bShowGlobal, bCaseInsensitive ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); if ( !oSettings.oFeatures.bFilter ) { return; } if ( bRegex === undefined || bRegex === null ) { bRegex = false; } if ( bSmart === undefined || bSmart === null ) { bSmart = true; } if ( bShowGlobal === undefined || bShowGlobal === null ) { bShowGlobal = true; } if ( bCaseInsensitive === undefined || bCaseInsensitive === null ) { bCaseInsensitive = true; } if ( iColumn === undefined || iColumn === null ) { /* Global filter */ _fnFilterComplete( oSettings, { "sSearch":sInput+"", "bRegex": bRegex, "bSmart": bSmart, "bCaseInsensitive": bCaseInsensitive }, 1 ); if ( bShowGlobal && oSettings.aanFeatures.f ) { var n = oSettings.aanFeatures.f; for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { // IE9 throws an 'unknown error' if document.activeElement is used // inside an iframe or frame... try { if ( n[i]._DT_Input != document.activeElement ) { $(n[i]._DT_Input).val( sInput ); } } catch ( e ) { $(n[i]._DT_Input).val( sInput ); } } } } else { /* Single column filter */ $.extend( oSettings.aoPreSearchCols[ iColumn ], { "sSearch": sInput+"", "bRegex": bRegex, "bSmart": bSmart, "bCaseInsensitive": bCaseInsensitive } ); _fnFilterComplete( oSettings, oSettings.oPreviousSearch, 1 ); } }; /** * Get the data for the whole table, an individual row or an individual cell based on the * provided parameters. * @param {int|node} [mRow] A TR row node, TD/TH cell node or an integer. If given as * a TR node then the data source for the whole row will be returned. If given as a * TD/TH cell node then iCol will be automatically calculated and the data for the * cell returned. If given as an integer, then this is treated as the aoData internal * data index for the row (see fnGetPosition) and the data for that row used. * @param {int} [iCol] Optional column index that you want the data of. * @returns {array|object|string} If mRow is undefined, then the data for all rows is * returned. If mRow is defined, just data for that row, and is iCol is * defined, only data for the designated cell is returned. * @dtopt API * * @example * // Row data * $(document).ready(function() { * oTable = $('#example').dataTable(); * * oTable.$('tr').click( function () { * var data = oTable.fnGetData( this ); * // ... do something with the array / object of data for the row * } ); * } ); * * @example * // Individual cell data * $(document).ready(function() { * oTable = $('#example').dataTable(); * * oTable.$('td').click( function () { * var sData = oTable.fnGetData( this ); * alert( 'The cell clicked on had the value of '+sData ); * } ); * } ); */ this.fnGetData = function( mRow, iCol ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); if ( mRow !== undefined ) { var iRow = mRow; if ( typeof mRow === 'object' ) { var sNode = mRow.nodeName.toLowerCase(); if (sNode === "tr" ) { iRow = _fnNodeToDataIndex(oSettings, mRow); } else if ( sNode === "td" ) { iRow = _fnNodeToDataIndex(oSettings, mRow.parentNode); iCol = _fnNodeToColumnIndex( oSettings, iRow, mRow ); } } if ( iCol !== undefined ) { return _fnGetCellData( oSettings, iRow, iCol, '' ); } return (oSettings.aoData[iRow]!==undefined) ? oSettings.aoData[iRow]._aData : null; } return _fnGetDataMaster( oSettings ); }; /** * Get an array of the TR nodes that are used in the table's body. Note that you will * typically want to use the '$' API method in preference to this as it is more * flexible. * @param {int} [iRow] Optional row index for the TR element you want * @returns {array|node} If iRow is undefined, returns an array of all TR elements * in the table's body, or iRow is defined, just the TR element requested. * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Get the nodes from the table * var nNodes = oTable.fnGetNodes( ); * } ); */ this.fnGetNodes = function( iRow ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); if ( iRow !== undefined ) { return (oSettings.aoData[iRow]!==undefined) ? oSettings.aoData[iRow].nTr : null; } return _fnGetTrNodes( oSettings ); }; /** * Get the array indexes of a particular cell from it's DOM element * and column index including hidden columns * @param {node} nNode this can either be a TR, TD or TH in the table's body * @returns {int} If nNode is given as a TR, then a single index is returned, or * if given as a cell, an array of [row index, column index (visible), * column index (all)] is given. * @dtopt API * * @example * $(document).ready(function() { * $('#example tbody td').click( function () { * // Get the position of the current data from the node * var aPos = oTable.fnGetPosition( this ); * * // Get the data array for this row * var aData = oTable.fnGetData( aPos[0] ); * * // Update the data array and return the value * aData[ aPos[1] ] = 'clicked'; * this.innerHTML = 'clicked'; * } ); * * // Init DataTables * oTable = $('#example').dataTable(); * } ); */ this.fnGetPosition = function( nNode ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var sNodeName = nNode.nodeName.toUpperCase(); if ( sNodeName == "TR" ) { return _fnNodeToDataIndex(oSettings, nNode); } else if ( sNodeName == "TD" || sNodeName == "TH" ) { var iDataIndex = _fnNodeToDataIndex( oSettings, nNode.parentNode ); var iColumnIndex = _fnNodeToColumnIndex( oSettings, iDataIndex, nNode ); return [ iDataIndex, _fnColumnIndexToVisible(oSettings, iColumnIndex ), iColumnIndex ]; } return null; }; /** * Check to see if a row is 'open' or not. * @param {node} nTr the table row to check * @returns {boolean} true if the row is currently open, false otherwise * @dtopt API * * @example * $(document).ready(function() { * var oTable; * * // 'open' an information row when a row is clicked on * $('#example tbody tr').click( function () { * if ( oTable.fnIsOpen(this) ) { * oTable.fnClose( this ); * } else { * oTable.fnOpen( this, "Temporary row opened", "info_row" ); * } * } ); * * oTable = $('#example').dataTable(); * } ); */ this.fnIsOpen = function( nTr ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var aoOpenRows = oSettings.aoOpenRows; for ( var i=0 ; i<oSettings.aoOpenRows.length ; i++ ) { if ( oSettings.aoOpenRows[i].nParent == nTr ) { return true; } } return false; }; /** * This function will place a new row directly after a row which is currently * on display on the page, with the HTML contents that is passed into the * function. This can be used, for example, to ask for confirmation that a * particular record should be deleted. * @param {node} nTr The table row to 'open' * @param {string|node|jQuery} mHtml The HTML to put into the row * @param {string} sClass Class to give the new TD cell * @returns {node} The row opened. Note that if the table row passed in as the * first parameter, is not found in the table, this method will silently * return. * @dtopt API * * @example * $(document).ready(function() { * var oTable; * * // 'open' an information row when a row is clicked on * $('#example tbody tr').click( function () { * if ( oTable.fnIsOpen(this) ) { * oTable.fnClose( this ); * } else { * oTable.fnOpen( this, "Temporary row opened", "info_row" ); * } * } ); * * oTable = $('#example').dataTable(); * } ); */ this.fnOpen = function( nTr, mHtml, sClass ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); /* Check that the row given is in the table */ var nTableRows = _fnGetTrNodes( oSettings ); if ( $.inArray(nTr, nTableRows) === -1 ) { return; } /* the old open one if there is one */ this.fnClose( nTr ); var nNewRow = document.createElement("tr"); var nNewCell = document.createElement("td"); nNewRow.appendChild( nNewCell ); nNewCell.className = sClass; nNewCell.colSpan = _fnVisbleColumns( oSettings ); if (typeof mHtml === "string") { nNewCell.innerHTML = mHtml; } else { $(nNewCell).html( mHtml ); } /* If the nTr isn't on the page at the moment - then we don't insert at the moment */ var nTrs = $('tr', oSettings.nTBody); if ( $.inArray(nTr, nTrs) != -1 ) { $(nNewRow).insertAfter(nTr); } oSettings.aoOpenRows.push( { "nTr": nNewRow, "nParent": nTr } ); return nNewRow; }; /** * Change the pagination - provides the internal logic for pagination in a simple API * function. With this function you can have a DataTables table go to the next, * previous, first or last pages. * @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last" * or page number to jump to (integer), note that page 0 is the first page. * @param {bool} [bRedraw=true] Redraw the table or not * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * oTable.fnPageChange( 'next' ); * } ); */ this.fnPageChange = function ( mAction, bRedraw ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); _fnPageChange( oSettings, mAction ); _fnCalculateEnd( oSettings ); if ( bRedraw === undefined || bRedraw ) { _fnDraw( oSettings ); } }; /** * Show a particular column * @param {int} iCol The column whose display should be changed * @param {bool} bShow Show (true) or hide (false) the column * @param {bool} [bRedraw=true] Redraw the table or not * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Hide the second column after initialisation * oTable.fnSetColumnVis( 1, false ); * } ); */ this.fnSetColumnVis = function ( iCol, bShow, bRedraw ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var i, iLen; var aoColumns = oSettings.aoColumns; var aoData = oSettings.aoData; var nTd, bAppend, iBefore; /* No point in doing anything if we are requesting what is already true */ if ( aoColumns[iCol].bVisible == bShow ) { return; } /* Show the column */ if ( bShow ) { var iInsert = 0; for ( i=0 ; i<iCol ; i++ ) { if ( aoColumns[i].bVisible ) { iInsert++; } } /* Need to decide if we should use appendChild or insertBefore */ bAppend = (iInsert >= _fnVisbleColumns( oSettings )); /* Which coloumn should we be inserting before? */ if ( !bAppend ) { for ( i=iCol ; i<aoColumns.length ; i++ ) { if ( aoColumns[i].bVisible ) { iBefore = i; break; } } } for ( i=0, iLen=aoData.length ; i<iLen ; i++ ) { if ( aoData[i].nTr !== null ) { if ( bAppend ) { aoData[i].nTr.appendChild( aoData[i]._anHidden[iCol] ); } else { aoData[i].nTr.insertBefore( aoData[i]._anHidden[iCol], _fnGetTdNodes( oSettings, i )[iBefore] ); } } } } else { /* Remove a column from display */ for ( i=0, iLen=aoData.length ; i<iLen ; i++ ) { if ( aoData[i].nTr !== null ) { nTd = _fnGetTdNodes( oSettings, i )[iCol]; aoData[i]._anHidden[iCol] = nTd; nTd.parentNode.removeChild( nTd ); } } } /* Clear to set the visible flag */ aoColumns[iCol].bVisible = bShow; /* Redraw the header and footer based on the new column visibility */ _fnDrawHead( oSettings, oSettings.aoHeader ); if ( oSettings.nTFoot ) { _fnDrawHead( oSettings, oSettings.aoFooter ); } /* If there are any 'open' rows, then we need to alter the colspan for this col change */ for ( i=0, iLen=oSettings.aoOpenRows.length ; i<iLen ; i++ ) { oSettings.aoOpenRows[i].nTr.colSpan = _fnVisbleColumns( oSettings ); } /* Do a redraw incase anything depending on the table columns needs it * (built-in: scrolling) */ if ( bRedraw === undefined || bRedraw ) { _fnAdjustColumnSizing( oSettings ); _fnDraw( oSettings ); } _fnSaveState( oSettings ); }; /** * Get the settings for a particular table for external manipulation * @returns {object} DataTables settings object. See * {@link DataTable.models.oSettings} * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * var oSettings = oTable.fnSettings(); * * // Show an example parameter from the settings * alert( oSettings._iDisplayStart ); * } ); */ this.fnSettings = function() { return _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); }; /** * Sort the table by a particular column * @param {int} iCol the data index to sort on. Note that this will not match the * 'display index' if you have hidden data entries * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Sort immediately with columns 0 and 1 * oTable.fnSort( [ [0,'asc'], [1,'asc'] ] ); * } ); */ this.fnSort = function( aaSort ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); oSettings.aaSorting = aaSort; _fnSort( oSettings ); }; /** * Attach a sort listener to an element for a given column * @param {node} nNode the element to attach the sort listener to * @param {int} iColumn the column that a click on this node will sort on * @param {function} [fnCallback] callback function when sort is run * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Sort on column 1, when 'sorter' is clicked on * oTable.fnSortListener( document.getElementById('sorter'), 1 ); * } ); */ this.fnSortListener = function( nNode, iColumn, fnCallback ) { _fnSortAttachListener( _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ), nNode, iColumn, fnCallback ); }; /** * Update a table cell or row - this method will accept either a single value to * update the cell with, an array of values with one element for each column or * an object in the same format as the original data source. The function is * self-referencing in order to make the multi column updates easier. * @param {object|array|string} mData Data to update the cell/row with * @param {node|int} mRow TR element you want to update or the aoData index * @param {int} [iColumn] The column to update (not used of mData is an array or object) * @param {bool} [bRedraw=true] Redraw the table or not * @param {bool} [bAction=true] Perform pre-draw actions or not * @returns {int} 0 on success, 1 on error * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell * oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], 1, 0 ); // Row * } ); */ this.fnUpdate = function( mData, mRow, iColumn, bRedraw, bAction ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var i, iLen, sDisplay; var iRow = (typeof mRow === 'object') ? _fnNodeToDataIndex(oSettings, mRow) : mRow; if ( $.isArray(mData) && iColumn === undefined ) { /* Array update - update the whole row */ oSettings.aoData[iRow]._aData = mData.slice(); /* Flag to the function that we are recursing */ for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { this.fnUpdate( _fnGetCellData( oSettings, iRow, i ), iRow, i, false, false ); } } else if ( $.isPlainObject(mData) && iColumn === undefined ) { /* Object update - update the whole row - assume the developer gets the object right */ oSettings.aoData[iRow]._aData = $.extend( true, {}, mData ); for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { this.fnUpdate( _fnGetCellData( oSettings, iRow, i ), iRow, i, false, false ); } } else { /* Individual cell update */ _fnSetCellData( oSettings, iRow, iColumn, mData ); sDisplay = _fnGetCellData( oSettings, iRow, iColumn, 'display' ); var oCol = oSettings.aoColumns[iColumn]; if ( oCol.fnRender !== null ) { sDisplay = _fnRender( oSettings, iRow, iColumn ); if ( oCol.bUseRendered ) { _fnSetCellData( oSettings, iRow, iColumn, sDisplay ); } } if ( oSettings.aoData[iRow].nTr !== null ) { /* Do the actual HTML update */ _fnGetTdNodes( oSettings, iRow )[iColumn].innerHTML = sDisplay; } } /* Modify the search index for this row (strictly this is likely not needed, since fnReDraw * will rebuild the search array - however, the redraw might be disabled by the user) */ var iDisplayIndex = $.inArray( iRow, oSettings.aiDisplay ); oSettings.asDataSearch[iDisplayIndex] = _fnBuildSearchRow( oSettings, _fnGetRowData( oSettings, iRow, 'filter', _fnGetColumns( oSettings, 'bSearchable' ) ) ); /* Perform pre-draw actions */ if ( bAction === undefined || bAction ) { _fnAdjustColumnSizing( oSettings ); } /* Redraw the table */ if ( bRedraw === undefined || bRedraw ) { _fnReDraw( oSettings ); } return 0; }; /** * Provide a common method for plug-ins to check the version of DataTables being used, in order * to ensure compatibility. * @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the * formats "X" and "X.Y" are also acceptable. * @returns {boolean} true if this version of DataTables is greater or equal to the required * version, or false if this version of DataTales is not suitable * @method * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * alert( oTable.fnVersionCheck( '1.9.0' ) ); * } ); */ this.fnVersionCheck = DataTable.ext.fnVersionCheck; /* * This is really a good bit rubbish this method of exposing the internal methods * publicly... - To be fixed in 2.0 using methods on the prototype */ /** * Create a wrapper function for exporting an internal functions to an external API. * @param {string} sFunc API function name * @returns {function} wrapped function * @memberof DataTable#oApi */ function _fnExternApiFunc (sFunc) { return function() { var aArgs = [_fnSettingsFromNode(this[DataTable.ext.iApiIndex])].concat( Array.prototype.slice.call(arguments) ); return DataTable.ext.oApi[sFunc].apply( this, aArgs ); }; } /** * Reference to internal functions for use by plug-in developers. Note that these * methods are references to internal functions and are considered to be private. * If you use these methods, be aware that they are liable to change between versions * (check the upgrade notes). * @namespace */ this.oApi = { "_fnExternApiFunc": _fnExternApiFunc, "_fnInitialise": _fnInitialise, "_fnInitComplete": _fnInitComplete, "_fnLanguageCompat": _fnLanguageCompat, "_fnAddColumn": _fnAddColumn, "_fnColumnOptions": _fnColumnOptions, "_fnAddData": _fnAddData, "_fnCreateTr": _fnCreateTr, "_fnGatherData": _fnGatherData, "_fnBuildHead": _fnBuildHead, "_fnDrawHead": _fnDrawHead, "_fnDraw": _fnDraw, "_fnReDraw": _fnReDraw, "_fnAjaxUpdate": _fnAjaxUpdate, "_fnAjaxParameters": _fnAjaxParameters, "_fnAjaxUpdateDraw": _fnAjaxUpdateDraw, "_fnServerParams": _fnServerParams, "_fnAddOptionsHtml": _fnAddOptionsHtml, "_fnFeatureHtmlTable": _fnFeatureHtmlTable, "_fnScrollDraw": _fnScrollDraw, "_fnAdjustColumnSizing": _fnAdjustColumnSizing, "_fnFeatureHtmlFilter": _fnFeatureHtmlFilter, "_fnFilterComplete": _fnFilterComplete, "_fnFilterCustom": _fnFilterCustom, "_fnFilterColumn": _fnFilterColumn, "_fnFilter": _fnFilter, "_fnBuildSearchArray": _fnBuildSearchArray, "_fnBuildSearchRow": _fnBuildSearchRow, "_fnFilterCreateSearch": _fnFilterCreateSearch, "_fnDataToSearch": _fnDataToSearch, "_fnSort": _fnSort, "_fnSortAttachListener": _fnSortAttachListener, "_fnSortingClasses": _fnSortingClasses, "_fnFeatureHtmlPaginate": _fnFeatureHtmlPaginate, "_fnPageChange": _fnPageChange, "_fnFeatureHtmlInfo": _fnFeatureHtmlInfo, "_fnUpdateInfo": _fnUpdateInfo, "_fnFeatureHtmlLength": _fnFeatureHtmlLength, "_fnFeatureHtmlProcessing": _fnFeatureHtmlProcessing, "_fnProcessingDisplay": _fnProcessingDisplay, "_fnVisibleToColumnIndex": _fnVisibleToColumnIndex, "_fnColumnIndexToVisible": _fnColumnIndexToVisible, "_fnNodeToDataIndex": _fnNodeToDataIndex, "_fnVisbleColumns": _fnVisbleColumns, "_fnCalculateEnd": _fnCalculateEnd, "_fnConvertToWidth": _fnConvertToWidth, "_fnCalculateColumnWidths": _fnCalculateColumnWidths, "_fnScrollingWidthAdjust": _fnScrollingWidthAdjust, "_fnGetWidestNode": _fnGetWidestNode, "_fnGetMaxLenString": _fnGetMaxLenString, "_fnStringToCss": _fnStringToCss, "_fnDetectType": _fnDetectType, "_fnSettingsFromNode": _fnSettingsFromNode, "_fnGetDataMaster": _fnGetDataMaster, "_fnGetTrNodes": _fnGetTrNodes, "_fnGetTdNodes": _fnGetTdNodes, "_fnEscapeRegex": _fnEscapeRegex, "_fnDeleteIndex": _fnDeleteIndex, "_fnReOrderIndex": _fnReOrderIndex, "_fnColumnOrdering": _fnColumnOrdering, "_fnLog": _fnLog, "_fnClearTable": _fnClearTable, "_fnSaveState": _fnSaveState, "_fnLoadState": _fnLoadState, "_fnCreateCookie": _fnCreateCookie, "_fnReadCookie": _fnReadCookie, "_fnDetectHeader": _fnDetectHeader, "_fnGetUniqueThs": _fnGetUniqueThs, "_fnScrollBarWidth": _fnScrollBarWidth, "_fnApplyToChildren": _fnApplyToChildren, "_fnMap": _fnMap, "_fnGetRowData": _fnGetRowData, "_fnGetCellData": _fnGetCellData, "_fnSetCellData": _fnSetCellData, "_fnGetObjectDataFn": _fnGetObjectDataFn, "_fnSetObjectDataFn": _fnSetObjectDataFn, "_fnApplyColumnDefs": _fnApplyColumnDefs, "_fnBindAction": _fnBindAction, "_fnExtend": _fnExtend, "_fnCallbackReg": _fnCallbackReg, "_fnCallbackFire": _fnCallbackFire, "_fnJsonString": _fnJsonString, "_fnRender": _fnRender, "_fnNodeToColumnIndex": _fnNodeToColumnIndex, "_fnInfoMacros": _fnInfoMacros, "_fnBrowserDetect": _fnBrowserDetect, "_fnGetColumns": _fnGetColumns }; $.extend( DataTable.ext.oApi, this.oApi ); for ( var sFunc in DataTable.ext.oApi ) { if ( sFunc ) { this[sFunc] = _fnExternApiFunc(sFunc); } } var _that = this; this.each(function() { var i=0, iLen, j, jLen, k, kLen; var sId = this.getAttribute( 'id' ); var bInitHandedOff = false; var bUsePassedData = false; /* Sanity check */ if ( this.nodeName.toLowerCase() != 'table' ) { _fnLog( null, 0, "Attempted to initialise DataTables on a node which is not a "+ "table: "+this.nodeName ); return; } /* Check to see if we are re-initialising a table */ for ( i=0, iLen=DataTable.settings.length ; i<iLen ; i++ ) { /* Base check on table node */ if ( DataTable.settings[i].nTable == this ) { if ( oInit === undefined || oInit.bRetrieve ) { return DataTable.settings[i].oInstance; } else if ( oInit.bDestroy ) { DataTable.settings[i].oInstance.fnDestroy(); break; } else { _fnLog( DataTable.settings[i], 0, "Cannot reinitialise DataTable.\n\n"+ "To retrieve the DataTables object for this table, pass no arguments or see "+ "the docs for bRetrieve and bDestroy" ); return; } } /* If the element we are initialising has the same ID as a table which was previously * initialised, but the table nodes don't match (from before) then we destroy the old * instance by simply deleting it. This is under the assumption that the table has been * destroyed by other methods. Anyone using non-id selectors will need to do this manually */ if ( DataTable.settings[i].sTableId == this.id ) { DataTable.settings.splice( i, 1 ); break; } } /* Ensure the table has an ID - required for accessibility */ if ( sId === null || sId === "" ) { sId = "DataTables_Table_"+(DataTable.ext._oExternConfig.iNextUnique++); this.id = sId; } /* Create the settings object for this table and set some of the default parameters */ var oSettings = $.extend( true, {}, DataTable.models.oSettings, { "nTable": this, "oApi": _that.oApi, "oInit": oInit, "sDestroyWidth": $(this).width(), "sInstance": sId, "sTableId": sId } ); DataTable.settings.push( oSettings ); // Need to add the instance after the instance after the settings object has been added // to the settings array, so we can self reference the table instance if more than one oSettings.oInstance = (_that.length===1) ? _that : $(this).dataTable(); /* Setting up the initialisation object */ if ( !oInit ) { oInit = {}; } // Backwards compatibility, before we apply all the defaults if ( oInit.oLanguage ) { _fnLanguageCompat( oInit.oLanguage ); } oInit = _fnExtend( $.extend(true, {}, DataTable.defaults), oInit ); // Map the initialisation options onto the settings object _fnMap( oSettings.oFeatures, oInit, "bPaginate" ); _fnMap( oSettings.oFeatures, oInit, "bLengthChange" ); _fnMap( oSettings.oFeatures, oInit, "bFilter" ); _fnMap( oSettings.oFeatures, oInit, "bSort" ); _fnMap( oSettings.oFeatures, oInit, "bInfo" ); _fnMap( oSettings.oFeatures, oInit, "bProcessing" ); _fnMap( oSettings.oFeatures, oInit, "bAutoWidth" ); _fnMap( oSettings.oFeatures, oInit, "bSortClasses" ); _fnMap( oSettings.oFeatures, oInit, "bServerSide" ); _fnMap( oSettings.oFeatures, oInit, "bDeferRender" ); _fnMap( oSettings.oScroll, oInit, "sScrollX", "sX" ); _fnMap( oSettings.oScroll, oInit, "sScrollXInner", "sXInner" ); _fnMap( oSettings.oScroll, oInit, "sScrollY", "sY" ); _fnMap( oSettings.oScroll, oInit, "bScrollCollapse", "bCollapse" ); _fnMap( oSettings.oScroll, oInit, "bScrollInfinite", "bInfinite" ); _fnMap( oSettings.oScroll, oInit, "iScrollLoadGap", "iLoadGap" ); _fnMap( oSettings.oScroll, oInit, "bScrollAutoCss", "bAutoCss" ); _fnMap( oSettings, oInit, "asStripeClasses" ); _fnMap( oSettings, oInit, "asStripClasses", "asStripeClasses" ); // legacy _fnMap( oSettings, oInit, "fnServerData" ); _fnMap( oSettings, oInit, "fnFormatNumber" ); _fnMap( oSettings, oInit, "sServerMethod" ); _fnMap( oSettings, oInit, "aaSorting" ); _fnMap( oSettings, oInit, "aaSortingFixed" ); _fnMap( oSettings, oInit, "aLengthMenu" ); _fnMap( oSettings, oInit, "sPaginationType" ); _fnMap( oSettings, oInit, "sAjaxSource" ); _fnMap( oSettings, oInit, "sAjaxDataProp" ); _fnMap( oSettings, oInit, "iCookieDuration" ); _fnMap( oSettings, oInit, "sCookiePrefix" ); _fnMap( oSettings, oInit, "sDom" ); _fnMap( oSettings, oInit, "bSortCellsTop" ); _fnMap( oSettings, oInit, "iTabIndex" ); _fnMap( oSettings, oInit, "oSearch", "oPreviousSearch" ); _fnMap( oSettings, oInit, "aoSearchCols", "aoPreSearchCols" ); _fnMap( oSettings, oInit, "iDisplayLength", "_iDisplayLength" ); _fnMap( oSettings, oInit, "bJQueryUI", "bJUI" ); _fnMap( oSettings, oInit, "fnCookieCallback" ); _fnMap( oSettings, oInit, "fnStateLoad" ); _fnMap( oSettings, oInit, "fnStateSave" ); _fnMap( oSettings.oLanguage, oInit, "fnInfoCallback" ); /* Callback functions which are array driven */ _fnCallbackReg( oSettings, 'aoDrawCallback', oInit.fnDrawCallback, 'user' ); _fnCallbackReg( oSettings, 'aoServerParams', oInit.fnServerParams, 'user' ); _fnCallbackReg( oSettings, 'aoStateSaveParams', oInit.fnStateSaveParams, 'user' ); _fnCallbackReg( oSettings, 'aoStateLoadParams', oInit.fnStateLoadParams, 'user' ); _fnCallbackReg( oSettings, 'aoStateLoaded', oInit.fnStateLoaded, 'user' ); _fnCallbackReg( oSettings, 'aoRowCallback', oInit.fnRowCallback, 'user' ); _fnCallbackReg( oSettings, 'aoRowCreatedCallback', oInit.fnCreatedRow, 'user' ); _fnCallbackReg( oSettings, 'aoHeaderCallback', oInit.fnHeaderCallback, 'user' ); _fnCallbackReg( oSettings, 'aoFooterCallback', oInit.fnFooterCallback, 'user' ); _fnCallbackReg( oSettings, 'aoInitComplete', oInit.fnInitComplete, 'user' ); _fnCallbackReg( oSettings, 'aoPreDrawCallback', oInit.fnPreDrawCallback, 'user' ); if ( oSettings.oFeatures.bServerSide && oSettings.oFeatures.bSort && oSettings.oFeatures.bSortClasses ) { /* Enable sort classes for server-side processing. Safe to do it here, since server-side * processing must be enabled by the developer */ _fnCallbackReg( oSettings, 'aoDrawCallback', _fnSortingClasses, 'server_side_sort_classes' ); } else if ( oSettings.oFeatures.bDeferRender ) { _fnCallbackReg( oSettings, 'aoDrawCallback', _fnSortingClasses, 'defer_sort_classes' ); } if ( oInit.bJQueryUI ) { /* Use the JUI classes object for display. You could clone the oStdClasses object if * you want to have multiple tables with multiple independent classes */ $.extend( oSettings.oClasses, DataTable.ext.oJUIClasses ); if ( oInit.sDom === DataTable.defaults.sDom && DataTable.defaults.sDom === "lfrtip" ) { /* Set the DOM to use a layout suitable for jQuery UI's theming */ oSettings.sDom = '<"H"lfr>t<"F"ip>'; } } else { $.extend( oSettings.oClasses, DataTable.ext.oStdClasses ); } $(this).addClass( oSettings.oClasses.sTable ); /* Calculate the scroll bar width and cache it for use later on */ if ( oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "" ) { oSettings.oScroll.iBarWidth = _fnScrollBarWidth(); } if ( oSettings.iInitDisplayStart === undefined ) { /* Display start point, taking into account the save saving */ oSettings.iInitDisplayStart = oInit.iDisplayStart; oSettings._iDisplayStart = oInit.iDisplayStart; } /* Must be done after everything which can be overridden by a cookie! */ if ( oInit.bStateSave ) { oSettings.oFeatures.bStateSave = true; _fnLoadState( oSettings, oInit ); _fnCallbackReg( oSettings, 'aoDrawCallback', _fnSaveState, 'state_save' ); } if ( oInit.iDeferLoading !== null ) { oSettings.bDeferLoading = true; var tmp = $.isArray( oInit.iDeferLoading ); oSettings._iRecordsDisplay = tmp ? oInit.iDeferLoading[0] : oInit.iDeferLoading; oSettings._iRecordsTotal = tmp ? oInit.iDeferLoading[1] : oInit.iDeferLoading; } if ( oInit.aaData !== null ) { bUsePassedData = true; } /* Language definitions */ if ( oInit.oLanguage.sUrl !== "" ) { /* Get the language definitions from a file - because this Ajax call makes the language * get async to the remainder of this function we use bInitHandedOff to indicate that * _fnInitialise will be fired by the returned Ajax handler, rather than the constructor */ oSettings.oLanguage.sUrl = oInit.oLanguage.sUrl; $.getJSON( oSettings.oLanguage.sUrl, null, function( json ) { _fnLanguageCompat( json ); $.extend( true, oSettings.oLanguage, oInit.oLanguage, json ); _fnInitialise( oSettings ); } ); bInitHandedOff = true; } else { $.extend( true, oSettings.oLanguage, oInit.oLanguage ); } /* * Stripes */ if ( oInit.asStripeClasses === null ) { oSettings.asStripeClasses =[ oSettings.oClasses.sStripeOdd, oSettings.oClasses.sStripeEven ]; } /* Remove row stripe classes if they are already on the table row */ iLen=oSettings.asStripeClasses.length; oSettings.asDestroyStripes = []; if (iLen) { var bStripeRemove = false; var anRows = $(this).children('tbody').children('tr:lt(' + iLen + ')'); for ( i=0 ; i<iLen ; i++ ) { if ( anRows.hasClass( oSettings.asStripeClasses[i] ) ) { bStripeRemove = true; /* Store the classes which we are about to remove so they can be re-added on destroy */ oSettings.asDestroyStripes.push( oSettings.asStripeClasses[i] ); } } if ( bStripeRemove ) { anRows.removeClass( oSettings.asStripeClasses.join(' ') ); } } /* * Columns * See if we should load columns automatically or use defined ones */ var anThs = []; var aoColumnsInit; var nThead = this.getElementsByTagName('thead'); if ( nThead.length !== 0 ) { _fnDetectHeader( oSettings.aoHeader, nThead[0] ); anThs = _fnGetUniqueThs( oSettings ); } /* If not given a column array, generate one with nulls */ if ( oInit.aoColumns === null ) { aoColumnsInit = []; for ( i=0, iLen=anThs.length ; i<iLen ; i++ ) { aoColumnsInit.push( null ); } } else { aoColumnsInit = oInit.aoColumns; } /* Add the columns */ for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ ) { /* Short cut - use the loop to check if we have column visibility state to restore */ if ( oInit.saved_aoColumns !== undefined && oInit.saved_aoColumns.length == iLen ) { if ( aoColumnsInit[i] === null ) { aoColumnsInit[i] = {}; } aoColumnsInit[i].bVisible = oInit.saved_aoColumns[i].bVisible; } _fnAddColumn( oSettings, anThs ? anThs[i] : null ); } /* Apply the column definitions */ _fnApplyColumnDefs( oSettings, oInit.aoColumnDefs, aoColumnsInit, function (iCol, oDef) { _fnColumnOptions( oSettings, iCol, oDef ); } ); /* * Sorting * Check the aaSorting array */ for ( i=0, iLen=oSettings.aaSorting.length ; i<iLen ; i++ ) { if ( oSettings.aaSorting[i][0] >= oSettings.aoColumns.length ) { oSettings.aaSorting[i][0] = 0; } var oColumn = oSettings.aoColumns[ oSettings.aaSorting[i][0] ]; /* Add a default sorting index */ if ( oSettings.aaSorting[i][2] === undefined ) { oSettings.aaSorting[i][2] = 0; } /* If aaSorting is not defined, then we use the first indicator in asSorting */ if ( oInit.aaSorting === undefined && oSettings.saved_aaSorting === undefined ) { oSettings.aaSorting[i][1] = oColumn.asSorting[0]; } /* Set the current sorting index based on aoColumns.asSorting */ for ( j=0, jLen=oColumn.asSorting.length ; j<jLen ; j++ ) { if ( oSettings.aaSorting[i][1] == oColumn.asSorting[j] ) { oSettings.aaSorting[i][2] = j; break; } } } /* Do a first pass on the sorting classes (allows any size changes to be taken into * account, and also will apply sorting disabled classes if disabled */ _fnSortingClasses( oSettings ); /* * Final init * Cache the header, body and footer as required, creating them if needed */ /* Browser support detection */ _fnBrowserDetect( oSettings ); // Work around for Webkit bug 83867 - store the caption-side before removing from doc var captions = $(this).children('caption').each( function () { this._captionSide = $(this).css('caption-side'); } ); var thead = $(this).children('thead'); if ( thead.length === 0 ) { thead = [ document.createElement( 'thead' ) ]; this.appendChild( thead[0] ); } oSettings.nTHead = thead[0]; var tbody = $(this).children('tbody'); if ( tbody.length === 0 ) { tbody = [ document.createElement( 'tbody' ) ]; this.appendChild( tbody[0] ); } oSettings.nTBody = tbody[0]; oSettings.nTBody.setAttribute( "role", "alert" ); oSettings.nTBody.setAttribute( "aria-live", "polite" ); oSettings.nTBody.setAttribute( "aria-relevant", "all" ); var tfoot = $(this).children('tfoot'); if ( tfoot.length === 0 && captions.length > 0 && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "") ) { // If we are a scrolling table, and no footer has been given, then we need to create // a tfoot element for the caption element to be appended to tfoot = [ document.createElement( 'tfoot' ) ]; this.appendChild( tfoot[0] ); } if ( tfoot.length > 0 ) { oSettings.nTFoot = tfoot[0]; _fnDetectHeader( oSettings.aoFooter, oSettings.nTFoot ); } /* Check if there is data passing into the constructor */ if ( bUsePassedData ) { for ( i=0 ; i<oInit.aaData.length ; i++ ) { _fnAddData( oSettings, oInit.aaData[ i ] ); } } else { /* Grab the data from the page */ _fnGatherData( oSettings ); } /* Copy the data index array */ oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); /* Initialisation complete - table can be drawn */ oSettings.bInitialised = true; /* Check if we need to initialise the table (it might not have been handed off to the * language processor) */ if ( bInitHandedOff === false ) { _fnInitialise( oSettings ); } } ); _that = null; return this; }; /** * Provide a common method for plug-ins to check the version of DataTables being used, in order * to ensure compatibility. * @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the * formats "X" and "X.Y" are also acceptable. * @returns {boolean} true if this version of DataTables is greater or equal to the required * version, or false if this version of DataTales is not suitable * @static * @dtopt API-Static * * @example * alert( $.fn.dataTable.fnVersionCheck( '1.9.0' ) ); */ DataTable.fnVersionCheck = function( sVersion ) { /* This is cheap, but effective */ var fnZPad = function (Zpad, count) { while(Zpad.length < count) { Zpad += '0'; } return Zpad; }; var aThis = DataTable.ext.sVersion.split('.'); var aThat = sVersion.split('.'); var sThis = '', sThat = ''; for ( var i=0, iLen=aThat.length ; i<iLen ; i++ ) { sThis += fnZPad( aThis[i], 3 ); sThat += fnZPad( aThat[i], 3 ); } return parseInt(sThis, 10) >= parseInt(sThat, 10); }; /** * Check if a TABLE node is a DataTable table already or not. * @param {node} nTable The TABLE node to check if it is a DataTable or not (note that other * node types can be passed in, but will always return false). * @returns {boolean} true the table given is a DataTable, or false otherwise * @static * @dtopt API-Static * * @example * var ex = document.getElementById('example'); * if ( ! $.fn.DataTable.fnIsDataTable( ex ) ) { * $(ex).dataTable(); * } */ DataTable.fnIsDataTable = function ( nTable ) { var o = DataTable.settings; for ( var i=0 ; i<o.length ; i++ ) { if ( o[i].nTable === nTable || o[i].nScrollHead === nTable || o[i].nScrollFoot === nTable ) { return true; } } return false; }; /** * Get all DataTable tables that have been initialised - optionally you can select to * get only currently visible tables. * @param {boolean} [bVisible=false] Flag to indicate if you want all (default) or * visible tables only. * @returns {array} Array of TABLE nodes (not DataTable instances) which are DataTables * @static * @dtopt API-Static * * @example * var table = $.fn.dataTable.fnTables(true); * if ( table.length > 0 ) { * $(table).dataTable().fnAdjustColumnSizing(); * } */ DataTable.fnTables = function ( bVisible ) { var out = []; jQuery.each( DataTable.settings, function (i, o) { if ( !bVisible || (bVisible === true && $(o.nTable).is(':visible')) ) { out.push( o.nTable ); } } ); return out; }; /** * Version string for plug-ins to check compatibility. Allowed format is * a.b.c.d.e where: a:int, b:int, c:int, d:string(dev|beta), e:int. d and * e are optional * @member * @type string * @default Version number */ DataTable.version = "1.9.4"; /** * Private data store, containing all of the settings objects that are created for the * tables on a given page. * * Note that the <i>DataTable.settings</i> object is aliased to <i>jQuery.fn.dataTableExt</i> * through which it may be accessed and manipulated, or <i>jQuery.fn.dataTable.settings</i>. * @member * @type array * @default [] * @private */ DataTable.settings = []; /** * Object models container, for the various models that DataTables has available * to it. These models define the objects that are used to hold the active state * and configuration of the table. * @namespace */ DataTable.models = {}; /** * DataTables extension options and plug-ins. This namespace acts as a collection "area" * for plug-ins that can be used to extend the default DataTables behaviour - indeed many * of the build in methods use this method to provide their own capabilities (sorting methods * for example). * * Note that this namespace is aliased to jQuery.fn.dataTableExt so it can be readily accessed * and modified by plug-ins. * @namespace */ DataTable.models.ext = { /** * Plug-in filtering functions - this method of filtering is complimentary to the default * type based filtering, and a lot more comprehensive as it allows you complete control * over the filtering logic. Each element in this array is a function (parameters * described below) that is called for every row in the table, and your logic decides if * it should be included in the filtered data set or not. * <ul> * <li> * Function input parameters: * <ul> * <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li> * <li>{array|object} Data for the row to be processed (same as the original format * that was passed in as the data source, or an array from a DOM data source</li> * <li>{int} Row index in aoData ({@link DataTable.models.oSettings.aoData}), which can * be useful to retrieve the TR element if you need DOM interaction.</li> * </ul> * </li> * <li> * Function return: * <ul> * <li>{boolean} Include the row in the filtered result set (true) or not (false)</li> * </ul> * </il> * </ul> * @type array * @default [] * * @example * // The following example shows custom filtering being applied to the fourth column (i.e. * // the aData[3] index) based on two input values from the end-user, matching the data in * // a certain range. * $.fn.dataTableExt.afnFiltering.push( * function( oSettings, aData, iDataIndex ) { * var iMin = document.getElementById('min').value * 1; * var iMax = document.getElementById('max').value * 1; * var iVersion = aData[3] == "-" ? 0 : aData[3]*1; * if ( iMin == "" && iMax == "" ) { * return true; * } * else if ( iMin == "" && iVersion < iMax ) { * return true; * } * else if ( iMin < iVersion && "" == iMax ) { * return true; * } * else if ( iMin < iVersion && iVersion < iMax ) { * return true; * } * return false; * } * ); */ "afnFiltering": [], /** * Plug-in sorting functions - this method of sorting is complimentary to the default type * based sorting that DataTables does automatically, allowing much greater control over the * the data that is being used to sort a column. This is useful if you want to do sorting * based on live data (for example the contents of an 'input' element) rather than just the * static string that DataTables knows of. The way these plug-ins work is that you create * an array of the values you wish to be sorted for the column in question and then return * that array. Which pre-sorting function is run here depends on the sSortDataType parameter * that is used for the column (if any). This is the corollary of <i>ofnSearch</i> for sort * data. * <ul> * <li> * Function input parameters: * <ul> * <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li> * <li>{int} Target column index</li> * </ul> * </li> * <li> * Function return: * <ul> * <li>{array} Data for the column to be sorted upon</li> * </ul> * </il> * </ul> * * Note that as of v1.9, it is typically preferable to use <i>mData</i> to prepare data for * the different uses that DataTables can put the data to. Specifically <i>mData</i> when * used as a function will give you a 'type' (sorting, filtering etc) that you can use to * prepare the data as required for the different types. As such, this method is deprecated. * @type array * @default [] * @deprecated * * @example * // Updating the cached sorting information with user entered values in HTML input elements * jQuery.fn.dataTableExt.afnSortData['dom-text'] = function ( oSettings, iColumn ) * { * var aData = []; * $( 'td:eq('+iColumn+') input', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () { * aData.push( this.value ); * } ); * return aData; * } */ "afnSortData": [], /** * Feature plug-ins - This is an array of objects which describe the feature plug-ins that are * available to DataTables. These feature plug-ins are accessible through the sDom initialisation * option. As such, each feature plug-in must describe a function that is used to initialise * itself (fnInit), a character so the feature can be enabled by sDom (cFeature) and the name * of the feature (sFeature). Thus the objects attached to this method must provide: * <ul> * <li>{function} fnInit Initialisation of the plug-in * <ul> * <li> * Function input parameters: * <ul> * <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li> * </ul> * </li> * <li> * Function return: * <ul> * <li>{node|null} The element which contains your feature. Note that the return * may also be void if your plug-in does not require to inject any DOM elements * into DataTables control (sDom) - for example this might be useful when * developing a plug-in which allows table control via keyboard entry.</li> * </ul> * </il> * </ul> * </li> * <li>{character} cFeature Character that will be matched in sDom - case sensitive</li> * <li>{string} sFeature Feature name</li> * </ul> * @type array * @default [] * * @example * // How TableTools initialises itself. * $.fn.dataTableExt.aoFeatures.push( { * "fnInit": function( oSettings ) { * return new TableTools( { "oDTSettings": oSettings } ); * }, * "cFeature": "T", * "sFeature": "TableTools" * } ); */ "aoFeatures": [], /** * Type detection plug-in functions - DataTables utilises types to define how sorting and * filtering behave, and types can be either be defined by the developer (sType for the * column) or they can be automatically detected by the methods in this array. The functions * defined in the array are quite simple, taking a single parameter (the data to analyse) * and returning the type if it is a known type, or null otherwise. * <ul> * <li> * Function input parameters: * <ul> * <li>{*} Data from the column cell to be analysed</li> * </ul> * </li> * <li> * Function return: * <ul> * <li>{string|null} Data type detected, or null if unknown (and thus pass it * on to the other type detection functions.</li> * </ul> * </il> * </ul> * @type array * @default [] * * @example * // Currency type detection plug-in: * jQuery.fn.dataTableExt.aTypes.push( * function ( sData ) { * var sValidChars = "0123456789.-"; * var Char; * * // Check the numeric part * for ( i=1 ; i<sData.length ; i++ ) { * Char = sData.charAt(i); * if (sValidChars.indexOf(Char) == -1) { * return null; * } * } * * // Check prefixed by currency * if ( sData.charAt(0) == '$' || sData.charAt(0) == '&pound;' ) { * return 'currency'; * } * return null; * } * ); */ "aTypes": [], /** * Provide a common method for plug-ins to check the version of DataTables being used, * in order to ensure compatibility. * @type function * @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note * that the formats "X" and "X.Y" are also acceptable. * @returns {boolean} true if this version of DataTables is greater or equal to the * required version, or false if this version of DataTales is not suitable * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * alert( oTable.fnVersionCheck( '1.9.0' ) ); * } ); */ "fnVersionCheck": DataTable.fnVersionCheck, /** * Index for what 'this' index API functions should use * @type int * @default 0 */ "iApiIndex": 0, /** * Pre-processing of filtering data plug-ins - When you assign the sType for a column * (or have it automatically detected for you by DataTables or a type detection plug-in), * you will typically be using this for custom sorting, but it can also be used to provide * custom filtering by allowing you to pre-processing the data and returning the data in * the format that should be filtered upon. This is done by adding functions this object * with a parameter name which matches the sType for that target column. This is the * corollary of <i>afnSortData</i> for filtering data. * <ul> * <li> * Function input parameters: * <ul> * <li>{*} Data from the column cell to be prepared for filtering</li> * </ul> * </li> * <li> * Function return: * <ul> * <li>{string|null} Formatted string that will be used for the filtering.</li> * </ul> * </il> * </ul> * * Note that as of v1.9, it is typically preferable to use <i>mData</i> to prepare data for * the different uses that DataTables can put the data to. Specifically <i>mData</i> when * used as a function will give you a 'type' (sorting, filtering etc) that you can use to * prepare the data as required for the different types. As such, this method is deprecated. * @type object * @default {} * @deprecated * * @example * $.fn.dataTableExt.ofnSearch['title-numeric'] = function ( sData ) { * return sData.replace(/\n/g," ").replace( /<.*?>/g, "" ); * } */ "ofnSearch": {}, /** * Container for all private functions in DataTables so they can be exposed externally * @type object * @default {} */ "oApi": {}, /** * Storage for the various classes that DataTables uses * @type object * @default {} */ "oStdClasses": {}, /** * Storage for the various classes that DataTables uses - jQuery UI suitable * @type object * @default {} */ "oJUIClasses": {}, /** * Pagination plug-in methods - The style and controls of the pagination can significantly * impact on how the end user interacts with the data in your table, and DataTables allows * the addition of pagination controls by extending this object, which can then be enabled * through the <i>sPaginationType</i> initialisation parameter. Each pagination type that * is added is an object (the property name of which is what <i>sPaginationType</i> refers * to) that has two properties, both methods that are used by DataTables to update the * control's state. * <ul> * <li> * fnInit - Initialisation of the paging controls. Called only during initialisation * of the table. It is expected that this function will add the required DOM elements * to the page for the paging controls to work. The element pointer * 'oSettings.aanFeatures.p' array is provided by DataTables to contain the paging * controls (note that this is a 2D array to allow for multiple instances of each * DataTables DOM element). It is suggested that you add the controls to this element * as children * <ul> * <li> * Function input parameters: * <ul> * <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li> * <li>{node} Container into which the pagination controls must be inserted</li> * <li>{function} Draw callback function - whenever the controls cause a page * change, this method must be called to redraw the table.</li> * </ul> * </li> * <li> * Function return: * <ul> * <li>No return required</li> * </ul> * </il> * </ul> * </il> * <li> * fnInit - This function is called whenever the paging status of the table changes and is * typically used to update classes and/or text of the paging controls to reflex the new * status. * <ul> * <li> * Function input parameters: * <ul> * <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li> * <li>{function} Draw callback function - in case you need to redraw the table again * or attach new event listeners</li> * </ul> * </li> * <li> * Function return: * <ul> * <li>No return required</li> * </ul> * </il> * </ul> * </il> * </ul> * @type object * @default {} * * @example * $.fn.dataTableExt.oPagination.four_button = { * "fnInit": function ( oSettings, nPaging, fnCallbackDraw ) { * nFirst = document.createElement( 'span' ); * nPrevious = document.createElement( 'span' ); * nNext = document.createElement( 'span' ); * nLast = document.createElement( 'span' ); * * nFirst.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sFirst ) ); * nPrevious.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sPrevious ) ); * nNext.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sNext ) ); * nLast.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sLast ) ); * * nFirst.className = "paginate_button first"; * nPrevious.className = "paginate_button previous"; * nNext.className="paginate_button next"; * nLast.className = "paginate_button last"; * * nPaging.appendChild( nFirst ); * nPaging.appendChild( nPrevious ); * nPaging.appendChild( nNext ); * nPaging.appendChild( nLast ); * * $(nFirst).click( function () { * oSettings.oApi._fnPageChange( oSettings, "first" ); * fnCallbackDraw( oSettings ); * } ); * * $(nPrevious).click( function() { * oSettings.oApi._fnPageChange( oSettings, "previous" ); * fnCallbackDraw( oSettings ); * } ); * * $(nNext).click( function() { * oSettings.oApi._fnPageChange( oSettings, "next" ); * fnCallbackDraw( oSettings ); * } ); * * $(nLast).click( function() { * oSettings.oApi._fnPageChange( oSettings, "last" ); * fnCallbackDraw( oSettings ); * } ); * * $(nFirst).bind( 'selectstart', function () { return false; } ); * $(nPrevious).bind( 'selectstart', function () { return false; } ); * $(nNext).bind( 'selectstart', function () { return false; } ); * $(nLast).bind( 'selectstart', function () { return false; } ); * }, * * "fnUpdate": function ( oSettings, fnCallbackDraw ) { * if ( !oSettings.aanFeatures.p ) { * return; * } * * // Loop over each instance of the pager * var an = oSettings.aanFeatures.p; * for ( var i=0, iLen=an.length ; i<iLen ; i++ ) { * var buttons = an[i].getElementsByTagName('span'); * if ( oSettings._iDisplayStart === 0 ) { * buttons[0].className = "paginate_disabled_previous"; * buttons[1].className = "paginate_disabled_previous"; * } * else { * buttons[0].className = "paginate_enabled_previous"; * buttons[1].className = "paginate_enabled_previous"; * } * * if ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() ) { * buttons[2].className = "paginate_disabled_next"; * buttons[3].className = "paginate_disabled_next"; * } * else { * buttons[2].className = "paginate_enabled_next"; * buttons[3].className = "paginate_enabled_next"; * } * } * } * }; */ "oPagination": {}, /** * Sorting plug-in methods - Sorting in DataTables is based on the detected type of the * data column (you can add your own type detection functions, or override automatic * detection using sType). With this specific type given to the column, DataTables will * apply the required sort from the functions in the object. Each sort type must provide * two mandatory methods, one each for ascending and descending sorting, and can optionally * provide a pre-formatting method that will help speed up sorting by allowing DataTables * to pre-format the sort data only once (rather than every time the actual sort functions * are run). The two sorting functions are typical Javascript sort methods: * <ul> * <li> * Function input parameters: * <ul> * <li>{*} Data to compare to the second parameter</li> * <li>{*} Data to compare to the first parameter</li> * </ul> * </li> * <li> * Function return: * <ul> * <li>{int} Sorting match: <0 if first parameter should be sorted lower than * the second parameter, ===0 if the two parameters are equal and >0 if * the first parameter should be sorted height than the second parameter.</li> * </ul> * </il> * </ul> * @type object * @default {} * * @example * // Case-sensitive string sorting, with no pre-formatting method * $.extend( $.fn.dataTableExt.oSort, { * "string-case-asc": function(x,y) { * return ((x < y) ? -1 : ((x > y) ? 1 : 0)); * }, * "string-case-desc": function(x,y) { * return ((x < y) ? 1 : ((x > y) ? -1 : 0)); * } * } ); * * @example * // Case-insensitive string sorting, with pre-formatting * $.extend( $.fn.dataTableExt.oSort, { * "string-pre": function(x) { * return x.toLowerCase(); * }, * "string-asc": function(x,y) { * return ((x < y) ? -1 : ((x > y) ? 1 : 0)); * }, * "string-desc": function(x,y) { * return ((x < y) ? 1 : ((x > y) ? -1 : 0)); * } * } ); */ "oSort": {}, /** * Version string for plug-ins to check compatibility. Allowed format is * a.b.c.d.e where: a:int, b:int, c:int, d:string(dev|beta), e:int. d and * e are optional * @type string * @default Version number */ "sVersion": DataTable.version, /** * How should DataTables report an error. Can take the value 'alert' or 'throw' * @type string * @default alert */ "sErrMode": "alert", /** * Store information for DataTables to access globally about other instances * @namespace * @private */ "_oExternConfig": { /* int:iNextUnique - next unique number for an instance */ "iNextUnique": 0 } }; /** * Template object for the way in which DataTables holds information about * search information for the global filter and individual column filters. * @namespace */ DataTable.models.oSearch = { /** * Flag to indicate if the filtering should be case insensitive or not * @type boolean * @default true */ "bCaseInsensitive": true, /** * Applied search term * @type string * @default <i>Empty string</i> */ "sSearch": "", /** * Flag to indicate if the search term should be interpreted as a * regular expression (true) or not (false) and therefore and special * regex characters escaped. * @type boolean * @default false */ "bRegex": false, /** * Flag to indicate if DataTables is to use its smart filtering or not. * @type boolean * @default true */ "bSmart": true }; /** * Template object for the way in which DataTables holds information about * each individual row. This is the object format used for the settings * aoData array. * @namespace */ DataTable.models.oRow = { /** * TR element for the row * @type node * @default null */ "nTr": null, /** * Data object from the original data source for the row. This is either * an array if using the traditional form of DataTables, or an object if * using mData options. The exact type will depend on the passed in * data from the data source, or will be an array if using DOM a data * source. * @type array|object * @default [] */ "_aData": [], /** * Sorting data cache - this array is ostensibly the same length as the * number of columns (although each index is generated only as it is * needed), and holds the data that is used for sorting each column in the * row. We do this cache generation at the start of the sort in order that * the formatting of the sort data need be done only once for each cell * per sort. This array should not be read from or written to by anything * other than the master sorting methods. * @type array * @default [] * @private */ "_aSortData": [], /** * Array of TD elements that are cached for hidden rows, so they can be * reinserted into the table if a column is made visible again (or to act * as a store if a column is made hidden). Only hidden columns have a * reference in the array. For non-hidden columns the value is either * undefined or null. * @type array nodes * @default [] * @private */ "_anHidden": [], /** * Cache of the class name that DataTables has applied to the row, so we * can quickly look at this variable rather than needing to do a DOM check * on className for the nTr property. * @type string * @default <i>Empty string</i> * @private */ "_sRowStripe": "" }; /** * Template object for the column information object in DataTables. This object * is held in the settings aoColumns array and contains all the information that * DataTables needs about each individual column. * * Note that this object is related to {@link DataTable.defaults.columns} * but this one is the internal data store for DataTables's cache of columns. * It should NOT be manipulated outside of DataTables. Any configuration should * be done through the initialisation options. * @namespace */ DataTable.models.oColumn = { /** * A list of the columns that sorting should occur on when this column * is sorted. That this property is an array allows multi-column sorting * to be defined for a column (for example first name / last name columns * would benefit from this). The values are integers pointing to the * columns to be sorted on (typically it will be a single integer pointing * at itself, but that doesn't need to be the case). * @type array */ "aDataSort": null, /** * Define the sorting directions that are applied to the column, in sequence * as the column is repeatedly sorted upon - i.e. the first value is used * as the sorting direction when the column if first sorted (clicked on). * Sort it again (click again) and it will move on to the next index. * Repeat until loop. * @type array */ "asSorting": null, /** * Flag to indicate if the column is searchable, and thus should be included * in the filtering or not. * @type boolean */ "bSearchable": null, /** * Flag to indicate if the column is sortable or not. * @type boolean */ "bSortable": null, /** * <code>Deprecated</code> When using fnRender, you have two options for what * to do with the data, and this property serves as the switch. Firstly, you * can have the sorting and filtering use the rendered value (true - default), * or you can have the sorting and filtering us the original value (false). * * Please note that this option has now been deprecated and will be removed * in the next version of DataTables. Please use mRender / mData rather than * fnRender. * @type boolean * @deprecated */ "bUseRendered": null, /** * Flag to indicate if the column is currently visible in the table or not * @type boolean */ "bVisible": null, /** * Flag to indicate to the type detection method if the automatic type * detection should be used, or if a column type (sType) has been specified * @type boolean * @default true * @private */ "_bAutoType": true, /** * Developer definable function that is called whenever a cell is created (Ajax source, * etc) or processed for input (DOM source). This can be used as a compliment to mRender * allowing you to modify the DOM element (add background colour for example) when the * element is available. * @type function * @param {element} nTd The TD node that has been created * @param {*} sData The Data for the cell * @param {array|object} oData The data for the whole row * @param {int} iRow The row index for the aoData data store * @default null */ "fnCreatedCell": null, /** * Function to get data from a cell in a column. You should <b>never</b> * access data directly through _aData internally in DataTables - always use * the method attached to this property. It allows mData to function as * required. This function is automatically assigned by the column * initialisation method * @type function * @param {array|object} oData The data array/object for the array * (i.e. aoData[]._aData) * @param {string} sSpecific The specific data type you want to get - * 'display', 'type' 'filter' 'sort' * @returns {*} The data for the cell from the given row's data * @default null */ "fnGetData": null, /** * <code>Deprecated</code> Custom display function that will be called for the * display of each cell in this column. * * Please note that this option has now been deprecated and will be removed * in the next version of DataTables. Please use mRender / mData rather than * fnRender. * @type function * @param {object} o Object with the following parameters: * @param {int} o.iDataRow The row in aoData * @param {int} o.iDataColumn The column in question * @param {array} o.aData The data for the row in question * @param {object} o.oSettings The settings object for this DataTables instance * @returns {string} The string you which to use in the display * @default null * @deprecated */ "fnRender": null, /** * Function to set data for a cell in the column. You should <b>never</b> * set the data directly to _aData internally in DataTables - always use * this method. It allows mData to function as required. This function * is automatically assigned by the column initialisation method * @type function * @param {array|object} oData The data array/object for the array * (i.e. aoData[]._aData) * @param {*} sValue Value to set * @default null */ "fnSetData": null, /** * Property to read the value for the cells in the column from the data * source array / object. If null, then the default content is used, if a * function is given then the return from the function is used. * @type function|int|string|null * @default null */ "mData": null, /** * Partner property to mData which is used (only when defined) to get * the data - i.e. it is basically the same as mData, but without the * 'set' option, and also the data fed to it is the result from mData. * This is the rendering method to match the data method of mData. * @type function|int|string|null * @default null */ "mRender": null, /** * Unique header TH/TD element for this column - this is what the sorting * listener is attached to (if sorting is enabled.) * @type node * @default null */ "nTh": null, /** * Unique footer TH/TD element for this column (if there is one). Not used * in DataTables as such, but can be used for plug-ins to reference the * footer for each column. * @type node * @default null */ "nTf": null, /** * The class to apply to all TD elements in the table's TBODY for the column * @type string * @default null */ "sClass": null, /** * When DataTables calculates the column widths to assign to each column, * it finds the longest string in each column and then constructs a * temporary table and reads the widths from that. The problem with this * is that "mmm" is much wider then "iiii", but the latter is a longer * string - thus the calculation can go wrong (doing it properly and putting * it into an DOM object and measuring that is horribly(!) slow). Thus as * a "work around" we provide this option. It will append its value to the * text that is found to be the longest string for the column - i.e. padding. * @type string */ "sContentPadding": null, /** * Allows a default value to be given for a column's data, and will be used * whenever a null data source is encountered (this can be because mData * is set to null, or because the data source itself is null). * @type string * @default null */ "sDefaultContent": null, /** * Name for the column, allowing reference to the column by name as well as * by index (needs a lookup to work by name). * @type string */ "sName": null, /** * Custom sorting data type - defines which of the available plug-ins in * afnSortData the custom sorting will use - if any is defined. * @type string * @default std */ "sSortDataType": 'std', /** * Class to be applied to the header element when sorting on this column * @type string * @default null */ "sSortingClass": null, /** * Class to be applied to the header element when sorting on this column - * when jQuery UI theming is used. * @type string * @default null */ "sSortingClassJUI": null, /** * Title of the column - what is seen in the TH element (nTh). * @type string */ "sTitle": null, /** * Column sorting and filtering type * @type string * @default null */ "sType": null, /** * Width of the column * @type string * @default null */ "sWidth": null, /** * Width of the column when it was first "encountered" * @type string * @default null */ "sWidthOrig": null }; /** * Initialisation options that can be given to DataTables at initialisation * time. * @namespace */ DataTable.defaults = { /** * An array of data to use for the table, passed in at initialisation which * will be used in preference to any data which is already in the DOM. This is * particularly useful for constructing tables purely in Javascript, for * example with a custom Ajax call. * @type array * @default null * @dtopt Option * * @example * // Using a 2D array data source * $(document).ready( function () { * $('#example').dataTable( { * "aaData": [ * ['Trident', 'Internet Explorer 4.0', 'Win 95+', 4, 'X'], * ['Trident', 'Internet Explorer 5.0', 'Win 95+', 5, 'C'], * ], * "aoColumns": [ * { "sTitle": "Engine" }, * { "sTitle": "Browser" }, * { "sTitle": "Platform" }, * { "sTitle": "Version" }, * { "sTitle": "Grade" } * ] * } ); * } ); * * @example * // Using an array of objects as a data source (mData) * $(document).ready( function () { * $('#example').dataTable( { * "aaData": [ * { * "engine": "Trident", * "browser": "Internet Explorer 4.0", * "platform": "Win 95+", * "version": 4, * "grade": "X" * }, * { * "engine": "Trident", * "browser": "Internet Explorer 5.0", * "platform": "Win 95+", * "version": 5, * "grade": "C" * } * ], * "aoColumns": [ * { "sTitle": "Engine", "mData": "engine" }, * { "sTitle": "Browser", "mData": "browser" }, * { "sTitle": "Platform", "mData": "platform" }, * { "sTitle": "Version", "mData": "version" }, * { "sTitle": "Grade", "mData": "grade" } * ] * } ); * } ); */ "aaData": null, /** * If sorting is enabled, then DataTables will perform a first pass sort on * initialisation. You can define which column(s) the sort is performed upon, * and the sorting direction, with this variable. The aaSorting array should * contain an array for each column to be sorted initially containing the * column's index and a direction string ('asc' or 'desc'). * @type array * @default [[0,'asc']] * @dtopt Option * * @example * // Sort by 3rd column first, and then 4th column * $(document).ready( function() { * $('#example').dataTable( { * "aaSorting": [[2,'asc'], [3,'desc']] * } ); * } ); * * // No initial sorting * $(document).ready( function() { * $('#example').dataTable( { * "aaSorting": [] * } ); * } ); */ "aaSorting": [[0,'asc']], /** * This parameter is basically identical to the aaSorting parameter, but * cannot be overridden by user interaction with the table. What this means * is that you could have a column (visible or hidden) which the sorting will * always be forced on first - any sorting after that (from the user) will * then be performed as required. This can be useful for grouping rows * together. * @type array * @default null * @dtopt Option * * @example * $(document).ready( function() { * $('#example').dataTable( { * "aaSortingFixed": [[0,'asc']] * } ); * } ) */ "aaSortingFixed": null, /** * This parameter allows you to readily specify the entries in the length drop * down menu that DataTables shows when pagination is enabled. It can be * either a 1D array of options which will be used for both the displayed * option and the value, or a 2D array which will use the array in the first * position as the value, and the array in the second position as the * displayed options (useful for language strings such as 'All'). * @type array * @default [ 10, 25, 50, 100 ] * @dtopt Option * * @example * $(document).ready( function() { * $('#example').dataTable( { * "aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]] * } ); * } ); * * @example * // Setting the default display length as well as length menu * // This is likely to be wanted if you remove the '10' option which * // is the iDisplayLength default. * $(document).ready( function() { * $('#example').dataTable( { * "iDisplayLength": 25, * "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]] * } ); * } ); */ "aLengthMenu": [ 10, 25, 50, 100 ], /** * The aoColumns option in the initialisation parameter allows you to define * details about the way individual columns behave. For a full list of * column options that can be set, please see * {@link DataTable.defaults.columns}. Note that if you use aoColumns to * define your columns, you must have an entry in the array for every single * column that you have in your table (these can be null if you don't which * to specify any options). * @member */ "aoColumns": null, /** * Very similar to aoColumns, aoColumnDefs allows you to target a specific * column, multiple columns, or all columns, using the aTargets property of * each object in the array. This allows great flexibility when creating * tables, as the aoColumnDefs arrays can be of any length, targeting the * columns you specifically want. aoColumnDefs may use any of the column * options available: {@link DataTable.defaults.columns}, but it _must_ * have aTargets defined in each object in the array. Values in the aTargets * array may be: * <ul> * <li>a string - class name will be matched on the TH for the column</li> * <li>0 or a positive integer - column index counting from the left</li> * <li>a negative integer - column index counting from the right</li> * <li>the string "_all" - all columns (i.e. assign a default)</li> * </ul> * @member */ "aoColumnDefs": null, /** * Basically the same as oSearch, this parameter defines the individual column * filtering state at initialisation time. The array must be of the same size * as the number of columns, and each element be an object with the parameters * "sSearch" and "bEscapeRegex" (the latter is optional). 'null' is also * accepted and the default will be used. * @type array * @default [] * @dtopt Option * * @example * $(document).ready( function() { * $('#example').dataTable( { * "aoSearchCols": [ * null, * { "sSearch": "My filter" }, * null, * { "sSearch": "^[0-9]", "bEscapeRegex": false } * ] * } ); * } ) */ "aoSearchCols": [], /** * An array of CSS classes that should be applied to displayed rows. This * array may be of any length, and DataTables will apply each class * sequentially, looping when required. * @type array * @default null <i>Will take the values determined by the oClasses.sStripe* * options</i> * @dtopt Option * * @example * $(document).ready( function() { * $('#example').dataTable( { * "asStripeClasses": [ 'strip1', 'strip2', 'strip3' ] * } ); * } ) */ "asStripeClasses": null, /** * Enable or disable automatic column width calculation. This can be disabled * as an optimisation (it takes some time to calculate the widths) if the * tables widths are passed in using aoColumns. * @type boolean * @default true * @dtopt Features * * @example * $(document).ready( function () { * $('#example').dataTable( { * "bAutoWidth": false * } ); * } ); */ "bAutoWidth": true, /** * Deferred rendering can provide DataTables with a huge speed boost when you * are using an Ajax or JS data source for the table. This option, when set to * true, will cause DataTables to defer the creation of the table elements for * each row until they are needed for a draw - saving a significant amount of * time. * @type boolean * @default false * @dtopt Features * * @example * $(document).ready( function() { * var oTable = $('#example').dataTable( { * "sAjaxSource": "sources/arrays.txt", * "bDeferRender": true * } ); * } ); */ "bDeferRender": false, /** * Replace a DataTable which matches the given selector and replace it with * one which has the properties of the new initialisation object passed. If no * table matches the selector, then the new DataTable will be constructed as * per normal. * @type boolean * @default false * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "sScrollY": "200px", * "bPaginate": false * } ); * * // Some time later.... * $('#example').dataTable( { * "bFilter": false, * "bDestroy": true * } ); * } ); */ "bDestroy": false, /** * Enable or disable filtering of data. Filtering in DataTables is "smart" in * that it allows the end user to input multiple words (space separated) and * will match a row containing those words, even if not in the order that was * specified (this allow matching across multiple columns). Note that if you * wish to use filtering in DataTables this must remain 'true' - to remove the * default filtering input box and retain filtering abilities, please use * {@link DataTable.defaults.sDom}. * @type boolean * @default true * @dtopt Features * * @example * $(document).ready( function () { * $('#example').dataTable( { * "bFilter": false * } ); * } ); */ "bFilter": true, /** * Enable or disable the table information display. This shows information * about the data that is currently visible on the page, including information * about filtered data if that action is being performed. * @type boolean * @default true * @dtopt Features * * @example * $(document).ready( function () { * $('#example').dataTable( { * "bInfo": false * } ); * } ); */ "bInfo": true, /** * Enable jQuery UI ThemeRoller support (required as ThemeRoller requires some * slightly different and additional mark-up from what DataTables has * traditionally used). * @type boolean * @default false * @dtopt Features * * @example * $(document).ready( function() { * $('#example').dataTable( { * "bJQueryUI": true * } ); * } ); */ "bJQueryUI": false, /** * Allows the end user to select the size of a formatted page from a select * menu (sizes are 10, 25, 50 and 100). Requires pagination (bPaginate). * @type boolean * @default true * @dtopt Features * * @example * $(document).ready( function () { * $('#example').dataTable( { * "bLengthChange": false * } ); * } ); */ "bLengthChange": true, /** * Enable or disable pagination. * @type boolean * @default true * @dtopt Features * * @example * $(document).ready( function () { * $('#example').dataTable( { * "bPaginate": false * } ); * } ); */ "bPaginate": true, /** * Enable or disable the display of a 'processing' indicator when the table is * being processed (e.g. a sort). This is particularly useful for tables with * large amounts of data where it can take a noticeable amount of time to sort * the entries. * @type boolean * @default false * @dtopt Features * * @example * $(document).ready( function () { * $('#example').dataTable( { * "bProcessing": true * } ); * } ); */ "bProcessing": false, /** * Retrieve the DataTables object for the given selector. Note that if the * table has already been initialised, this parameter will cause DataTables * to simply return the object that has already been set up - it will not take * account of any changes you might have made to the initialisation object * passed to DataTables (setting this parameter to true is an acknowledgement * that you understand this). bDestroy can be used to reinitialise a table if * you need. * @type boolean * @default false * @dtopt Options * * @example * $(document).ready( function() { * initTable(); * tableActions(); * } ); * * function initTable () * { * return $('#example').dataTable( { * "sScrollY": "200px", * "bPaginate": false, * "bRetrieve": true * } ); * } * * function tableActions () * { * var oTable = initTable(); * // perform API operations with oTable * } */ "bRetrieve": false, /** * Indicate if DataTables should be allowed to set the padding / margin * etc for the scrolling header elements or not. Typically you will want * this. * @type boolean * @default true * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "bScrollAutoCss": false, * "sScrollY": "200px" * } ); * } ); */ "bScrollAutoCss": true, /** * When vertical (y) scrolling is enabled, DataTables will force the height of * the table's viewport to the given height at all times (useful for layout). * However, this can look odd when filtering data down to a small data set, * and the footer is left "floating" further down. This parameter (when * enabled) will cause DataTables to collapse the table's viewport down when * the result set will fit within the given Y height. * @type boolean * @default false * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "sScrollY": "200", * "bScrollCollapse": true * } ); * } ); */ "bScrollCollapse": false, /** * Enable infinite scrolling for DataTables (to be used in combination with * sScrollY). Infinite scrolling means that DataTables will continually load * data as a user scrolls through a table, which is very useful for large * dataset. This cannot be used with pagination, which is automatically * disabled. Note - the Scroller extra for DataTables is recommended in * in preference to this option. * @type boolean * @default false * @dtopt Features * * @example * $(document).ready( function() { * $('#example').dataTable( { * "bScrollInfinite": true, * "bScrollCollapse": true, * "sScrollY": "200px" * } ); * } ); */ "bScrollInfinite": false, /** * Configure DataTables to use server-side processing. Note that the * sAjaxSource parameter must also be given in order to give DataTables a * source to obtain the required data for each draw. * @type boolean * @default false * @dtopt Features * @dtopt Server-side * * @example * $(document).ready( function () { * $('#example').dataTable( { * "bServerSide": true, * "sAjaxSource": "xhr.php" * } ); * } ); */ "bServerSide": false, /** * Enable or disable sorting of columns. Sorting of individual columns can be * disabled by the "bSortable" option for each column. * @type boolean * @default true * @dtopt Features * * @example * $(document).ready( function () { * $('#example').dataTable( { * "bSort": false * } ); * } ); */ "bSort": true, /** * Allows control over whether DataTables should use the top (true) unique * cell that is found for a single column, or the bottom (false - default). * This is useful when using complex headers. * @type boolean * @default false * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "bSortCellsTop": true * } ); * } ); */ "bSortCellsTop": false, /** * Enable or disable the addition of the classes 'sorting_1', 'sorting_2' and * 'sorting_3' to the columns which are currently being sorted on. This is * presented as a feature switch as it can increase processing time (while * classes are removed and added) so for large data sets you might want to * turn this off. * @type boolean * @default true * @dtopt Features * * @example * $(document).ready( function () { * $('#example').dataTable( { * "bSortClasses": false * } ); * } ); */ "bSortClasses": true, /** * Enable or disable state saving. When enabled a cookie will be used to save * table display information such as pagination information, display length, * filtering and sorting. As such when the end user reloads the page the * display display will match what thy had previously set up. * @type boolean * @default false * @dtopt Features * * @example * $(document).ready( function () { * $('#example').dataTable( { * "bStateSave": true * } ); * } ); */ "bStateSave": false, /** * Customise the cookie and / or the parameters being stored when using * DataTables with state saving enabled. This function is called whenever * the cookie is modified, and it expects a fully formed cookie string to be * returned. Note that the data object passed in is a Javascript object which * must be converted to a string (JSON.stringify for example). * @type function * @param {string} sName Name of the cookie defined by DataTables * @param {object} oData Data to be stored in the cookie * @param {string} sExpires Cookie expires string * @param {string} sPath Path of the cookie to set * @returns {string} Cookie formatted string (which should be encoded by * using encodeURIComponent()) * @dtopt Callbacks * * @example * $(document).ready( function () { * $('#example').dataTable( { * "fnCookieCallback": function (sName, oData, sExpires, sPath) { * // Customise oData or sName or whatever else here * return sName + "="+JSON.stringify(oData)+"; expires=" + sExpires +"; path=" + sPath; * } * } ); * } ); */ "fnCookieCallback": null, /** * This function is called when a TR element is created (and all TD child * elements have been inserted), or registered if using a DOM source, allowing * manipulation of the TR element (adding classes etc). * @type function * @param {node} nRow "TR" element for the current row * @param {array} aData Raw data array for this row * @param {int} iDataIndex The index of this row in aoData * @dtopt Callbacks * * @example * $(document).ready( function() { * $('#example').dataTable( { * "fnCreatedRow": function( nRow, aData, iDataIndex ) { * // Bold the grade for all 'A' grade browsers * if ( aData[4] == "A" ) * { * $('td:eq(4)', nRow).html( '<b>A</b>' ); * } * } * } ); * } ); */ "fnCreatedRow": null, /** * This function is called on every 'draw' event, and allows you to * dynamically modify any aspect you want about the created DOM. * @type function * @param {object} oSettings DataTables settings object * @dtopt Callbacks * * @example * $(document).ready( function() { * $('#example').dataTable( { * "fnDrawCallback": function( oSettings ) { * alert( 'DataTables has redrawn the table' ); * } * } ); * } ); */ "fnDrawCallback": null, /** * Identical to fnHeaderCallback() but for the table footer this function * allows you to modify the table footer on every 'draw' even. * @type function * @param {node} nFoot "TR" element for the footer * @param {array} aData Full table data (as derived from the original HTML) * @param {int} iStart Index for the current display starting point in the * display array * @param {int} iEnd Index for the current display ending point in the * display array * @param {array int} aiDisplay Index array to translate the visual position * to the full data array * @dtopt Callbacks * * @example * $(document).ready( function() { * $('#example').dataTable( { * "fnFooterCallback": function( nFoot, aData, iStart, iEnd, aiDisplay ) { * nFoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+iStart; * } * } ); * } ) */ "fnFooterCallback": null, /** * When rendering large numbers in the information element for the table * (i.e. "Showing 1 to 10 of 57 entries") DataTables will render large numbers * to have a comma separator for the 'thousands' units (e.g. 1 million is * rendered as "1,000,000") to help readability for the end user. This * function will override the default method DataTables uses. * @type function * @member * @param {int} iIn number to be formatted * @returns {string} formatted string for DataTables to show the number * @dtopt Callbacks * * @example * $(document).ready( function() { * $('#example').dataTable( { * "fnFormatNumber": function ( iIn ) { * if ( iIn &lt; 1000 ) { * return iIn; * } else { * var * s=(iIn+""), * a=s.split(""), out="", * iLen=s.length; * * for ( var i=0 ; i&lt;iLen ; i++ ) { * if ( i%3 === 0 &amp;&amp; i !== 0 ) { * out = "'"+out; * } * out = a[iLen-i-1]+out; * } * } * return out; * }; * } ); * } ); */ "fnFormatNumber": function ( iIn ) { if ( iIn < 1000 ) { // A small optimisation for what is likely to be the majority of use cases return iIn; } var s=(iIn+""), a=s.split(""), out="", iLen=s.length; for ( var i=0 ; i<iLen ; i++ ) { if ( i%3 === 0 && i !== 0 ) { out = this.oLanguage.sInfoThousands+out; } out = a[iLen-i-1]+out; } return out; }, /** * This function is called on every 'draw' event, and allows you to * dynamically modify the header row. This can be used to calculate and * display useful information about the table. * @type function * @param {node} nHead "TR" element for the header * @param {array} aData Full table data (as derived from the original HTML) * @param {int} iStart Index for the current display starting point in the * display array * @param {int} iEnd Index for the current display ending point in the * display array * @param {array int} aiDisplay Index array to translate the visual position * to the full data array * @dtopt Callbacks * * @example * $(document).ready( function() { * $('#example').dataTable( { * "fnHeaderCallback": function( nHead, aData, iStart, iEnd, aiDisplay ) { * nHead.getElementsByTagName('th')[0].innerHTML = "Displaying "+(iEnd-iStart)+" records"; * } * } ); * } ) */ "fnHeaderCallback": null, /** * The information element can be used to convey information about the current * state of the table. Although the internationalisation options presented by * DataTables are quite capable of dealing with most customisations, there may * be times where you wish to customise the string further. This callback * allows you to do exactly that. * @type function * @param {object} oSettings DataTables settings object * @param {int} iStart Starting position in data for the draw * @param {int} iEnd End position in data for the draw * @param {int} iMax Total number of rows in the table (regardless of * filtering) * @param {int} iTotal Total number of rows in the data set, after filtering * @param {string} sPre The string that DataTables has formatted using it's * own rules * @returns {string} The string to be displayed in the information element. * @dtopt Callbacks * * @example * $('#example').dataTable( { * "fnInfoCallback": function( oSettings, iStart, iEnd, iMax, iTotal, sPre ) { * return iStart +" to "+ iEnd; * } * } ); */ "fnInfoCallback": null, /** * Called when the table has been initialised. Normally DataTables will * initialise sequentially and there will be no need for this function, * however, this does not hold true when using external language information * since that is obtained using an async XHR call. * @type function * @param {object} oSettings DataTables settings object * @param {object} json The JSON object request from the server - only * present if client-side Ajax sourced data is used * @dtopt Callbacks * * @example * $(document).ready( function() { * $('#example').dataTable( { * "fnInitComplete": function(oSettings, json) { * alert( 'DataTables has finished its initialisation.' ); * } * } ); * } ) */ "fnInitComplete": null, /** * Called at the very start of each table draw and can be used to cancel the * draw by returning false, any other return (including undefined) results in * the full draw occurring). * @type function * @param {object} oSettings DataTables settings object * @returns {boolean} False will cancel the draw, anything else (including no * return) will allow it to complete. * @dtopt Callbacks * * @example * $(document).ready( function() { * $('#example').dataTable( { * "fnPreDrawCallback": function( oSettings ) { * if ( $('#test').val() == 1 ) { * return false; * } * } * } ); * } ); */ "fnPreDrawCallback": null, /** * This function allows you to 'post process' each row after it have been * generated for each table draw, but before it is rendered on screen. This * function might be used for setting the row class name etc. * @type function * @param {node} nRow "TR" element for the current row * @param {array} aData Raw data array for this row * @param {int} iDisplayIndex The display index for the current table draw * @param {int} iDisplayIndexFull The index of the data in the full list of * rows (after filtering) * @dtopt Callbacks * * @example * $(document).ready( function() { * $('#example').dataTable( { * "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { * // Bold the grade for all 'A' grade browsers * if ( aData[4] == "A" ) * { * $('td:eq(4)', nRow).html( '<b>A</b>' ); * } * } * } ); * } ); */ "fnRowCallback": null, /** * This parameter allows you to override the default function which obtains * the data from the server ($.getJSON) so something more suitable for your * application. For example you could use POST data, or pull information from * a Gears or AIR database. * @type function * @member * @param {string} sSource HTTP source to obtain the data from (sAjaxSource) * @param {array} aoData A key/value pair object containing the data to send * to the server * @param {function} fnCallback to be called on completion of the data get * process that will draw the data on the page. * @param {object} oSettings DataTables settings object * @dtopt Callbacks * @dtopt Server-side * * @example * // POST data to server * $(document).ready( function() { * $('#example').dataTable( { * "bProcessing": true, * "bServerSide": true, * "sAjaxSource": "xhr.php", * "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { * oSettings.jqXHR = $.ajax( { * "dataType": 'json', * "type": "POST", * "url": sSource, * "data": aoData, * "success": fnCallback * } ); * } * } ); * } ); */ "fnServerData": function ( sUrl, aoData, fnCallback, oSettings ) { oSettings.jqXHR = $.ajax( { "url": sUrl, "data": aoData, "success": function (json) { if ( json.sError ) { oSettings.oApi._fnLog( oSettings, 0, json.sError ); } $(oSettings.oInstance).trigger('xhr', [oSettings, json]); fnCallback( json ); }, "dataType": "json", "cache": false, "type": oSettings.sServerMethod, "error": function (xhr, error, thrown) { if ( error == "parsererror" ) { oSettings.oApi._fnLog( oSettings, 0, "DataTables warning: JSON data from "+ "server could not be parsed. This is caused by a JSON formatting error." ); } } } ); }, /** * It is often useful to send extra data to the server when making an Ajax * request - for example custom filtering information, and this callback * function makes it trivial to send extra information to the server. The * passed in parameter is the data set that has been constructed by * DataTables, and you can add to this or modify it as you require. * @type function * @param {array} aoData Data array (array of objects which are name/value * pairs) that has been constructed by DataTables and will be sent to the * server. In the case of Ajax sourced data with server-side processing * this will be an empty array, for server-side processing there will be a * significant number of parameters! * @returns {undefined} Ensure that you modify the aoData array passed in, * as this is passed by reference. * @dtopt Callbacks * @dtopt Server-side * * @example * $(document).ready( function() { * $('#example').dataTable( { * "bProcessing": true, * "bServerSide": true, * "sAjaxSource": "scripts/server_processing.php", * "fnServerParams": function ( aoData ) { * aoData.push( { "name": "more_data", "value": "my_value" } ); * } * } ); * } ); */ "fnServerParams": null, /** * Load the table state. With this function you can define from where, and how, the * state of a table is loaded. By default DataTables will load from its state saving * cookie, but you might wish to use local storage (HTML5) or a server-side database. * @type function * @member * @param {object} oSettings DataTables settings object * @return {object} The DataTables state object to be loaded * @dtopt Callbacks * * @example * $(document).ready( function() { * $('#example').dataTable( { * "bStateSave": true, * "fnStateLoad": function (oSettings) { * var o; * * // Send an Ajax request to the server to get the data. Note that * // this is a synchronous request. * $.ajax( { * "url": "/state_load", * "async": false, * "dataType": "json", * "success": function (json) { * o = json; * } * } ); * * return o; * } * } ); * } ); */ "fnStateLoad": function ( oSettings ) { var sData = this.oApi._fnReadCookie( oSettings.sCookiePrefix+oSettings.sInstance ); var oData; try { oData = (typeof $.parseJSON === 'function') ? $.parseJSON(sData) : eval( '('+sData+')' ); } catch (e) { oData = null; } return oData; }, /** * Callback which allows modification of the saved state prior to loading that state. * This callback is called when the table is loading state from the stored data, but * prior to the settings object being modified by the saved state. Note that for * plug-in authors, you should use the 'stateLoadParams' event to load parameters for * a plug-in. * @type function * @param {object} oSettings DataTables settings object * @param {object} oData The state object that is to be loaded * @dtopt Callbacks * * @example * // Remove a saved filter, so filtering is never loaded * $(document).ready( function() { * $('#example').dataTable( { * "bStateSave": true, * "fnStateLoadParams": function (oSettings, oData) { * oData.oSearch.sSearch = ""; * } * } ); * } ); * * @example * // Disallow state loading by returning false * $(document).ready( function() { * $('#example').dataTable( { * "bStateSave": true, * "fnStateLoadParams": function (oSettings, oData) { * return false; * } * } ); * } ); */ "fnStateLoadParams": null, /** * Callback that is called when the state has been loaded from the state saving method * and the DataTables settings object has been modified as a result of the loaded state. * @type function * @param {object} oSettings DataTables settings object * @param {object} oData The state object that was loaded * @dtopt Callbacks * * @example * // Show an alert with the filtering value that was saved * $(document).ready( function() { * $('#example').dataTable( { * "bStateSave": true, * "fnStateLoaded": function (oSettings, oData) { * alert( 'Saved filter was: '+oData.oSearch.sSearch ); * } * } ); * } ); */ "fnStateLoaded": null, /** * Save the table state. This function allows you to define where and how the state * information for the table is stored - by default it will use a cookie, but you * might want to use local storage (HTML5) or a server-side database. * @type function * @member * @param {object} oSettings DataTables settings object * @param {object} oData The state object to be saved * @dtopt Callbacks * * @example * $(document).ready( function() { * $('#example').dataTable( { * "bStateSave": true, * "fnStateSave": function (oSettings, oData) { * // Send an Ajax request to the server with the state object * $.ajax( { * "url": "/state_save", * "data": oData, * "dataType": "json", * "method": "POST" * "success": function () {} * } ); * } * } ); * } ); */ "fnStateSave": function ( oSettings, oData ) { this.oApi._fnCreateCookie( oSettings.sCookiePrefix+oSettings.sInstance, this.oApi._fnJsonString(oData), oSettings.iCookieDuration, oSettings.sCookiePrefix, oSettings.fnCookieCallback ); }, /** * Callback which allows modification of the state to be saved. Called when the table * has changed state a new state save is required. This method allows modification of * the state saving object prior to actually doing the save, including addition or * other state properties or modification. Note that for plug-in authors, you should * use the 'stateSaveParams' event to save parameters for a plug-in. * @type function * @param {object} oSettings DataTables settings object * @param {object} oData The state object to be saved * @dtopt Callbacks * * @example * // Remove a saved filter, so filtering is never saved * $(document).ready( function() { * $('#example').dataTable( { * "bStateSave": true, * "fnStateSaveParams": function (oSettings, oData) { * oData.oSearch.sSearch = ""; * } * } ); * } ); */ "fnStateSaveParams": null, /** * Duration of the cookie which is used for storing session information. This * value is given in seconds. * @type int * @default 7200 <i>(2 hours)</i> * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "iCookieDuration": 60*60*24; // 1 day * } ); * } ) */ "iCookieDuration": 7200, /** * When enabled DataTables will not make a request to the server for the first * page draw - rather it will use the data already on the page (no sorting etc * will be applied to it), thus saving on an XHR at load time. iDeferLoading * is used to indicate that deferred loading is required, but it is also used * to tell DataTables how many records there are in the full table (allowing * the information element and pagination to be displayed correctly). In the case * where a filtering is applied to the table on initial load, this can be * indicated by giving the parameter as an array, where the first element is * the number of records available after filtering and the second element is the * number of records without filtering (allowing the table information element * to be shown correctly). * @type int | array * @default null * @dtopt Options * * @example * // 57 records available in the table, no filtering applied * $(document).ready( function() { * $('#example').dataTable( { * "bServerSide": true, * "sAjaxSource": "scripts/server_processing.php", * "iDeferLoading": 57 * } ); * } ); * * @example * // 57 records after filtering, 100 without filtering (an initial filter applied) * $(document).ready( function() { * $('#example').dataTable( { * "bServerSide": true, * "sAjaxSource": "scripts/server_processing.php", * "iDeferLoading": [ 57, 100 ], * "oSearch": { * "sSearch": "my_filter" * } * } ); * } ); */ "iDeferLoading": null, /** * Number of rows to display on a single page when using pagination. If * feature enabled (bLengthChange) then the end user will be able to override * this to a custom setting using a pop-up menu. * @type int * @default 10 * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "iDisplayLength": 50 * } ); * } ) */ "iDisplayLength": 10, /** * Define the starting point for data display when using DataTables with * pagination. Note that this parameter is the number of records, rather than * the page number, so if you have 10 records per page and want to start on * the third page, it should be "20". * @type int * @default 0 * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "iDisplayStart": 20 * } ); * } ) */ "iDisplayStart": 0, /** * The scroll gap is the amount of scrolling that is left to go before * DataTables will load the next 'page' of data automatically. You typically * want a gap which is big enough that the scrolling will be smooth for the * user, while not so large that it will load more data than need. * @type int * @default 100 * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "bScrollInfinite": true, * "bScrollCollapse": true, * "sScrollY": "200px", * "iScrollLoadGap": 50 * } ); * } ); */ "iScrollLoadGap": 100, /** * By default DataTables allows keyboard navigation of the table (sorting, paging, * and filtering) by adding a tabindex attribute to the required elements. This * allows you to tab through the controls and press the enter key to activate them. * The tabindex is default 0, meaning that the tab follows the flow of the document. * You can overrule this using this parameter if you wish. Use a value of -1 to * disable built-in keyboard navigation. * @type int * @default 0 * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "iTabIndex": 1 * } ); * } ); */ "iTabIndex": 0, /** * All strings that DataTables uses in the user interface that it creates * are defined in this object, allowing you to modified them individually or * completely replace them all as required. * @namespace */ "oLanguage": { /** * Strings that are used for WAI-ARIA labels and controls only (these are not * actually visible on the page, but will be read by screenreaders, and thus * must be internationalised as well). * @namespace */ "oAria": { /** * ARIA label that is added to the table headers when the column may be * sorted ascending by activing the column (click or return when focused). * Note that the column header is prefixed to this string. * @type string * @default : activate to sort column ascending * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "oAria": { * "sSortAscending": " - click/return to sort ascending" * } * } * } ); * } ); */ "sSortAscending": ": activate to sort column ascending", /** * ARIA label that is added to the table headers when the column may be * sorted descending by activing the column (click or return when focused). * Note that the column header is prefixed to this string. * @type string * @default : activate to sort column ascending * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "oAria": { * "sSortDescending": " - click/return to sort descending" * } * } * } ); * } ); */ "sSortDescending": ": activate to sort column descending" }, /** * Pagination string used by DataTables for the two built-in pagination * control types ("two_button" and "full_numbers") * @namespace */ "oPaginate": { /** * Text to use when using the 'full_numbers' type of pagination for the * button to take the user to the first page. * @type string * @default First * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "oPaginate": { * "sFirst": "First page" * } * } * } ); * } ); */ "sFirst": "First", /** * Text to use when using the 'full_numbers' type of pagination for the * button to take the user to the last page. * @type string * @default Last * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "oPaginate": { * "sLast": "Last page" * } * } * } ); * } ); */ "sLast": "Last", /** * Text to use for the 'next' pagination button (to take the user to the * next page). * @type string * @default Next * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "oPaginate": { * "sNext": "Next page" * } * } * } ); * } ); */ "sNext": "Next", /** * Text to use for the 'previous' pagination button (to take the user to * the previous page). * @type string * @default Previous * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "oPaginate": { * "sPrevious": "Previous page" * } * } * } ); * } ); */ "sPrevious": "Previous" }, /** * This string is shown in preference to sZeroRecords when the table is * empty of data (regardless of filtering). Note that this is an optional * parameter - if it is not given, the value of sZeroRecords will be used * instead (either the default or given value). * @type string * @default No data available in table * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sEmptyTable": "No data available in table" * } * } ); * } ); */ "sEmptyTable": "No data available in table", /** * This string gives information to the end user about the information that * is current on display on the page. The _START_, _END_ and _TOTAL_ * variables are all dynamically replaced as the table display updates, and * can be freely moved or removed as the language requirements change. * @type string * @default Showing _START_ to _END_ of _TOTAL_ entries * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sInfo": "Got a total of _TOTAL_ entries to show (_START_ to _END_)" * } * } ); * } ); */ "sInfo": "Showing _START_ to _END_ of _TOTAL_ entries", /** * Display information string for when the table is empty. Typically the * format of this string should match sInfo. * @type string * @default Showing 0 to 0 of 0 entries * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sInfoEmpty": "No entries to show" * } * } ); * } ); */ "sInfoEmpty": "Showing 0 to 0 of 0 entries", /** * When a user filters the information in a table, this string is appended * to the information (sInfo) to give an idea of how strong the filtering * is. The variable _MAX_ is dynamically updated. * @type string * @default (filtered from _MAX_ total entries) * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sInfoFiltered": " - filtering from _MAX_ records" * } * } ); * } ); */ "sInfoFiltered": "(filtered from _MAX_ total entries)", /** * If can be useful to append extra information to the info string at times, * and this variable does exactly that. This information will be appended to * the sInfo (sInfoEmpty and sInfoFiltered in whatever combination they are * being used) at all times. * @type string * @default <i>Empty string</i> * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sInfoPostFix": "All records shown are derived from real information." * } * } ); * } ); */ "sInfoPostFix": "", /** * DataTables has a build in number formatter (fnFormatNumber) which is used * to format large numbers that are used in the table information. By * default a comma is used, but this can be trivially changed to any * character you wish with this parameter. * @type string * @default , * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sInfoThousands": "'" * } * } ); * } ); */ "sInfoThousands": ",", /** * Detail the action that will be taken when the drop down menu for the * pagination length option is changed. The '_MENU_' variable is replaced * with a default select list of 10, 25, 50 and 100, and can be replaced * with a custom select box if required. * @type string * @default Show _MENU_ entries * @dtopt Language * * @example * // Language change only * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sLengthMenu": "Display _MENU_ records" * } * } ); * } ); * * @example * // Language and options change * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sLengthMenu": 'Display <select>'+ * '<option value="10">10</option>'+ * '<option value="20">20</option>'+ * '<option value="30">30</option>'+ * '<option value="40">40</option>'+ * '<option value="50">50</option>'+ * '<option value="-1">All</option>'+ * '</select> records' * } * } ); * } ); */ "sLengthMenu": "Show _MENU_ entries", /** * When using Ajax sourced data and during the first draw when DataTables is * gathering the data, this message is shown in an empty row in the table to * indicate to the end user the the data is being loaded. Note that this * parameter is not used when loading data by server-side processing, just * Ajax sourced data with client-side processing. * @type string * @default Loading... * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sLoadingRecords": "Please wait - loading..." * } * } ); * } ); */ "sLoadingRecords": "Loading...", /** * Text which is displayed when the table is processing a user action * (usually a sort command or similar). * @type string * @default Processing... * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sProcessing": "DataTables is currently busy" * } * } ); * } ); */ "sProcessing": "Processing...", /** * Details the actions that will be taken when the user types into the * filtering input text box. The variable "_INPUT_", if used in the string, * is replaced with the HTML text box for the filtering input allowing * control over where it appears in the string. If "_INPUT_" is not given * then the input box is appended to the string automatically. * @type string * @default Search: * @dtopt Language * * @example * // Input text box will be appended at the end automatically * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sSearch": "Filter records:" * } * } ); * } ); * * @example * // Specify where the filter should appear * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sSearch": "Apply filter _INPUT_ to table" * } * } ); * } ); */ "sSearch": "Search:", /** * All of the language information can be stored in a file on the * server-side, which DataTables will look up if this parameter is passed. * It must store the URL of the language file, which is in a JSON format, * and the object has the same properties as the oLanguage object in the * initialiser object (i.e. the above parameters). Please refer to one of * the example language files to see how this works in action. * @type string * @default <i>Empty string - i.e. disabled</i> * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sUrl": "http://www.sprymedia.co.uk/dataTables/lang.txt" * } * } ); * } ); */ "sUrl": "", /** * Text shown inside the table records when the is no information to be * displayed after filtering. sEmptyTable is shown when there is simply no * information in the table at all (regardless of filtering). * @type string * @default No matching records found * @dtopt Language * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oLanguage": { * "sZeroRecords": "No records to display" * } * } ); * } ); */ "sZeroRecords": "No matching records found" }, /** * This parameter allows you to have define the global filtering state at * initialisation time. As an object the "sSearch" parameter must be * defined, but all other parameters are optional. When "bRegex" is true, * the search string will be treated as a regular expression, when false * (default) it will be treated as a straight string. When "bSmart" * DataTables will use it's smart filtering methods (to word match at * any point in the data), when false this will not be done. * @namespace * @extends DataTable.models.oSearch * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "oSearch": {"sSearch": "Initial search"} * } ); * } ) */ "oSearch": $.extend( {}, DataTable.models.oSearch ), /** * By default DataTables will look for the property 'aaData' when obtaining * data from an Ajax source or for server-side processing - this parameter * allows that property to be changed. You can use Javascript dotted object * notation to get a data source for multiple levels of nesting. * @type string * @default aaData * @dtopt Options * @dtopt Server-side * * @example * // Get data from { "data": [...] } * $(document).ready( function() { * var oTable = $('#example').dataTable( { * "sAjaxSource": "sources/data.txt", * "sAjaxDataProp": "data" * } ); * } ); * * @example * // Get data from { "data": { "inner": [...] } } * $(document).ready( function() { * var oTable = $('#example').dataTable( { * "sAjaxSource": "sources/data.txt", * "sAjaxDataProp": "data.inner" * } ); * } ); */ "sAjaxDataProp": "aaData", /** * You can instruct DataTables to load data from an external source using this * parameter (use aData if you want to pass data in you already have). Simply * provide a url a JSON object can be obtained from. This object must include * the parameter 'aaData' which is the data source for the table. * @type string * @default null * @dtopt Options * @dtopt Server-side * * @example * $(document).ready( function() { * $('#example').dataTable( { * "sAjaxSource": "http://www.sprymedia.co.uk/dataTables/json.php" * } ); * } ) */ "sAjaxSource": null, /** * This parameter can be used to override the default prefix that DataTables * assigns to a cookie when state saving is enabled. * @type string * @default SpryMedia_DataTables_ * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "sCookiePrefix": "my_datatable_", * } ); * } ); */ "sCookiePrefix": "SpryMedia_DataTables_", /** * This initialisation variable allows you to specify exactly where in the * DOM you want DataTables to inject the various controls it adds to the page * (for example you might want the pagination controls at the top of the * table). DIV elements (with or without a custom class) can also be added to * aid styling. The follow syntax is used: * <ul> * <li>The following options are allowed: * <ul> * <li>'l' - Length changing</li * <li>'f' - Filtering input</li> * <li>'t' - The table!</li> * <li>'i' - Information</li> * <li>'p' - Pagination</li> * <li>'r' - pRocessing</li> * </ul> * </li> * <li>The following constants are allowed: * <ul> * <li>'H' - jQueryUI theme "header" classes ('fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix')</li> * <li>'F' - jQueryUI theme "footer" classes ('fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix')</li> * </ul> * </li> * <li>The following syntax is expected: * <ul> * <li>'&lt;' and '&gt;' - div elements</li> * <li>'&lt;"class" and '&gt;' - div with a class</li> * <li>'&lt;"#id" and '&gt;' - div with an ID</li> * </ul> * </li> * <li>Examples: * <ul> * <li>'&lt;"wrapper"flipt&gt;'</li> * <li>'&lt;lf&lt;t&gt;ip&gt;'</li> * </ul> * </li> * </ul> * @type string * @default lfrtip <i>(when bJQueryUI is false)</i> <b>or</b> * <"H"lfr>t<"F"ip> <i>(when bJQueryUI is true)</i> * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "sDom": '&lt;"top"i&gt;rt&lt;"bottom"flp&gt;&lt;"clear"&gt;' * } ); * } ); */ "sDom": "lfrtip", /** * DataTables features two different built-in pagination interaction methods * ('two_button' or 'full_numbers') which present different page controls to * the end user. Further methods can be added using the API (see below). * @type string * @default two_button * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "sPaginationType": "full_numbers" * } ); * } ) */ "sPaginationType": "two_button", /** * Enable horizontal scrolling. When a table is too wide to fit into a certain * layout, or you have a large number of columns in the table, you can enable * x-scrolling to show the table in a viewport, which can be scrolled. This * property can be any CSS unit, or a number (in which case it will be treated * as a pixel measurement). * @type string * @default <i>blank string - i.e. disabled</i> * @dtopt Features * * @example * $(document).ready( function() { * $('#example').dataTable( { * "sScrollX": "100%", * "bScrollCollapse": true * } ); * } ); */ "sScrollX": "", /** * This property can be used to force a DataTable to use more width than it * might otherwise do when x-scrolling is enabled. For example if you have a * table which requires to be well spaced, this parameter is useful for * "over-sizing" the table, and thus forcing scrolling. This property can by * any CSS unit, or a number (in which case it will be treated as a pixel * measurement). * @type string * @default <i>blank string - i.e. disabled</i> * @dtopt Options * * @example * $(document).ready( function() { * $('#example').dataTable( { * "sScrollX": "100%", * "sScrollXInner": "110%" * } ); * } ); */ "sScrollXInner": "", /** * Enable vertical scrolling. Vertical scrolling will constrain the DataTable * to the given height, and enable scrolling for any data which overflows the * current viewport. This can be used as an alternative to paging to display * a lot of data in a small area (although paging and scrolling can both be * enabled at the same time). This property can be any CSS unit, or a number * (in which case it will be treated as a pixel measurement). * @type string * @default <i>blank string - i.e. disabled</i> * @dtopt Features * * @example * $(document).ready( function() { * $('#example').dataTable( { * "sScrollY": "200px", * "bPaginate": false * } ); * } ); */ "sScrollY": "", /** * Set the HTTP method that is used to make the Ajax call for server-side * processing or Ajax sourced data. * @type string * @default GET * @dtopt Options * @dtopt Server-side * * @example * $(document).ready( function() { * $('#example').dataTable( { * "bServerSide": true, * "sAjaxSource": "scripts/post.php", * "sServerMethod": "POST" * } ); * } ); */ "sServerMethod": "GET" }; /** * Column options that can be given to DataTables at initialisation time. * @namespace */ DataTable.defaults.columns = { /** * Allows a column's sorting to take multiple columns into account when * doing a sort. For example first name / last name columns make sense to * do a multi-column sort over the two columns. * @type array * @default null <i>Takes the value of the column index automatically</i> * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] }, * { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] }, * { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] } * ] * } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * { "aDataSort": [ 0, 1 ] }, * { "aDataSort": [ 1, 0 ] }, * { "aDataSort": [ 2, 3, 4 ] }, * null, * null * ] * } ); * } ); */ "aDataSort": null, /** * You can control the default sorting direction, and even alter the behaviour * of the sort handler (i.e. only allow ascending sorting etc) using this * parameter. * @type array * @default [ 'asc', 'desc' ] * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { "asSorting": [ "asc" ], "aTargets": [ 1 ] }, * { "asSorting": [ "desc", "asc", "asc" ], "aTargets": [ 2 ] }, * { "asSorting": [ "desc" ], "aTargets": [ 3 ] } * ] * } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * null, * { "asSorting": [ "asc" ] }, * { "asSorting": [ "desc", "asc", "asc" ] }, * { "asSorting": [ "desc" ] }, * null * ] * } ); * } ); */ "asSorting": [ 'asc', 'desc' ], /** * Enable or disable filtering on the data in this column. * @type boolean * @default true * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { "bSearchable": false, "aTargets": [ 0 ] } * ] } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * { "bSearchable": false }, * null, * null, * null, * null * ] } ); * } ); */ "bSearchable": true, /** * Enable or disable sorting on this column. * @type boolean * @default true * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { "bSortable": false, "aTargets": [ 0 ] } * ] } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * { "bSortable": false }, * null, * null, * null, * null * ] } ); * } ); */ "bSortable": true, /** * <code>Deprecated</code> When using fnRender() for a column, you may wish * to use the original data (before rendering) for sorting and filtering * (the default is to used the rendered data that the user can see). This * may be useful for dates etc. * * Please note that this option has now been deprecated and will be removed * in the next version of DataTables. Please use mRender / mData rather than * fnRender. * @type boolean * @default true * @dtopt Columns * @deprecated */ "bUseRendered": true, /** * Enable or disable the display of this column. * @type boolean * @default true * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { "bVisible": false, "aTargets": [ 0 ] } * ] } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * { "bVisible": false }, * null, * null, * null, * null * ] } ); * } ); */ "bVisible": true, /** * Developer definable function that is called whenever a cell is created (Ajax source, * etc) or processed for input (DOM source). This can be used as a compliment to mRender * allowing you to modify the DOM element (add background colour for example) when the * element is available. * @type function * @param {element} nTd The TD node that has been created * @param {*} sData The Data for the cell * @param {array|object} oData The data for the whole row * @param {int} iRow The row index for the aoData data store * @param {int} iCol The column index for aoColumns * @dtopt Columns * * @example * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ { * "aTargets": [3], * "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) { * if ( sData == "1.7" ) { * $(nTd).css('color', 'blue') * } * } * } ] * }); * } ); */ "fnCreatedCell": null, /** * <code>Deprecated</code> Custom display function that will be called for the * display of each cell in this column. * * Please note that this option has now been deprecated and will be removed * in the next version of DataTables. Please use mRender / mData rather than * fnRender. * @type function * @param {object} o Object with the following parameters: * @param {int} o.iDataRow The row in aoData * @param {int} o.iDataColumn The column in question * @param {array} o.aData The data for the row in question * @param {object} o.oSettings The settings object for this DataTables instance * @param {object} o.mDataProp The data property used for this column * @param {*} val The current cell value * @returns {string} The string you which to use in the display * @dtopt Columns * @deprecated */ "fnRender": null, /** * The column index (starting from 0!) that you wish a sort to be performed * upon when this column is selected for sorting. This can be used for sorting * on hidden columns for example. * @type int * @default -1 <i>Use automatically calculated column index</i> * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { "iDataSort": 1, "aTargets": [ 0 ] } * ] * } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * { "iDataSort": 1 }, * null, * null, * null, * null * ] * } ); * } ); */ "iDataSort": -1, /** * This parameter has been replaced by mData in DataTables to ensure naming * consistency. mDataProp can still be used, as there is backwards compatibility * in DataTables for this option, but it is strongly recommended that you use * mData in preference to mDataProp. * @name DataTable.defaults.columns.mDataProp */ /** * This property can be used to read data from any JSON data source property, * including deeply nested objects / properties. mData can be given in a * number of different ways which effect its behaviour: * <ul> * <li>integer - treated as an array index for the data source. This is the * default that DataTables uses (incrementally increased for each column).</li> * <li>string - read an object property from the data source. Note that you can * use Javascript dotted notation to read deep properties / arrays from the * data source.</li> * <li>null - the sDefaultContent option will be used for the cell (null * by default, so you will need to specify the default content you want - * typically an empty string). This can be useful on generated columns such * as edit / delete action columns.</li> * <li>function - the function given will be executed whenever DataTables * needs to set or get the data for a cell in the column. The function * takes three parameters: * <ul> * <li>{array|object} The data source for the row</li> * <li>{string} The type call data requested - this will be 'set' when * setting data or 'filter', 'display', 'type', 'sort' or undefined when * gathering data. Note that when <i>undefined</i> is given for the type * DataTables expects to get the raw data for the object back</li> * <li>{*} Data to set when the second parameter is 'set'.</li> * </ul> * The return value from the function is not required when 'set' is the type * of call, but otherwise the return is what will be used for the data * requested.</li> * </ul> * * Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change * reflects the flexibility of this property and is consistent with the naming of * mRender. If 'mDataProp' is given, then it will still be used by DataTables, as * it automatically maps the old name to the new if required. * @type string|int|function|null * @default null <i>Use automatically calculated column index</i> * @dtopt Columns * * @example * // Read table data from objects * $(document).ready( function() { * var oTable = $('#example').dataTable( { * "sAjaxSource": "sources/deep.txt", * "aoColumns": [ * { "mData": "engine" }, * { "mData": "browser" }, * { "mData": "platform.inner" }, * { "mData": "platform.details.0" }, * { "mData": "platform.details.1" } * ] * } ); * } ); * * @example * // Using mData as a function to provide different information for * // sorting, filtering and display. In this case, currency (price) * $(document).ready( function() { * var oTable = $('#example').dataTable( { * "aoColumnDefs": [ { * "aTargets": [ 0 ], * "mData": function ( source, type, val ) { * if (type === 'set') { * source.price = val; * // Store the computed dislay and filter values for efficiency * source.price_display = val=="" ? "" : "$"+numberFormat(val); * source.price_filter = val=="" ? "" : "$"+numberFormat(val)+" "+val; * return; * } * else if (type === 'display') { * return source.price_display; * } * else if (type === 'filter') { * return source.price_filter; * } * // 'sort', 'type' and undefined all just use the integer * return source.price; * } * } ] * } ); * } ); */ "mData": null, /** * This property is the rendering partner to mData and it is suggested that * when you want to manipulate data for display (including filtering, sorting etc) * but not altering the underlying data for the table, use this property. mData * can actually do everything this property can and more, but this parameter is * easier to use since there is no 'set' option. Like mData is can be given * in a number of different ways to effect its behaviour, with the addition of * supporting array syntax for easy outputting of arrays (including arrays of * objects): * <ul> * <li>integer - treated as an array index for the data source. This is the * default that DataTables uses (incrementally increased for each column).</li> * <li>string - read an object property from the data source. Note that you can * use Javascript dotted notation to read deep properties / arrays from the * data source and also array brackets to indicate that the data reader should * loop over the data source array. When characters are given between the array * brackets, these characters are used to join the data source array together. * For example: "accounts[, ].name" would result in a comma separated list with * the 'name' value from the 'accounts' array of objects.</li> * <li>function - the function given will be executed whenever DataTables * needs to set or get the data for a cell in the column. The function * takes three parameters: * <ul> * <li>{array|object} The data source for the row (based on mData)</li> * <li>{string} The type call data requested - this will be 'filter', 'display', * 'type' or 'sort'.</li> * <li>{array|object} The full data source for the row (not based on mData)</li> * </ul> * The return value from the function is what will be used for the data * requested.</li> * </ul> * @type string|int|function|null * @default null <i>Use mData</i> * @dtopt Columns * * @example * // Create a comma separated list from an array of objects * $(document).ready( function() { * var oTable = $('#example').dataTable( { * "sAjaxSource": "sources/deep.txt", * "aoColumns": [ * { "mData": "engine" }, * { "mData": "browser" }, * { * "mData": "platform", * "mRender": "[, ].name" * } * ] * } ); * } ); * * @example * // Use as a function to create a link from the data source * $(document).ready( function() { * var oTable = $('#example').dataTable( { * "aoColumnDefs": [ * { * "aTargets": [ 0 ], * "mData": "download_link", * "mRender": function ( data, type, full ) { * return '<a href="'+data+'">Download</a>'; * } * ] * } ); * } ); */ "mRender": null, /** * Change the cell type created for the column - either TD cells or TH cells. This * can be useful as TH cells have semantic meaning in the table body, allowing them * to act as a header for a row (you may wish to add scope='row' to the TH elements). * @type string * @default td * @dtopt Columns * * @example * // Make the first column use TH cells * $(document).ready( function() { * var oTable = $('#example').dataTable( { * "aoColumnDefs": [ { * "aTargets": [ 0 ], * "sCellType": "th" * } ] * } ); * } ); */ "sCellType": "td", /** * Class to give to each cell in this column. * @type string * @default <i>Empty string</i> * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { "sClass": "my_class", "aTargets": [ 0 ] } * ] * } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * { "sClass": "my_class" }, * null, * null, * null, * null * ] * } ); * } ); */ "sClass": "", /** * When DataTables calculates the column widths to assign to each column, * it finds the longest string in each column and then constructs a * temporary table and reads the widths from that. The problem with this * is that "mmm" is much wider then "iiii", but the latter is a longer * string - thus the calculation can go wrong (doing it properly and putting * it into an DOM object and measuring that is horribly(!) slow). Thus as * a "work around" we provide this option. It will append its value to the * text that is found to be the longest string for the column - i.e. padding. * Generally you shouldn't need this, and it is not documented on the * general DataTables.net documentation * @type string * @default <i>Empty string<i> * @dtopt Columns * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * null, * null, * null, * { * "sContentPadding": "mmm" * } * ] * } ); * } ); */ "sContentPadding": "", /** * Allows a default value to be given for a column's data, and will be used * whenever a null data source is encountered (this can be because mData * is set to null, or because the data source itself is null). * @type string * @default null * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { * "mData": null, * "sDefaultContent": "Edit", * "aTargets": [ -1 ] * } * ] * } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * null, * null, * null, * { * "mData": null, * "sDefaultContent": "Edit" * } * ] * } ); * } ); */ "sDefaultContent": null, /** * This parameter is only used in DataTables' server-side processing. It can * be exceptionally useful to know what columns are being displayed on the * client side, and to map these to database fields. When defined, the names * also allow DataTables to reorder information from the server if it comes * back in an unexpected order (i.e. if you switch your columns around on the * client-side, your server-side code does not also need updating). * @type string * @default <i>Empty string</i> * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { "sName": "engine", "aTargets": [ 0 ] }, * { "sName": "browser", "aTargets": [ 1 ] }, * { "sName": "platform", "aTargets": [ 2 ] }, * { "sName": "version", "aTargets": [ 3 ] }, * { "sName": "grade", "aTargets": [ 4 ] } * ] * } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * { "sName": "engine" }, * { "sName": "browser" }, * { "sName": "platform" }, * { "sName": "version" }, * { "sName": "grade" } * ] * } ); * } ); */ "sName": "", /** * Defines a data source type for the sorting which can be used to read * real-time information from the table (updating the internally cached * version) prior to sorting. This allows sorting to occur on user editable * elements such as form inputs. * @type string * @default std * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { "sSortDataType": "dom-text", "aTargets": [ 2, 3 ] }, * { "sType": "numeric", "aTargets": [ 3 ] }, * { "sSortDataType": "dom-select", "aTargets": [ 4 ] }, * { "sSortDataType": "dom-checkbox", "aTargets": [ 5 ] } * ] * } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * null, * null, * { "sSortDataType": "dom-text" }, * { "sSortDataType": "dom-text", "sType": "numeric" }, * { "sSortDataType": "dom-select" }, * { "sSortDataType": "dom-checkbox" } * ] * } ); * } ); */ "sSortDataType": "std", /** * The title of this column. * @type string * @default null <i>Derived from the 'TH' value for this column in the * original HTML table.</i> * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { "sTitle": "My column title", "aTargets": [ 0 ] } * ] * } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * { "sTitle": "My column title" }, * null, * null, * null, * null * ] * } ); * } ); */ "sTitle": null, /** * The type allows you to specify how the data for this column will be sorted. * Four types (string, numeric, date and html (which will strip HTML tags * before sorting)) are currently available. Note that only date formats * understood by Javascript's Date() object will be accepted as type date. For * example: "Mar 26, 2008 5:03 PM". May take the values: 'string', 'numeric', * 'date' or 'html' (by default). Further types can be adding through * plug-ins. * @type string * @default null <i>Auto-detected from raw data</i> * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { "sType": "html", "aTargets": [ 0 ] } * ] * } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * { "sType": "html" }, * null, * null, * null, * null * ] * } ); * } ); */ "sType": null, /** * Defining the width of the column, this parameter may take any CSS value * (3em, 20px etc). DataTables apples 'smart' widths to columns which have not * been given a specific width through this interface ensuring that the table * remains readable. * @type string * @default null <i>Automatic</i> * @dtopt Columns * * @example * // Using aoColumnDefs * $(document).ready( function() { * $('#example').dataTable( { * "aoColumnDefs": [ * { "sWidth": "20%", "aTargets": [ 0 ] } * ] * } ); * } ); * * @example * // Using aoColumns * $(document).ready( function() { * $('#example').dataTable( { * "aoColumns": [ * { "sWidth": "20%" }, * null, * null, * null, * null * ] * } ); * } ); */ "sWidth": null }; /** * DataTables settings object - this holds all the information needed for a * given table, including configuration, data and current application of the * table options. DataTables does not have a single instance for each DataTable * with the settings attached to that instance, but rather instances of the * DataTable "class" are created on-the-fly as needed (typically by a * $().dataTable() call) and the settings object is then applied to that * instance. * * Note that this object is related to {@link DataTable.defaults} but this * one is the internal data store for DataTables's cache of columns. It should * NOT be manipulated outside of DataTables. Any configuration should be done * through the initialisation options. * @namespace * @todo Really should attach the settings object to individual instances so we * don't need to create new instances on each $().dataTable() call (if the * table already exists). It would also save passing oSettings around and * into every single function. However, this is a very significant * architecture change for DataTables and will almost certainly break * backwards compatibility with older installations. This is something that * will be done in 2.0. */ DataTable.models.oSettings = { /** * Primary features of DataTables and their enablement state. * @namespace */ "oFeatures": { /** * Flag to say if DataTables should automatically try to calculate the * optimum table and columns widths (true) or not (false). * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bAutoWidth": null, /** * Delay the creation of TR and TD elements until they are actually * needed by a driven page draw. This can give a significant speed * increase for Ajax source and Javascript source data, but makes no * difference at all fro DOM and server-side processing tables. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bDeferRender": null, /** * Enable filtering on the table or not. Note that if this is disabled * then there is no filtering at all on the table, including fnFilter. * To just remove the filtering input use sDom and remove the 'f' option. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bFilter": null, /** * Table information element (the 'Showing x of y records' div) enable * flag. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bInfo": null, /** * Present a user control allowing the end user to change the page size * when pagination is enabled. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bLengthChange": null, /** * Pagination enabled or not. Note that if this is disabled then length * changing must also be disabled. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bPaginate": null, /** * Processing indicator enable flag whenever DataTables is enacting a * user request - typically an Ajax request for server-side processing. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bProcessing": null, /** * Server-side processing enabled flag - when enabled DataTables will * get all data from the server for every draw - there is no filtering, * sorting or paging done on the client-side. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bServerSide": null, /** * Sorting enablement flag. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bSort": null, /** * Apply a class to the columns which are being sorted to provide a * visual highlight or not. This can slow things down when enabled since * there is a lot of DOM interaction. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bSortClasses": null, /** * State saving enablement flag. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bStateSave": null }, /** * Scrolling settings for a table. * @namespace */ "oScroll": { /** * Indicate if DataTables should be allowed to set the padding / margin * etc for the scrolling header elements or not. Typically you will want * this. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bAutoCss": null, /** * When the table is shorter in height than sScrollY, collapse the * table container down to the height of the table (when true). * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bCollapse": null, /** * Infinite scrolling enablement flag. Now deprecated in favour of * using the Scroller plug-in. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bInfinite": null, /** * Width of the scrollbar for the web-browser's platform. Calculated * during table initialisation. * @type int * @default 0 */ "iBarWidth": 0, /** * Space (in pixels) between the bottom of the scrolling container and * the bottom of the scrolling viewport before the next page is loaded * when using infinite scrolling. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type int */ "iLoadGap": null, /** * Viewport width for horizontal scrolling. Horizontal scrolling is * disabled if an empty string. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string */ "sX": null, /** * Width to expand the table to when using x-scrolling. Typically you * should not need to use this. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @deprecated */ "sXInner": null, /** * Viewport height for vertical scrolling. Vertical scrolling is disabled * if an empty string. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string */ "sY": null }, /** * Language information for the table. * @namespace * @extends DataTable.defaults.oLanguage */ "oLanguage": { /** * Information callback function. See * {@link DataTable.defaults.fnInfoCallback} * @type function * @default null */ "fnInfoCallback": null }, /** * Browser support parameters * @namespace */ "oBrowser": { /** * Indicate if the browser incorrectly calculates width:100% inside a * scrolling element (IE6/7) * @type boolean * @default false */ "bScrollOversize": false }, /** * Array referencing the nodes which are used for the features. The * parameters of this object match what is allowed by sDom - i.e. * <ul> * <li>'l' - Length changing</li> * <li>'f' - Filtering input</li> * <li>'t' - The table!</li> * <li>'i' - Information</li> * <li>'p' - Pagination</li> * <li>'r' - pRocessing</li> * </ul> * @type array * @default [] */ "aanFeatures": [], /** * Store data information - see {@link DataTable.models.oRow} for detailed * information. * @type array * @default [] */ "aoData": [], /** * Array of indexes which are in the current display (after filtering etc) * @type array * @default [] */ "aiDisplay": [], /** * Array of indexes for display - no filtering * @type array * @default [] */ "aiDisplayMaster": [], /** * Store information about each column that is in use * @type array * @default [] */ "aoColumns": [], /** * Store information about the table's header * @type array * @default [] */ "aoHeader": [], /** * Store information about the table's footer * @type array * @default [] */ "aoFooter": [], /** * Search data array for regular expression searching * @type array * @default [] */ "asDataSearch": [], /** * Store the applied global search information in case we want to force a * research or compare the old search to a new one. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @namespace * @extends DataTable.models.oSearch */ "oPreviousSearch": {}, /** * Store the applied search for each column - see * {@link DataTable.models.oSearch} for the format that is used for the * filtering information for each column. * @type array * @default [] */ "aoPreSearchCols": [], /** * Sorting that is applied to the table. Note that the inner arrays are * used in the following manner: * <ul> * <li>Index 0 - column number</li> * <li>Index 1 - current sorting direction</li> * <li>Index 2 - index of asSorting for this column</li> * </ul> * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type array * @todo These inner arrays should really be objects */ "aaSorting": null, /** * Sorting that is always applied to the table (i.e. prefixed in front of * aaSorting). * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type array|null * @default null */ "aaSortingFixed": null, /** * Classes to use for the striping of a table. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type array * @default [] */ "asStripeClasses": null, /** * If restoring a table - we should restore its striping classes as well * @type array * @default [] */ "asDestroyStripes": [], /** * If restoring a table - we should restore its width * @type int * @default 0 */ "sDestroyWidth": 0, /** * Callback functions array for every time a row is inserted (i.e. on a draw). * @type array * @default [] */ "aoRowCallback": [], /** * Callback functions for the header on each draw. * @type array * @default [] */ "aoHeaderCallback": [], /** * Callback function for the footer on each draw. * @type array * @default [] */ "aoFooterCallback": [], /** * Array of callback functions for draw callback functions * @type array * @default [] */ "aoDrawCallback": [], /** * Array of callback functions for row created function * @type array * @default [] */ "aoRowCreatedCallback": [], /** * Callback functions for just before the table is redrawn. A return of * false will be used to cancel the draw. * @type array * @default [] */ "aoPreDrawCallback": [], /** * Callback functions for when the table has been initialised. * @type array * @default [] */ "aoInitComplete": [], /** * Callbacks for modifying the settings to be stored for state saving, prior to * saving state. * @type array * @default [] */ "aoStateSaveParams": [], /** * Callbacks for modifying the settings that have been stored for state saving * prior to using the stored values to restore the state. * @type array * @default [] */ "aoStateLoadParams": [], /** * Callbacks for operating on the settings object once the saved state has been * loaded * @type array * @default [] */ "aoStateLoaded": [], /** * Cache the table ID for quick access * @type string * @default <i>Empty string</i> */ "sTableId": "", /** * The TABLE node for the main table * @type node * @default null */ "nTable": null, /** * Permanent ref to the thead element * @type node * @default null */ "nTHead": null, /** * Permanent ref to the tfoot element - if it exists * @type node * @default null */ "nTFoot": null, /** * Permanent ref to the tbody element * @type node * @default null */ "nTBody": null, /** * Cache the wrapper node (contains all DataTables controlled elements) * @type node * @default null */ "nTableWrapper": null, /** * Indicate if when using server-side processing the loading of data * should be deferred until the second draw. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean * @default false */ "bDeferLoading": false, /** * Indicate if all required information has been read in * @type boolean * @default false */ "bInitialised": false, /** * Information about open rows. Each object in the array has the parameters * 'nTr' and 'nParent' * @type array * @default [] */ "aoOpenRows": [], /** * Dictate the positioning of DataTables' control elements - see * {@link DataTable.model.oInit.sDom}. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @default null */ "sDom": null, /** * Which type of pagination should be used. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @default two_button */ "sPaginationType": "two_button", /** * The cookie duration (for bStateSave) in seconds. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type int * @default 0 */ "iCookieDuration": 0, /** * The cookie name prefix. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @default <i>Empty string</i> */ "sCookiePrefix": "", /** * Callback function for cookie creation. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type function * @default null */ "fnCookieCallback": null, /** * Array of callback functions for state saving. Each array element is an * object with the following parameters: * <ul> * <li>function:fn - function to call. Takes two parameters, oSettings * and the JSON string to save that has been thus far created. Returns * a JSON string to be inserted into a json object * (i.e. '"param": [ 0, 1, 2]')</li> * <li>string:sName - name of callback</li> * </ul> * @type array * @default [] */ "aoStateSave": [], /** * Array of callback functions for state loading. Each array element is an * object with the following parameters: * <ul> * <li>function:fn - function to call. Takes two parameters, oSettings * and the object stored. May return false to cancel state loading</li> * <li>string:sName - name of callback</li> * </ul> * @type array * @default [] */ "aoStateLoad": [], /** * State that was loaded from the cookie. Useful for back reference * @type object * @default null */ "oLoadedState": null, /** * Source url for AJAX data for the table. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @default null */ "sAjaxSource": null, /** * Property from a given object from which to read the table data from. This * can be an empty string (when not server-side processing), in which case * it is assumed an an array is given directly. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string */ "sAjaxDataProp": null, /** * Note if draw should be blocked while getting data * @type boolean * @default true */ "bAjaxDataGet": true, /** * The last jQuery XHR object that was used for server-side data gathering. * This can be used for working with the XHR information in one of the * callbacks * @type object * @default null */ "jqXHR": null, /** * Function to get the server-side data. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type function */ "fnServerData": null, /** * Functions which are called prior to sending an Ajax request so extra * parameters can easily be sent to the server * @type array * @default [] */ "aoServerParams": [], /** * Send the XHR HTTP method - GET or POST (could be PUT or DELETE if * required). * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string */ "sServerMethod": null, /** * Format numbers for display. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type function */ "fnFormatNumber": null, /** * List of options that can be used for the user selectable length menu. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type array * @default [] */ "aLengthMenu": null, /** * Counter for the draws that the table does. Also used as a tracker for * server-side processing * @type int * @default 0 */ "iDraw": 0, /** * Indicate if a redraw is being done - useful for Ajax * @type boolean * @default false */ "bDrawing": false, /** * Draw index (iDraw) of the last error when parsing the returned data * @type int * @default -1 */ "iDrawError": -1, /** * Paging display length * @type int * @default 10 */ "_iDisplayLength": 10, /** * Paging start point - aiDisplay index * @type int * @default 0 */ "_iDisplayStart": 0, /** * Paging end point - aiDisplay index. Use fnDisplayEnd rather than * this property to get the end point * @type int * @default 10 * @private */ "_iDisplayEnd": 10, /** * Server-side processing - number of records in the result set * (i.e. before filtering), Use fnRecordsTotal rather than * this property to get the value of the number of records, regardless of * the server-side processing setting. * @type int * @default 0 * @private */ "_iRecordsTotal": 0, /** * Server-side processing - number of records in the current display set * (i.e. after filtering). Use fnRecordsDisplay rather than * this property to get the value of the number of records, regardless of * the server-side processing setting. * @type boolean * @default 0 * @private */ "_iRecordsDisplay": 0, /** * Flag to indicate if jQuery UI marking and classes should be used. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bJUI": null, /** * The classes to use for the table * @type object * @default {} */ "oClasses": {}, /** * Flag attached to the settings object so you can check in the draw * callback if filtering has been done in the draw. Deprecated in favour of * events. * @type boolean * @default false * @deprecated */ "bFiltered": false, /** * Flag attached to the settings object so you can check in the draw * callback if sorting has been done in the draw. Deprecated in favour of * events. * @type boolean * @default false * @deprecated */ "bSorted": false, /** * Indicate that if multiple rows are in the header and there is more than * one unique cell per column, if the top one (true) or bottom one (false) * should be used for sorting / title by DataTables. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bSortCellsTop": null, /** * Initialisation object that is used for the table * @type object * @default null */ "oInit": null, /** * Destroy callback functions - for plug-ins to attach themselves to the * destroy so they can clean up markup and events. * @type array * @default [] */ "aoDestroyCallback": [], /** * Get the number of records in the current record set, before filtering * @type function */ "fnRecordsTotal": function () { if ( this.oFeatures.bServerSide ) { return parseInt(this._iRecordsTotal, 10); } else { return this.aiDisplayMaster.length; } }, /** * Get the number of records in the current record set, after filtering * @type function */ "fnRecordsDisplay": function () { if ( this.oFeatures.bServerSide ) { return parseInt(this._iRecordsDisplay, 10); } else { return this.aiDisplay.length; } }, /** * Set the display end point - aiDisplay index * @type function * @todo Should do away with _iDisplayEnd and calculate it on-the-fly here */ "fnDisplayEnd": function () { if ( this.oFeatures.bServerSide ) { if ( this.oFeatures.bPaginate === false || this._iDisplayLength == -1 ) { return this._iDisplayStart+this.aiDisplay.length; } else { return Math.min( this._iDisplayStart+this._iDisplayLength, this._iRecordsDisplay ); } } else { return this._iDisplayEnd; } }, /** * The DataTables object for this table * @type object * @default null */ "oInstance": null, /** * Unique identifier for each instance of the DataTables object. If there * is an ID on the table node, then it takes that value, otherwise an * incrementing internal counter is used. * @type string * @default null */ "sInstance": null, /** * tabindex attribute value that is added to DataTables control elements, allowing * keyboard navigation of the table and its controls. */ "iTabIndex": 0, /** * DIV container for the footer scrolling table if scrolling */ "nScrollHead": null, /** * DIV container for the footer scrolling table if scrolling */ "nScrollFoot": null }; /** * Extension object for DataTables that is used to provide all extension options. * * Note that the <i>DataTable.ext</i> object is available through * <i>jQuery.fn.dataTable.ext</i> where it may be accessed and manipulated. It is * also aliased to <i>jQuery.fn.dataTableExt</i> for historic reasons. * @namespace * @extends DataTable.models.ext */ DataTable.ext = $.extend( true, {}, DataTable.models.ext ); $.extend( DataTable.ext.oStdClasses, { "sTable": "dataTable", /* Two buttons buttons */ "sPagePrevEnabled": "paginate_enabled_previous", "sPagePrevDisabled": "paginate_disabled_previous", "sPageNextEnabled": "paginate_enabled_next", "sPageNextDisabled": "paginate_disabled_next", "sPageJUINext": "", "sPageJUIPrev": "", /* Full numbers paging buttons */ "sPageButton": "paginate_button", "sPageButtonActive": "paginate_active", "sPageButtonStaticDisabled": "paginate_button paginate_button_disabled", "sPageFirst": "first", "sPagePrevious": "previous", "sPageNext": "next", "sPageLast": "last", /* Striping classes */ "sStripeOdd": "odd", "sStripeEven": "even", /* Empty row */ "sRowEmpty": "dataTables_empty", /* Features */ "sWrapper": "dataTables_wrapper", "sFilter": "dataTables_filter", "sInfo": "dataTables_info", "sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */ "sLength": "dataTables_length", "sProcessing": "dataTables_processing", /* Sorting */ "sSortAsc": "sorting_asc", "sSortDesc": "sorting_desc", "sSortable": "sorting", /* Sortable in both directions */ "sSortableAsc": "sorting_asc_disabled", "sSortableDesc": "sorting_desc_disabled", "sSortableNone": "sorting_disabled", "sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */ "sSortJUIAsc": "", "sSortJUIDesc": "", "sSortJUI": "", "sSortJUIAscAllowed": "", "sSortJUIDescAllowed": "", "sSortJUIWrapper": "", "sSortIcon": "", /* Scrolling */ "sScrollWrapper": "dataTables_scroll", "sScrollHead": "dataTables_scrollHead", "sScrollHeadInner": "dataTables_scrollHeadInner", "sScrollBody": "dataTables_scrollBody", "sScrollFoot": "dataTables_scrollFoot", "sScrollFootInner": "dataTables_scrollFootInner", /* Misc */ "sFooterTH": "", "sJUIHeader": "", "sJUIFooter": "" } ); $.extend( DataTable.ext.oJUIClasses, DataTable.ext.oStdClasses, { /* Two buttons buttons */ "sPagePrevEnabled": "fg-button ui-button ui-state-default ui-corner-left", "sPagePrevDisabled": "fg-button ui-button ui-state-default ui-corner-left ui-state-disabled", "sPageNextEnabled": "fg-button ui-button ui-state-default ui-corner-right", "sPageNextDisabled": "fg-button ui-button ui-state-default ui-corner-right ui-state-disabled", "sPageJUINext": "ui-icon ui-icon-circle-arrow-e", "sPageJUIPrev": "ui-icon ui-icon-circle-arrow-w", /* Full numbers paging buttons */ "sPageButton": "fg-button ui-button ui-state-default", "sPageButtonActive": "fg-button ui-button ui-state-default ui-state-disabled", "sPageButtonStaticDisabled": "fg-button ui-button ui-state-default ui-state-disabled", "sPageFirst": "first ui-corner-tl ui-corner-bl", "sPageLast": "last ui-corner-tr ui-corner-br", /* Features */ "sPaging": "dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi "+ "ui-buttonset-multi paging_", /* Note that the type is postfixed */ /* Sorting */ "sSortAsc": "ui-state-default", "sSortDesc": "ui-state-default", "sSortable": "ui-state-default", "sSortableAsc": "ui-state-default", "sSortableDesc": "ui-state-default", "sSortableNone": "ui-state-default", "sSortJUIAsc": "css_right ui-icon ui-icon-triangle-1-n", "sSortJUIDesc": "css_right ui-icon ui-icon-triangle-1-s", "sSortJUI": "css_right ui-icon ui-icon-carat-2-n-s", "sSortJUIAscAllowed": "css_right ui-icon ui-icon-carat-1-n", "sSortJUIDescAllowed": "css_right ui-icon ui-icon-carat-1-s", "sSortJUIWrapper": "DataTables_sort_wrapper", "sSortIcon": "DataTables_sort_icon", /* Scrolling */ "sScrollHead": "dataTables_scrollHead ui-state-default", "sScrollFoot": "dataTables_scrollFoot ui-state-default", /* Misc */ "sFooterTH": "ui-state-default", "sJUIHeader": "fg-toolbar ui-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix", "sJUIFooter": "fg-toolbar ui-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix" } ); /* * Variable: oPagination * Purpose: * Scope: jQuery.fn.dataTableExt */ $.extend( DataTable.ext.oPagination, { /* * Variable: two_button * Purpose: Standard two button (forward/back) pagination * Scope: jQuery.fn.dataTableExt.oPagination */ "two_button": { /* * Function: oPagination.two_button.fnInit * Purpose: Initialise dom elements required for pagination with forward/back buttons only * Returns: - * Inputs: object:oSettings - dataTables settings object * node:nPaging - the DIV which contains this pagination control * function:fnCallbackDraw - draw function which must be called on update */ "fnInit": function ( oSettings, nPaging, fnCallbackDraw ) { var oLang = oSettings.oLanguage.oPaginate; var oClasses = oSettings.oClasses; var fnClickHandler = function ( e ) { if ( oSettings.oApi._fnPageChange( oSettings, e.data.action ) ) { fnCallbackDraw( oSettings ); } }; var sAppend = (!oSettings.bJUI) ? '<a class="'+oSettings.oClasses.sPagePrevDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button">'+oLang.sPrevious+'</a>'+ '<a class="'+oSettings.oClasses.sPageNextDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button">'+oLang.sNext+'</a>' : '<a class="'+oSettings.oClasses.sPagePrevDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button"><span class="'+oSettings.oClasses.sPageJUIPrev+'"></span></a>'+ '<a class="'+oSettings.oClasses.sPageNextDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button"><span class="'+oSettings.oClasses.sPageJUINext+'"></span></a>'; $(nPaging).append( sAppend ); var els = $('a', nPaging); var nPrevious = els[0], nNext = els[1]; oSettings.oApi._fnBindAction( nPrevious, {action: "previous"}, fnClickHandler ); oSettings.oApi._fnBindAction( nNext, {action: "next"}, fnClickHandler ); /* ID the first elements only */ if ( !oSettings.aanFeatures.p ) { nPaging.id = oSettings.sTableId+'_paginate'; nPrevious.id = oSettings.sTableId+'_previous'; nNext.id = oSettings.sTableId+'_next'; nPrevious.setAttribute('aria-controls', oSettings.sTableId); nNext.setAttribute('aria-controls', oSettings.sTableId); } }, /* * Function: oPagination.two_button.fnUpdate * Purpose: Update the two button pagination at the end of the draw * Returns: - * Inputs: object:oSettings - dataTables settings object * function:fnCallbackDraw - draw function to call on page change */ "fnUpdate": function ( oSettings, fnCallbackDraw ) { if ( !oSettings.aanFeatures.p ) { return; } var oClasses = oSettings.oClasses; var an = oSettings.aanFeatures.p; var nNode; /* Loop over each instance of the pager */ for ( var i=0, iLen=an.length ; i<iLen ; i++ ) { nNode = an[i].firstChild; if ( nNode ) { /* Previous page */ nNode.className = ( oSettings._iDisplayStart === 0 ) ? oClasses.sPagePrevDisabled : oClasses.sPagePrevEnabled; /* Next page */ nNode = nNode.nextSibling; nNode.className = ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() ) ? oClasses.sPageNextDisabled : oClasses.sPageNextEnabled; } } } }, /* * Variable: iFullNumbersShowPages * Purpose: Change the number of pages which can be seen * Scope: jQuery.fn.dataTableExt.oPagination */ "iFullNumbersShowPages": 5, /* * Variable: full_numbers * Purpose: Full numbers pagination * Scope: jQuery.fn.dataTableExt.oPagination */ "full_numbers": { /* * Function: oPagination.full_numbers.fnInit * Purpose: Initialise dom elements required for pagination with a list of the pages * Returns: - * Inputs: object:oSettings - dataTables settings object * node:nPaging - the DIV which contains this pagination control * function:fnCallbackDraw - draw function which must be called on update */ "fnInit": function ( oSettings, nPaging, fnCallbackDraw ) { var oLang = oSettings.oLanguage.oPaginate; var oClasses = oSettings.oClasses; var fnClickHandler = function ( e ) { if ( oSettings.oApi._fnPageChange( oSettings, e.data.action ) ) { fnCallbackDraw( oSettings ); } }; $(nPaging).append( '<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageFirst+'">'+oLang.sFirst+'</a>'+ '<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPagePrevious+'">'+oLang.sPrevious+'</a>'+ '<span></span>'+ '<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageNext+'">'+oLang.sNext+'</a>'+ '<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageLast+'">'+oLang.sLast+'</a>' ); var els = $('a', nPaging); var nFirst = els[0], nPrev = els[1], nNext = els[2], nLast = els[3]; oSettings.oApi._fnBindAction( nFirst, {action: "first"}, fnClickHandler ); oSettings.oApi._fnBindAction( nPrev, {action: "previous"}, fnClickHandler ); oSettings.oApi._fnBindAction( nNext, {action: "next"}, fnClickHandler ); oSettings.oApi._fnBindAction( nLast, {action: "last"}, fnClickHandler ); /* ID the first elements only */ if ( !oSettings.aanFeatures.p ) { nPaging.id = oSettings.sTableId+'_paginate'; nFirst.id =oSettings.sTableId+'_first'; nPrev.id =oSettings.sTableId+'_previous'; nNext.id =oSettings.sTableId+'_next'; nLast.id =oSettings.sTableId+'_last'; } }, /* * Function: oPagination.full_numbers.fnUpdate * Purpose: Update the list of page buttons shows * Returns: - * Inputs: object:oSettings - dataTables settings object * function:fnCallbackDraw - draw function to call on page change */ "fnUpdate": function ( oSettings, fnCallbackDraw ) { if ( !oSettings.aanFeatures.p ) { return; } var iPageCount = DataTable.ext.oPagination.iFullNumbersShowPages; var iPageCountHalf = Math.floor(iPageCount / 2); var iPages = Math.ceil((oSettings.fnRecordsDisplay()) / oSettings._iDisplayLength); var iCurrentPage = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1; var sList = ""; var iStartButton, iEndButton, i, iLen; var oClasses = oSettings.oClasses; var anButtons, anStatic, nPaginateList, nNode; var an = oSettings.aanFeatures.p; var fnBind = function (j) { oSettings.oApi._fnBindAction( this, {"page": j+iStartButton-1}, function(e) { /* Use the information in the element to jump to the required page */ oSettings.oApi._fnPageChange( oSettings, e.data.page ); fnCallbackDraw( oSettings ); e.preventDefault(); } ); }; /* Pages calculation */ if ( oSettings._iDisplayLength === -1 ) { iStartButton = 1; iEndButton = 1; iCurrentPage = 1; } else if (iPages < iPageCount) { iStartButton = 1; iEndButton = iPages; } else if (iCurrentPage <= iPageCountHalf) { iStartButton = 1; iEndButton = iPageCount; } else if (iCurrentPage >= (iPages - iPageCountHalf)) { iStartButton = iPages - iPageCount + 1; iEndButton = iPages; } else { iStartButton = iCurrentPage - Math.ceil(iPageCount / 2) + 1; iEndButton = iStartButton + iPageCount - 1; } /* Build the dynamic list */ for ( i=iStartButton ; i<=iEndButton ; i++ ) { sList += (iCurrentPage !== i) ? '<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+'">'+oSettings.fnFormatNumber(i)+'</a>' : '<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButtonActive+'">'+oSettings.fnFormatNumber(i)+'</a>'; } /* Loop over each instance of the pager */ for ( i=0, iLen=an.length ; i<iLen ; i++ ) { nNode = an[i]; if ( !nNode.hasChildNodes() ) { continue; } /* Build up the dynamic list first - html and listeners */ $('span:eq(0)', nNode) .html( sList ) .children('a').each( fnBind ); /* Update the permanent button's classes */ anButtons = nNode.getElementsByTagName('a'); anStatic = [ anButtons[0], anButtons[1], anButtons[anButtons.length-2], anButtons[anButtons.length-1] ]; $(anStatic).removeClass( oClasses.sPageButton+" "+oClasses.sPageButtonActive+" "+oClasses.sPageButtonStaticDisabled ); $([anStatic[0], anStatic[1]]).addClass( (iCurrentPage==1) ? oClasses.sPageButtonStaticDisabled : oClasses.sPageButton ); $([anStatic[2], anStatic[3]]).addClass( (iPages===0 || iCurrentPage===iPages || oSettings._iDisplayLength===-1) ? oClasses.sPageButtonStaticDisabled : oClasses.sPageButton ); } } } } ); $.extend( DataTable.ext.oSort, { /* * text sorting */ "string-pre": function ( a ) { if ( typeof a != 'string' ) { a = (a !== null && a.toString) ? a.toString() : ''; } return a.toLowerCase(); }, "string-asc": function ( x, y ) { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }, "string-desc": function ( x, y ) { return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }, /* * html sorting (ignore html tags) */ "html-pre": function ( a ) { return a.replace( /<.*?>/g, "" ).toLowerCase(); }, "html-asc": function ( x, y ) { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }, "html-desc": function ( x, y ) { return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }, /* * date sorting */ "date-pre": function ( a ) { var x = Date.parse( a ); if ( isNaN(x) || x==="" ) { x = Date.parse( "01/01/1970 00:00:00" ); } return x; }, "date-asc": function ( x, y ) { return x - y; }, "date-desc": function ( x, y ) { return y - x; }, /* * numerical sorting */ "numeric-pre": function ( a ) { return (a=="-" || a==="") ? 0 : a*1; }, "numeric-asc": function ( x, y ) { return x - y; }, "numeric-desc": function ( x, y ) { return y - x; } } ); $.extend( DataTable.ext.aTypes, [ /* * Function: - * Purpose: Check to see if a string is numeric * Returns: string:'numeric' or null * Inputs: mixed:sText - string to check */ function ( sData ) { /* Allow zero length strings as a number */ if ( typeof sData === 'number' ) { return 'numeric'; } else if ( typeof sData !== 'string' ) { return null; } var sValidFirstChars = "0123456789-"; var sValidChars = "0123456789."; var Char; var bDecimal = false; /* Check for a valid first char (no period and allow negatives) */ Char = sData.charAt(0); if (sValidFirstChars.indexOf(Char) == -1) { return null; } /* Check all the other characters are valid */ for ( var i=1 ; i<sData.length ; i++ ) { Char = sData.charAt(i); if (sValidChars.indexOf(Char) == -1) { return null; } /* Only allowed one decimal place... */ if ( Char == "." ) { if ( bDecimal ) { return null; } bDecimal = true; } } return 'numeric'; }, /* * Function: - * Purpose: Check to see if a string is actually a formatted date * Returns: string:'date' or null * Inputs: string:sText - string to check */ function ( sData ) { var iParse = Date.parse(sData); if ( (iParse !== null && !isNaN(iParse)) || (typeof sData === 'string' && sData.length === 0) ) { return 'date'; } return null; }, /* * Function: - * Purpose: Check to see if a string should be treated as an HTML string * Returns: string:'html' or null * Inputs: string:sText - string to check */ function ( sData ) { if ( typeof sData === 'string' && sData.indexOf('<') != -1 && sData.indexOf('>') != -1 ) { return 'html'; } return null; } ] ); // jQuery aliases $.fn.DataTable = DataTable; $.fn.dataTable = DataTable; $.fn.dataTableSettings = DataTable.settings; $.fn.dataTableExt = DataTable.ext; // Information about events fired by DataTables - for documentation. /** * Draw event, fired whenever the table is redrawn on the page, at the same point as * fnDrawCallback. This may be useful for binding events or performing calculations when * the table is altered at all. * @name DataTable#draw * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Filter event, fired when the filtering applied to the table (using the build in global * global filter, or column filters) is altered. * @name DataTable#filter * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Page change event, fired when the paging of the table is altered. * @name DataTable#page * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Sort event, fired when the sorting applied to the table is altered. * @name DataTable#sort * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * DataTables initialisation complete event, fired when the table is fully drawn, * including Ajax data loaded, if Ajax data is required. * @name DataTable#init * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {object} json The JSON object request from the server - only * present if client-side Ajax sourced data is used</li></ol> */ /** * State save event, fired when the table has changed state a new state save is required. * This method allows modification of the state saving object prior to actually doing the * save, including addition or other state properties (for plug-ins) or modification * of a DataTables core property. * @name DataTable#stateSaveParams * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {object} json The state information to be saved */ /** * State load event, fired when the table is loading state from the stored data, but * prior to the settings object being modified by the saved state - allowing modification * of the saved state is required or loading of state for a plug-in. * @name DataTable#stateLoadParams * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {object} json The saved state information */ /** * State loaded event, fired when state has been loaded from stored data and the settings * object has been modified by the loaded data. * @name DataTable#stateLoaded * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {object} json The saved state information */ /** * Processing event, fired when DataTables is doing some kind of processing (be it, * sort, filter or anything else). Can be used to indicate to the end user that * there is something happening, or that something has finished. * @name DataTable#processing * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {boolean} bShow Flag for if DataTables is doing processing or not */ /** * Ajax (XHR) event, fired whenever an Ajax request is completed from a request to * made to the server for new data (note that this trigger is called in fnServerData, * if you override fnServerData and which to use this event, you need to trigger it in * you success function). * @name DataTable#xhr * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} * @param {object} json JSON returned from the server */ /** * Destroy event, fired when the DataTable is destroyed by calling fnDestroy or passing * the bDestroy:true parameter in the initialisation object. This can be used to remove * bound events, added DOM nodes, etc. * @name DataTable#destroy * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ })); }(window, document));
JavaScript
/* ========================================================== * bootpanorama-panorama.js v1.0 * http://aozora.github.com/bootpanorama/ * ========================================================== * Copyright 2012 Marcello Palmitessa * * 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. * ========================================================== */ !function ($) { "use strict"; /* PIVOT CLASS DEFINITION * ========================= */ var Panorama = function (element, options) { this.$element = $(element) this.options = options // this.options.slide && this.slide(this.options.slide) this.$groups = $('.panorama-sections .panorama-section') this.$current = 0 this.init() } Panorama.prototype = { // init panorama workspace init: function(){ var $this = this // arrange the panorama height this.$element.height( this.$element.parent().height() - $('#nav-bar').outerHeight() ) // arrange the section container width $this.resize(); // setup mousewheel // win8: wheel-down => scroll to right -1 0 -1 // wheel-up => scroll to left 1 0 1 if (this.options.mousewheel){ $('.panorama-sections').mousewheel(function(event, delta, deltaX, deltaY) { //e.preventDefault(); //console.log(delta, deltaX, deltaY); if (delta > 0){ $this.prev() } else{ $this.next() } }); } // Arrange Tiles like Win8 ones if (this.options.arrangetiles){ $('.panorama-sections .panorama-section').each(function(index, el){ }); } // parallax can be activated only if there is CSS3 transition support if (this.options.parallax){ // add a class to enable css3 transition $('body').addClass("panorama-parallax"); } if (this.options.showscrollbuttons){ var $p = $('.panorama-sections'); $('#panorama-scroll-prev').click(function(e){ e.preventDefault(); $this.prev() }); $("#panorama-scroll-next").click(function(e){ e.preventDefault(); $this.next() }); } else { $('#panorama-scroll-prev').hide() $('#panorama-scroll-next').hide() } //Enable swiping... $(".panorama").swipe( { //Generic swipe handler for all directions swipe:function(event, direction, distance, duration, fingerCount) { if (direction=='right'){ $this.prev() } if (direction=='left'){ $this.next() } } ,threshold: 0 //ingers: 'all' }); $this.setButtons() if (this.options.keyboard){ $(document).on('keyup', function ( e ) { if (e.which == 37) { // left-arrow $this.prev() } if (e.which == 39) { // right-arrow $this.next() } }) } // $(window).resize(function() { // // // call resize function // // }); } // end init , next: function () { var $this = this this.$current++ if (this.$current >= this.$groups.length){ this.$current = this.$groups.length - 1 } var $p = $('.panorama-sections'); var targetOffset = $(this.$groups[this.$current]).position().left if (this.options.parallax && $.support.transition){ $('body').css('background-position', (targetOffset / 2) + 'px 0px') } $p.animate({ marginLeft: -targetOffset }, { duration: 200, easing: 'swing' ,complete: function(){$this.setButtons()} } ); } , prev: function () { var $this = this this.$current-- if (this.$current < 0){ this.$current = 0 } var $p = $('.panorama-sections'); var targetOffset = $(this.$groups[this.$current]).position().left if (this.options.parallax && $.support.transition){ $('body').css('background-position', (targetOffset / 2) + 'px 0px') } $p.animate({ marginLeft: -targetOffset }, { duration: 200, easing: 'swing' ,complete: function(){$this.setButtons()} } ); } , resize: function(){ // arrange the section container width var totalWidth = 0 $('.panorama-sections .panorama-section').each(function(index, el){ totalWidth += $(el).outerWidth(true) }); $('.panorama-sections') .width(totalWidth) .height( this.$element.parent().height()) } , setButtons: function () { if (!this.options.showscrollbuttons){ return false; } if (this.$current === 0){ $("#panorama-scroll-prev").hide(); } else { $("#panorama-scroll-prev").show(); } if (this.$current === this.$groups.length - 1){ $("#panorama-scroll-next").hide(); } else { $("#panorama-scroll-next").show(); } } } /* PANORAMA PLUGIN DEFINITION * ========================== */ $.fn.panorama = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('panorama') , options = $.extend({}, $.fn.panorama.defaults, typeof option == 'object' && option) , action = typeof option == 'string' ? option : options.slide if (!data) { $this.data('panorama', (data = new Panorama(this, options))) } // if (typeof option == 'number') data.to(option) else if (action){ data[action]() } }) } $.fn.panorama.defaults = { showscrollbuttons: true, parallax: false, keyboard: true, mousewheel: true, arrangetiles: true } $.fn.panorama.Constructor = Panorama }(window.jQuery);
JavaScript
$(function() { $('#username').focus(); $('input').keyup(function(e) { $(this).removeClass('errorfield'); var code = e.keyCode || e.which; if(code==13) { loggingin(); } }); $('#do_login').click(function() { loggingin(); }); }); function loggingin() { var uname = $('#username').val(); var passwd = $('#password').val(); var passprocess = true; if(uname=='') { passprocess = false; $('#username').focus().addClass('errorfield').delay(3000).queue(function(next){ $(this).removeClass("errorfield"); next(); }); } if(passwd=='') { passprocess = false; $('#password').focus().addClass('errorfield').delay(3000).queue(function(next){ $(this).removeClass("errorfield"); next(); }); } if(passprocess) { $.ajax({ type : 'post', url : base_url+'auth/login/', data : 'username='+uname+'&password='+passwd, cache : false, success: function(datas) { if(datas==0) { $('#password').val('').focus(); $('#username, #password').addClass('errorfield').delay(3000).queue(function(next){ $(this).removeClass("errorfield"); next(); }); } else { window.location.reload(); } } }); } }
JavaScript
/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.1.3 * * Requires: 1.2.2+ */ (function (factory) { if ( typeof define === 'function' && define.amd ) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object') { // Node/CommonJS style for Browserify module.exports = factory; } else { // Browser globals factory(jQuery); } }(function ($) { var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll']; var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll']; var lowestDelta, lowestDeltaXY; if ( $.event.fixHooks ) { for ( var i = toFix.length; i; ) { $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; } } $.event.special.mousewheel = { setup: function() { if ( this.addEventListener ) { for ( var i = toBind.length; i; ) { this.addEventListener( toBind[--i], handler, false ); } } else { this.onmousewheel = handler; } }, teardown: function() { if ( this.removeEventListener ) { for ( var i = toBind.length; i; ) { this.removeEventListener( toBind[--i], handler, false ); } } else { this.onmousewheel = null; } } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, unmousewheel: function(fn) { return this.unbind("mousewheel", fn); } }); function handler(event) { var orgEvent = event || window.event, args = [].slice.call(arguments, 1), delta = 0, deltaX = 0, deltaY = 0, absDelta = 0, absDeltaXY = 0, fn; event = $.event.fix(orgEvent); event.type = "mousewheel"; // Old school scrollwheel delta if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; } if ( orgEvent.detail ) { delta = orgEvent.detail * -1; } // New school wheel delta (wheel event) if ( orgEvent.deltaY ) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } if ( orgEvent.deltaX ) { deltaX = orgEvent.deltaX; delta = deltaX * -1; } // Webkit if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; } if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; } // Look for lowest delta to normalize the delta values absDelta = Math.abs(delta); if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; } absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX)); if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; } // Get a whole value for the deltas fn = delta > 0 ? 'floor' : 'ceil'; delta = Math[fn](delta / lowestDelta); deltaX = Math[fn](deltaX / lowestDeltaXY); deltaY = Math[fn](deltaY / lowestDeltaXY); // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); return ($.event.dispatch || $.event.handle).apply(this, args); } }));
JavaScript
/* * * Copyright (c) 2006-2011 Sam Collett (http://www.texotela.co.uk) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * Version 1.3.1 * Demo: http://www.texotela.co.uk/code/jquery/numeric/ * */ (function($) { /* * Allows only valid characters to be entered into input boxes. * Note: fixes value when pasting via Ctrl+V, but not when using the mouse to paste * side-effect: Ctrl+A does not work, though you can still use the mouse to select (or double-click to select all) * * @name numeric * @param config { decimal : "." , negative : true } * @param callback A function that runs if the number is not valid (fires onblur) * @author Sam Collett (http://www.texotela.co.uk) * @example $(".numeric").numeric(); * @example $(".numeric").numeric(","); // use , as separator * @example $(".numeric").numeric({ decimal : "," }); // use , as separator * @example $(".numeric").numeric({ negative : false }); // do not allow negative values * @example $(".numeric").numeric(null, callback); // use default values, pass on the 'callback' function * */ $.fn.numeric = function(config, callback) { if(typeof config === 'boolean') { config = { decimal: config }; } config = config || {}; // if config.negative undefined, set to true (default is to allow negative numbers) if(typeof config.negative == "undefined") { config.negative = true; } // set decimal point var decimal = (config.decimal === false) ? "" : config.decimal || "."; // allow negatives var negative = (config.negative === true) ? true : false; // callback function callback = (typeof(callback) == "function" ? callback : function() {}); // set data and methods return this.data("numeric.decimal", decimal).data("numeric.negative", negative).data("numeric.callback", callback).keypress($.fn.numeric.keypress).keyup($.fn.numeric.keyup).blur($.fn.numeric.blur); }; $.fn.numeric.keypress = function(e) { // get decimal character and determine if negatives are allowed var decimal = $.data(this, "numeric.decimal"); var negative = $.data(this, "numeric.negative"); // get the key that was pressed var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; // allow enter/return key (only when in an input box) if(key == 13 && this.nodeName.toLowerCase() == "input") { return true; } else if(key == 13) { return false; } var allow = false; // allow Ctrl+A if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) { return true; } // allow Ctrl+X (cut) if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) { return true; } // allow Ctrl+C (copy) if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) { return true; } // allow Ctrl+Z (undo) if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) { return true; } // allow or deny Ctrl+V (paste), Shift+Ins if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */ || (e.shiftKey && key == 45)) { return true; } // if a number was not pressed if(key < 48 || key > 57) { var value = $(this).val(); /* '-' only allowed at start and if negative numbers allowed */ if(value.indexOf("-") !== 0 && negative && key == 45 && (value.length === 0 || parseInt($.fn.getSelectionStart(this), 10) === 0)) { return true; } /* only one decimal separator allowed */ if(decimal && key == decimal.charCodeAt(0) && value.indexOf(decimal) != -1) { allow = false; } // check for other keys that have special purposes if( key != 8 /* backspace */ && key != 9 /* tab */ && key != 13 /* enter */ && key != 35 /* end */ && key != 36 /* home */ && key != 37 /* left */ && key != 39 /* right */ && key != 46 /* del */ ) { allow = false; } else { // for detecting special keys (listed above) // IE does not support 'charCode' and ignores them in keypress anyway if(typeof e.charCode != "undefined") { // special keys have 'keyCode' and 'which' the same (e.g. backspace) if(e.keyCode == e.which && e.which !== 0) { allow = true; // . and delete share the same code, don't allow . (will be set to true later if it is the decimal point) if(e.which == 46) { allow = false; } } // or keyCode != 0 and 'charCode'/'which' = 0 else if(e.keyCode !== 0 && e.charCode === 0 && e.which === 0) { allow = true; } } } // if key pressed is the decimal and it is not already in the field if(decimal && key == decimal.charCodeAt(0)) { if(value.indexOf(decimal) == -1) { allow = true; } else { allow = false; } } } else { allow = true; } return allow; }; $.fn.numeric.keyup = function(e) { var val = $(this).val(); if(val && val.length > 0) { // get carat (cursor) position var carat = $.fn.getSelectionStart(this); var selectionEnd = $.fn.getSelectionEnd(this); // get decimal character and determine if negatives are allowed var decimal = $.data(this, "numeric.decimal"); var negative = $.data(this, "numeric.negative"); // prepend a 0 if necessary if(decimal !== "" && decimal !== null) { // find decimal point var dot = val.indexOf(decimal); // if dot at start, add 0 before if(dot === 0) { this.value = "0" + val; } // if dot at position 1, check if there is a - symbol before it if(dot == 1 && val.charAt(0) == "-") { this.value = "-0" + val.substring(1); } val = this.value; } // if pasted in, only allow the following characters var validChars = [0,1,2,3,4,5,6,7,8,9,'-',decimal]; // get length of the value (to loop through) var length = val.length; // loop backwards (to prevent going out of bounds) for(var i = length - 1; i >= 0; i--) { var ch = val.charAt(i); // remove '-' if it is in the wrong place if(i !== 0 && ch == "-") { val = val.substring(0, i) + val.substring(i + 1); } // remove character if it is at the start, a '-' and negatives aren't allowed else if(i === 0 && !negative && ch == "-") { val = val.substring(1); } var validChar = false; // loop through validChars for(var j = 0; j < validChars.length; j++) { // if it is valid, break out the loop if(ch == validChars[j]) { validChar = true; break; } } // if not a valid character, or a space, remove if(!validChar || ch == " ") { val = val.substring(0, i) + val.substring(i + 1); } } // remove extra decimal characters var firstDecimal = val.indexOf(decimal); if(firstDecimal > 0) { for(var k = length - 1; k > firstDecimal; k--) { var chch = val.charAt(k); // remove decimal character if(chch == decimal) { val = val.substring(0, k) + val.substring(k + 1); } } } // set the value and prevent the cursor moving to the end this.value = val; $.fn.setSelection(this, [carat, selectionEnd]); } }; $.fn.numeric.blur = function() { var decimal = $.data(this, "numeric.decimal"); var callback = $.data(this, "numeric.callback"); var val = this.value; if(val !== "") { var re = new RegExp("^\\d+$|^\\d*" + decimal + "\\d+$"); if(!re.exec(val)) { callback.apply(this); } } }; $.fn.removeNumeric = function() { return this.data("numeric.decimal", null).data("numeric.negative", null).data("numeric.callback", null).unbind("keypress", $.fn.numeric.keypress).unbind("blur", $.fn.numeric.blur); }; // Based on code from http://javascript.nwbox.com/cursor_position/ (Diego Perini <dperini@nwbox.com>) $.fn.getSelectionStart = function(o) { if (o.createTextRange) { var r = document.selection.createRange().duplicate(); r.moveEnd('character', o.value.length); if (r.text === '') { return o.value.length; } return o.value.lastIndexOf(r.text); } else { return o.selectionStart; } }; // Based on code from http://javascript.nwbox.com/cursor_position/ (Diego Perini <dperini@nwbox.com>) $.fn.getSelectionEnd = function(o) { if (o.createTextRange) { var r = document.selection.createRange().duplicate() r.moveStart('character', -o.value.length) return r.text.length } else return o.selectionEnd } // set the selection, o is the object (input), p is the position ([start, end] or just start) $.fn.setSelection = function(o, p) { // if p is number, start and end are the same if(typeof p == "number") { p = [p, p]; } // only set if p is an array of length 2 if(p && p.constructor == Array && p.length == 2) { if (o.createTextRange) { var r = o.createTextRange(); r.collapse(true); r.moveStart('character', p[0]); r.moveEnd('character', p[1]); r.select(); } else if(o.setSelectionRange) { o.focus(); o.setSelectionRange(p[0], p[1]); } } }; })(jQuery);
JavaScript
/** * @name InfoBox * @version 1.1.9 [October 2, 2011] * @author Gary Little (inspired by proof-of-concept code from Pamela Fox of Google) * @copyright Copyright 2010 Gary Little [gary at luxcentral.com] * @fileoverview InfoBox extends the Google Maps JavaScript API V3 <tt>OverlayView</tt> class. * <p> * An InfoBox behaves like a <tt>google.maps.InfoWindow</tt>, but it supports several * additional properties for advanced styling. An InfoBox can also be used as a map label. * <p> * An InfoBox also fires the same events as a <tt>google.maps.InfoWindow</tt>. * <p> * Browsers tested: * <p> * Mac -- Safari (4.0.4), Firefox (3.6), Opera (10.10), Chrome (4.0.249.43), OmniWeb (5.10.1) * <br> * Win -- Safari, Firefox, Opera, Chrome (3.0.195.38), Internet Explorer (8.0.6001.18702) * <br> * iPod Touch/iPhone -- Safari (3.1.2) */ /*! * * 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. */ /*jslint browser:true */ /*global google */ /** * @name InfoBoxOptions * @class This class represents the optional parameter passed to the {@link InfoBox} constructor. * @property {string|Node} content The content of the InfoBox (plain text or an HTML DOM node). * @property {boolean} disableAutoPan Disable auto-pan on <tt>open</tt> (default is <tt>false</tt>). * @property {number} maxWidth The maximum width (in pixels) of the InfoBox. Set to 0 if no maximum. * @property {Size} pixelOffset The offset (in pixels) from the top left corner of the InfoBox * (or the bottom left corner if the <code>alignBottom</code> property is <code>true</code>) * to the map pixel corresponding to <tt>position</tt>. * @property {LatLng} position The geographic location at which to display the InfoBox. * @property {number} zIndex The CSS z-index style value for the InfoBox. * Note: This value overrides a zIndex setting specified in the <tt>boxStyle</tt> property. * @property {string} boxClass The name of the CSS class defining the styles for the InfoBox container. * The default name is <code>infoBox</code>. * @property {Object} [boxStyle] An object literal whose properties define specific CSS * style values to be applied to the InfoBox. Style values defined here override those that may * be defined in the <code>boxClass</code> style sheet. If this property is changed after the * InfoBox has been created, all previously set styles (except those defined in the style sheet) * are removed from the InfoBox before the new style values are applied. * @property {string} closeBoxMargin The CSS margin style value for the close box. * The default is "2px" (a 2-pixel margin on all sides). * @property {string} closeBoxURL The URL of the image representing the close box. * Note: The default is the URL for Google's standard close box. * Set this property to "" if no close box is required. * @property {Size} infoBoxClearance Minimum offset (in pixels) from the InfoBox to the * map edge after an auto-pan. * @property {boolean} isHidden Hide the InfoBox on <tt>open</tt> (default is <tt>false</tt>). * @property {boolean} alignBottom Align the bottom left corner of the InfoBox to the <code>position</code> * location (default is <tt>false</tt> which means that the top left corner of the InfoBox is aligned). * @property {string} pane The pane where the InfoBox is to appear (default is "floatPane"). * Set the pane to "mapPane" if the InfoBox is being used as a map label. * Valid pane names are the property names for the <tt>google.maps.MapPanes</tt> object. * @property {boolean} enableEventPropagation Propagate mousedown, click, dblclick, * and contextmenu events in the InfoBox (default is <tt>false</tt> to mimic the behavior * of a <tt>google.maps.InfoWindow</tt>). Set this property to <tt>true</tt> if the InfoBox * is being used as a map label. iPhone note: This property setting has no effect; events are * always propagated. */ /** * Creates an InfoBox with the options specified in {@link InfoBoxOptions}. * Call <tt>InfoBox.open</tt> to add the box to the map. * @constructor * @param {InfoBoxOptions} [opt_opts] */ function InfoBox(opt_opts) { opt_opts = opt_opts || {}; google.maps.OverlayView.apply(this, arguments); // Standard options (in common with google.maps.InfoWindow): // this.content_ = opt_opts.content || ""; this.disableAutoPan_ = opt_opts.disableAutoPan || false; this.maxWidth_ = opt_opts.maxWidth || 0; this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0); this.position_ = opt_opts.position || new google.maps.LatLng(0, 0); this.zIndex_ = opt_opts.zIndex || null; // Additional options (unique to InfoBox): // this.boxClass_ = opt_opts.boxClass || "infoBox"; this.boxStyle_ = opt_opts.boxStyle || {}; this.closeBoxMargin_ = opt_opts.closeBoxMargin || "2px"; this.closeBoxURL_ = opt_opts.closeBoxURL || "http://www.google.com/intl/en_us/mapfiles/close.gif"; if (opt_opts.closeBoxURL === "") { this.closeBoxURL_ = ""; } this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1); this.isHidden_ = opt_opts.isHidden || false; this.alignBottom_ = opt_opts.alignBottom || false; this.pane_ = opt_opts.pane || "floatPane"; this.enableEventPropagation_ = opt_opts.enableEventPropagation || false; this.div_ = null; this.closeListener_ = null; this.eventListener1_ = null; this.eventListener2_ = null; this.eventListener3_ = null; this.moveListener_ = null; this.contextListener_ = null; this.fixedWidthSet_ = null; } /* InfoBox extends OverlayView in the Google Maps API v3. */ InfoBox.prototype = new google.maps.OverlayView(); /** * Creates the DIV representing the InfoBox. * @private */ InfoBox.prototype.createInfoBoxDiv_ = function () { var bw; var me = this; // This handler prevents an event in the InfoBox from being passed on to the map. // var cancelHandler = function (e) { e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; // This handler ignores the current event in the InfoBox and conditionally prevents // the event from being passed on to the map. It is used for the contextmenu event. // var ignoreHandler = function (e) { e.returnValue = false; if (e.preventDefault) { e.preventDefault(); } if (!me.enableEventPropagation_) { cancelHandler(e); } }; if (!this.div_) { this.div_ = document.createElement("div"); this.setBoxStyle_(); if (typeof this.content_.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + this.content_; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(this.content_); } // Add the InfoBox DIV to the DOM this.getPanes()[this.pane_].appendChild(this.div_); this.addClickHandler_(); if (this.div_.style.width) { this.fixedWidthSet_ = true; } else { if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) { this.div_.style.width = this.maxWidth_; this.div_.style.overflow = "auto"; this.fixedWidthSet_ = true; } else { // The following code is needed to overcome problems with MSIE bw = this.getBoxWidths_(); this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px"; this.fixedWidthSet_ = false; } } this.panBox_(this.disableAutoPan_); if (!this.enableEventPropagation_) { // Cancel event propagation. // this.eventListener1_ = google.maps.event.addDomListener(this.div_, "mousedown", cancelHandler); this.eventListener2_ = google.maps.event.addDomListener(this.div_, "click", cancelHandler); this.eventListener3_ = google.maps.event.addDomListener(this.div_, "dblclick", cancelHandler); this.eventListener4_ = google.maps.event.addDomListener(this.div_, "mouseover", function (e) { this.style.cursor = "default"; }); } this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler); /** * This event is fired when the DIV containing the InfoBox's content is attached to the DOM. * @name InfoBox#domready * @event */ google.maps.event.trigger(this, "domready"); } }; /** * Returns the HTML <IMG> tag for the close box. * @private */ InfoBox.prototype.getCloseBoxImg_ = function () { var img = ""; if (this.closeBoxURL_ !== "") { img = "<img"; img += " src='" + this.closeBoxURL_ + "'"; img += " align=right"; // Do this because Opera chokes on style='float: right;' img += " style='"; img += " position: relative;"; // Required by MSIE img += " cursor: pointer;"; img += " margin: " + this.closeBoxMargin_ + ";"; img += "'>"; } return img; }; /** * Adds the click handler to the InfoBox close box. * @private */ InfoBox.prototype.addClickHandler_ = function () { var closeBox; if (this.closeBoxURL_ !== "") { closeBox = this.div_.firstChild; this.closeListener_ = google.maps.event.addDomListener(closeBox, 'click', this.getCloseClickHandler_()); } else { this.closeListener_ = null; } }; /** * Returns the function to call when the user clicks the close box of an InfoBox. * @private */ InfoBox.prototype.getCloseClickHandler_ = function () { var me = this; return function (e) { // 1.0.3 fix: Always prevent propagation of a close box click to the map: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } me.close(); /** * This event is fired when the InfoBox's close box is clicked. * @name InfoBox#closeclick * @event */ google.maps.event.trigger(me, "closeclick"); }; }; /** * Pans the map so that the InfoBox appears entirely within the map's visible area. * @private */ InfoBox.prototype.panBox_ = function (disablePan) { var map; var bounds; var xOffset = 0, yOffset = 0; if (!disablePan) { map = this.getMap(); if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama if (!map.getBounds().contains(this.position_)) { // Marker not in visible area of map, so set center // of map to the marker position first. map.setCenter(this.position_); } bounds = map.getBounds(); var mapDiv = map.getDiv(); var mapWidth = mapDiv.offsetWidth; var mapHeight = mapDiv.offsetHeight; var iwOffsetX = this.pixelOffset_.width; var iwOffsetY = this.pixelOffset_.height; var iwWidth = this.div_.offsetWidth; var iwHeight = this.div_.offsetHeight; var padX = this.infoBoxClearance_.width; var padY = this.infoBoxClearance_.height; var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_); if (pixPosition.x < (-iwOffsetX + padX)) { xOffset = pixPosition.x + iwOffsetX - padX; } else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) { xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth; } if (this.alignBottom_) { if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) { yOffset = pixPosition.y + iwOffsetY - padY - iwHeight; } else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) { yOffset = pixPosition.y + iwOffsetY + padY - mapHeight; } } else { if (pixPosition.y < (-iwOffsetY + padY)) { yOffset = pixPosition.y + iwOffsetY - padY; } else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) { yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight; } } if (!(xOffset === 0 && yOffset === 0)) { // Move the map to the shifted center. // var c = map.getCenter(); map.panBy(xOffset, yOffset); } } } }; /** * Sets the style of the InfoBox by setting the style sheet and applying * other specific styles requested. * @private */ InfoBox.prototype.setBoxStyle_ = function () { var i, boxStyle; if (this.div_) { // Apply style values from the style sheet defined in the boxClass parameter: this.div_.className = this.boxClass_; // Clear existing inline style values: this.div_.style.cssText = ""; // Apply style values defined in the boxStyle parameter: boxStyle = this.boxStyle_; for (i in boxStyle) { if (boxStyle.hasOwnProperty(i)) { this.div_.style[i] = boxStyle[i]; } } // Fix up opacity style for benefit of MSIE: // if (typeof this.div_.style.opacity !== "undefined" && this.div_.style.opacity !== "") { this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")"; } // Apply required styles: // this.div_.style.position = "absolute"; this.div_.style.visibility = 'hidden'; if (this.zIndex_ !== null) { this.div_.style.zIndex = this.zIndex_; } } }; /** * Get the widths of the borders of the InfoBox. * @private * @return {Object} widths object (top, bottom left, right) */ InfoBox.prototype.getBoxWidths_ = function () { var computedStyle; var bw = {top: 0, bottom: 0, left: 0, right: 0}; var box = this.div_; if (document.defaultView && document.defaultView.getComputedStyle) { computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, ""); if (computedStyle) { // The computed styles are always in pixel units (good!) bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0; } } else if (document.documentElement.currentStyle) { // MSIE if (box.currentStyle) { // The current styles may not be in pixel units, but assume they are (bad!) bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0; } } return bw; }; /** * Invoked when <tt>close</tt> is called. Do not call it directly. */ InfoBox.prototype.onRemove = function () { if (this.div_) { this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Draws the InfoBox based on the current map projection and zoom level. */ InfoBox.prototype.draw = function () { this.createInfoBoxDiv_(); var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_); this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + "px"; if (this.alignBottom_) { this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + "px"; } else { this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + "px"; } if (this.isHidden_) { this.div_.style.visibility = 'hidden'; } else { this.div_.style.visibility = "visible"; } }; /** * Sets the options for the InfoBox. Note that changes to the <tt>maxWidth</tt>, * <tt>closeBoxMargin</tt>, <tt>closeBoxURL</tt>, and <tt>enableEventPropagation</tt> * properties have no affect until the current InfoBox is <tt>close</tt>d and a new one * is <tt>open</tt>ed. * @param {InfoBoxOptions} opt_opts */ InfoBox.prototype.setOptions = function (opt_opts) { if (typeof opt_opts.boxClass !== "undefined") { // Must be first this.boxClass_ = opt_opts.boxClass; this.setBoxStyle_(); } if (typeof opt_opts.boxStyle !== "undefined") { // Must be second this.boxStyle_ = opt_opts.boxStyle; this.setBoxStyle_(); } if (typeof opt_opts.content !== "undefined") { this.setContent(opt_opts.content); } if (typeof opt_opts.disableAutoPan !== "undefined") { this.disableAutoPan_ = opt_opts.disableAutoPan; } if (typeof opt_opts.maxWidth !== "undefined") { this.maxWidth_ = opt_opts.maxWidth; } if (typeof opt_opts.pixelOffset !== "undefined") { this.pixelOffset_ = opt_opts.pixelOffset; } if (typeof opt_opts.alignBottom !== "undefined") { this.alignBottom_ = opt_opts.alignBottom; } if (typeof opt_opts.position !== "undefined") { this.setPosition(opt_opts.position); } if (typeof opt_opts.zIndex !== "undefined") { this.setZIndex(opt_opts.zIndex); } if (typeof opt_opts.closeBoxMargin !== "undefined") { this.closeBoxMargin_ = opt_opts.closeBoxMargin; } if (typeof opt_opts.closeBoxURL !== "undefined") { this.closeBoxURL_ = opt_opts.closeBoxURL; } if (typeof opt_opts.infoBoxClearance !== "undefined") { this.infoBoxClearance_ = opt_opts.infoBoxClearance; } if (typeof opt_opts.isHidden !== "undefined") { this.isHidden_ = opt_opts.isHidden; } if (typeof opt_opts.enableEventPropagation !== "undefined") { this.enableEventPropagation_ = opt_opts.enableEventPropagation; } if (this.div_) { this.draw(); } }; /** * Sets the content of the InfoBox. * The content can be plain text or an HTML DOM node. * @param {string|Node} content */ InfoBox.prototype.setContent = function (content) { this.content_ = content; if (this.div_) { if (this.closeListener_) { google.maps.event.removeListener(this.closeListener_); this.closeListener_ = null; } // Odd code required to make things work with MSIE. // if (!this.fixedWidthSet_) { this.div_.style.width = ""; } if (typeof content.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + content; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(content); } // Perverse code required to make things work with MSIE. // (Ensures the close box does, in fact, float to the right.) // if (!this.fixedWidthSet_) { this.div_.style.width = this.div_.offsetWidth + "px"; if (typeof content.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + content; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(content); } } this.addClickHandler_(); } /** * This event is fired when the content of the InfoBox changes. * @name InfoBox#content_changed * @event */ google.maps.event.trigger(this, "content_changed"); }; /** * Sets the geographic location of the InfoBox. * @param {LatLng} latlng */ InfoBox.prototype.setPosition = function (latlng) { this.position_ = latlng; if (this.div_) { this.draw(); } /** * This event is fired when the position of the InfoBox changes. * @name InfoBox#position_changed * @event */ google.maps.event.trigger(this, "position_changed"); }; /** * Sets the zIndex style for the InfoBox. * @param {number} index */ InfoBox.prototype.setZIndex = function (index) { this.zIndex_ = index; if (this.div_) { this.div_.style.zIndex = index; } /** * This event is fired when the zIndex of the InfoBox changes. * @name InfoBox#zindex_changed * @event */ google.maps.event.trigger(this, "zindex_changed"); }; /** * Returns the content of the InfoBox. * @returns {string} */ InfoBox.prototype.getContent = function () { return this.content_; }; /** * Returns the geographic location of the InfoBox. * @returns {LatLng} */ InfoBox.prototype.getPosition = function () { return this.position_; }; /** * Returns the zIndex for the InfoBox. * @returns {number} */ InfoBox.prototype.getZIndex = function () { return this.zIndex_; }; /** * Shows the InfoBox. */ InfoBox.prototype.show = function () { this.isHidden_ = false; if (this.div_) { this.div_.style.visibility = "visible"; } }; /** * Hides the InfoBox. */ InfoBox.prototype.hide = function () { this.isHidden_ = true; if (this.div_) { this.div_.style.visibility = "hidden"; } }; /** * Adds the InfoBox to the specified map or Street View panorama. If <tt>anchor</tt> * (usually a <tt>google.maps.Marker</tt>) is specified, the position * of the InfoBox is set to the position of the <tt>anchor</tt>. If the * anchor is dragged to a new location, the InfoBox moves as well. * @param {Map|StreetViewPanorama} map * @param {MVCObject} [anchor] */ InfoBox.prototype.open = function (map, anchor) { var me = this; if (anchor) { this.position_ = anchor.getPosition(); this.moveListener_ = google.maps.event.addListener(anchor, "position_changed", function () { me.setPosition(this.getPosition()); }); } this.setMap(map); if (this.div_) { this.panBox_(); } }; /** * Removes the InfoBox from the map. */ InfoBox.prototype.close = function () { if (this.closeListener_) { google.maps.event.removeListener(this.closeListener_); this.closeListener_ = null; } if (this.eventListener1_) { google.maps.event.removeListener(this.eventListener1_); google.maps.event.removeListener(this.eventListener2_); google.maps.event.removeListener(this.eventListener3_); google.maps.event.removeListener(this.eventListener4_); this.eventListener1_ = null; this.eventListener2_ = null; this.eventListener3_ = null; this.eventListener4_ = null; } if (this.moveListener_) { google.maps.event.removeListener(this.moveListener_); this.moveListener_ = null; } if (this.contextListener_) { google.maps.event.removeListener(this.contextListener_); this.contextListener_ = null; } this.setMap(null); };
JavaScript
var GeoJSON = function( geojson, options ){ var _geometryToGoogleMaps = function( geojsonGeometry, options, geojsonProperties ){ var googleObj, opts = _copy(options); switch ( geojsonGeometry.type ){ case "Point": opts.position = new google.maps.LatLng(geojsonGeometry.coordinates[1], geojsonGeometry.coordinates[0]); googleObj = new google.maps.Marker(opts); if (geojsonProperties) { googleObj.set("geojsonProperties", geojsonProperties); } break; case "MultiPoint": googleObj = []; for (var i = 0; i < geojsonGeometry.coordinates.length; i++){ opts.position = new google.maps.LatLng(geojsonGeometry.coordinates[i][1], geojsonGeometry.coordinates[i][0]); googleObj.push(new google.maps.Marker(opts)); } if (geojsonProperties) { for (var k = 0; k < googleObj.length; k++){ googleObj[k].set("geojsonProperties", geojsonProperties); } } break; case "LineString": var path = []; for (var i = 0; i < geojsonGeometry.coordinates.length; i++){ var coord = geojsonGeometry.coordinates[i]; var ll = new google.maps.LatLng(coord[1], coord[0]); path.push(ll); } opts.path = path; googleObj = new google.maps.Polyline(opts); if (geojsonProperties) { googleObj.set("geojsonProperties", geojsonProperties); } break; case "MultiLineString": googleObj = []; for (var i = 0; i < geojsonGeometry.coordinates.length; i++){ var path = []; for (var j = 0; j < geojsonGeometry.coordinates[i].length; j++){ var coord = geojsonGeometry.coordinates[i][j]; var ll = new google.maps.LatLng(coord[1], coord[0]); path.push(ll); } opts.path = path; googleObj.push(new google.maps.Polyline(opts)); } if (geojsonProperties) { for (var k = 0; k < googleObj.length; k++){ googleObj[k].set("geojsonProperties", geojsonProperties); } } break; case "Polygon": var paths = []; var exteriorDirection; var interiorDirection; for (var i = 0; i < geojsonGeometry.coordinates.length; i++){ var path = []; for (var j = 0; j < geojsonGeometry.coordinates[i].length; j++){ var ll = new google.maps.LatLng(geojsonGeometry.coordinates[i][j][1], geojsonGeometry.coordinates[i][j][0]); path.push(ll); } if(!i){ exteriorDirection = _ccw(path); paths.push(path); }else if(i == 1){ interiorDirection = _ccw(path); if(exteriorDirection == interiorDirection){ paths.push(path.reverse()); }else{ paths.push(path); } }else{ if(exteriorDirection == interiorDirection){ paths.push(path.reverse()); }else{ paths.push(path); } } } opts.paths = paths; googleObj = new google.maps.Polygon(opts); if (geojsonProperties) { googleObj.set("geojsonProperties", geojsonProperties); } break; case "MultiPolygon": googleObj = []; for (var i = 0; i < geojsonGeometry.coordinates.length; i++){ var paths = []; var exteriorDirection; var interiorDirection; for (var j = 0; j < geojsonGeometry.coordinates[i].length; j++){ var path = []; for (var k = 0; k < geojsonGeometry.coordinates[i][j].length; k++){ var ll = new google.maps.LatLng(geojsonGeometry.coordinates[i][j][k][1], geojsonGeometry.coordinates[i][j][k][0]); path.push(ll); } if(!j){ exteriorDirection = _ccw(path); paths.push(path); }else if(j == 1){ interiorDirection = _ccw(path); if(exteriorDirection == interiorDirection){ paths.push(path.reverse()); }else{ paths.push(path); } }else{ if(exteriorDirection == interiorDirection){ paths.push(path.reverse()); }else{ paths.push(path); } } } opts.paths = paths; googleObj.push(new google.maps.Polygon(opts)); } if (geojsonProperties) { for (var k = 0; k < googleObj.length; k++){ googleObj[k].set("geojsonProperties", geojsonProperties); } } break; case "GeometryCollection": googleObj = []; if (!geojsonGeometry.geometries){ googleObj = _error("Invalid GeoJSON object: GeometryCollection object missing \"geometries\" member."); }else{ for (var i = 0; i < geojsonGeometry.geometries.length; i++){ googleObj.push(_geometryToGoogleMaps(geojsonGeometry.geometries[i], opts, geojsonProperties || null)); } } break; default: googleObj = _error("Invalid GeoJSON object: Geometry object must be one of \"Point\", \"LineString\", \"Polygon\" or \"MultiPolygon\"."); } return googleObj; }; var _error = function( message ){ return { type: "Error", message: message }; }; var _ccw = function( path ){ var isCCW; var a = 0; for (var i = 0; i < path.length-2; i++){ a += ((path[i+1].lat() - path[i].lat()) * (path[i+2].lng() - path[i].lng()) - (path[i+2].lat() - path[i].lat()) * (path[i+1].lng() - path[i].lng())); } if(a > 0){ isCCW = true; } else{ isCCW = false; } return isCCW; }; var _copy = function(obj){ var newObj = {}; for(var i in obj){ if(obj.hasOwnProperty(i)){ newObj[i] = obj[i]; } } return newObj; }; var obj; var opts = options || {}; switch ( geojson.type ){ case "FeatureCollection": if (!geojson.features){ obj = _error("Invalid GeoJSON object: FeatureCollection object missing \"features\" member."); }else{ obj = []; for (var i = 0; i < geojson.features.length; i++){ obj.push(_geometryToGoogleMaps(geojson.features[i].geometry, opts, geojson.features[i].properties)); } } break; case "GeometryCollection": if (!geojson.geometries){ obj = _error("Invalid GeoJSON object: GeometryCollection object missing \"geometries\" member."); }else{ obj = []; for (var i = 0; i < geojson.geometries.length; i++){ obj.push(_geometryToGoogleMaps(geojson.geometries[i], opts)); } } break; case "Feature": if (!( geojson.properties && geojson.geometry )){ obj = _error("Invalid GeoJSON object: Feature object missing \"properties\" or \"geometry\" member."); }else{ obj = _geometryToGoogleMaps(geojson.geometry, opts, geojson.properties); } break; case "Point": case "MultiPoint": case "LineString": case "MultiLineString": case "Polygon": case "MultiPolygon": obj = geojson.coordinates ? obj = _geometryToGoogleMaps(geojson, opts) : _error("Invalid GeoJSON object: Geometry object missing \"coordinates\" member."); break; default: obj = _error("Invalid GeoJSON object: GeoJSON object must be one of \"Point\", \"LineString\", \"Polygon\", \"MultiPolygon\", \"Feature\", \"FeatureCollection\" or \"GeometryCollection\"."); } return obj; };
JavaScript
/*! bootmetro 2013-06-18 */ /*! * jQuery Charms Plugin * Original author: @aozora * Licensed under the MIT license */ (function($, window, document, undefined){ // undefined is used here as the undefined global // variable in ECMAScript 3 and is mutable (i.e. it can // be changed by someone else). undefined isn't really // being passed in so we can ensure that its value is // truly undefined. In ES5, undefined can no longer be // modified. // window and document are passed through as local // variables rather than as globals, because this (slightly) // quickens the resolution process and can be more // efficiently minified (especially when both are // regularly referenced in your plugin). // Create the defaults once var pluginName = 'charms', defaults = { width: '320px', animateDuration: 600 }; // The actual plugin constructor function Charms(element, options){ this.element = element; // jQuery has an extend method that merges the // contents of two or more objects, storing the // result in the first object. The first object // is generally empty because we don't want to alter // the default options for future instances of the plugin this.options = $.extend({ }, defaults, options); this._defaults = defaults; this._name = pluginName; this.init(); } Charms.prototype = { init: function(){ // Place initialization logic here // You already have access to the DOM element and // the options via the instance, e.g. this.element // and this.options // you can add more functions like the one below and // call them like so: this.yourotherfunction(this.element, this.options). }, showSection: function(sectionId, width){ var w = this.options.width; if (width !== undefined){ w = width; } var transition = $.support.transition && $(this.element).hasClass('slide'); if (transition) { var ow = $(this.element).eq(0).offsetWidth; // force reflow } $(this.element).addClass('in'); return false; }, close: function(){ $(this.element).removeClass('in'); return false; }, toggleSection: function(sectionId, width){ if ($(this.element).hasClass('in')){ this.close(); }else{ this.showSection(sectionId, width); } }//, // // togglePin: function () { // var isPinned = $.cookie('charms_pinned'); // // if (isPinned == null) // { // // pin // $.cookie('charms_pinned', 'true'); // $.cookie('charms_width', $(this.element).width() ); // $("a#pin-charms").addClass("active"); // } // else // { // // unpin // $.cookie('charms_pinned', null); // $.cookie('charms_width', null ); // $("a#pin-charms").removeClass("active"); // } // } }; // A really lightweight plugin wrapper around the constructor, // preventing against multiple instantiations and allowing any // public function (ie. a function whose name doesn't start // with an underscore) to be called via the jQuery plugin, // e.g. $(element).defaultPluginName('functionName', arg1, arg2) $.fn[pluginName] = function(options){ var args = arguments; if (options === undefined || typeof options === 'object') { return this.each(function(){ if (!$.data(this, 'plugin_' + pluginName)) { $.data(this, 'plugin_' + pluginName, new Charms(this, options)); } }); } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') { return this.each(function(){ var instance = $.data(this, 'plugin_' + pluginName); if (instance instanceof Charms && typeof instance[options] === 'function') { instance[options].apply(instance, Array.prototype.slice.call(args, 1)); } }); } }; })(jQuery, window, document); (function ($) { $("#charms").charms(); $('.close-charms').click(function(e){ e.preventDefault(); $("#charms").charms('close'); }); /*$("a#pin-charms").click(function () { $(this) $("#charms").charms('togglePin'); });*/ })(jQuery); /* Load this script using conditional IE comments if you need to support IE 7 and IE 6. */ window.onload = function() { function addIcon(el, entity) { var html = el.innerHTML; el.innerHTML = '<span style="font-family: \'icomoon\'">' + entity + '</span>' + html; } var icons = { 'icon-battery-low' : '&#xe000;', 'icon-battery' : '&#xe001;', 'icon-battery-full' : '&#xe002;', 'icon-battery-charging' : '&#xe003;', 'icon-plus' : '&#xe004;', 'icon-cross' : '&#xe005;', 'icon-arrow-right' : '&#xe006;', 'icon-arrow-left' : '&#xe007;', 'icon-pencil' : '&#xe008;', 'icon-search' : '&#xe009;', 'icon-grid' : '&#xe00a;', 'icon-list' : '&#xe00b;', 'icon-star' : '&#xe00c;', 'icon-heart' : '&#xe00d;', 'icon-back' : '&#xe00e;', 'icon-forward' : '&#xe00f;', 'icon-map-marker' : '&#xe010;', 'icon-phone' : '&#xe011;', 'icon-home' : '&#xe012;', 'icon-camera' : '&#xe013;', 'icon-arrow-left-2' : '&#xe014;', 'icon-arrow-right-2' : '&#xe015;', 'icon-arrow-up' : '&#xe016;', 'icon-arrow-down' : '&#xe017;', 'icon-refresh' : '&#xe018;', 'icon-refresh-2' : '&#xe019;', 'icon-escape' : '&#xe01a;', 'icon-repeat' : '&#xe01b;', 'icon-loop' : '&#xe01c;', 'icon-shuffle' : '&#xe01d;', 'icon-feed' : '&#xe01e;', 'icon-cog' : '&#xe01f;', 'icon-wrench' : '&#xe020;', 'icon-bars' : '&#xe021;', 'icon-chart' : '&#xe022;', 'icon-stats' : '&#xe023;', 'icon-eye' : '&#xe024;', 'icon-zoom-out' : '&#xe025;', 'icon-zoom-in' : '&#xe026;', 'icon-export' : '&#xe027;', 'icon-user' : '&#xe028;', 'icon-users' : '&#xe029;', 'icon-microphone' : '&#xe02a;', 'icon-mail' : '&#xe02b;', 'icon-comment' : '&#xe02c;', 'icon-trashcan' : '&#xe02d;', 'icon-delete' : '&#xe02e;', 'icon-infinity' : '&#xe02f;', 'icon-key' : '&#xe030;', 'icon-globe' : '&#xe031;', 'icon-thumbs-up' : '&#xe032;', 'icon-thumbs-down' : '&#xe033;', 'icon-tag' : '&#xe034;', 'icon-views' : '&#xe035;', 'icon-warning' : '&#xe036;', 'icon-beta' : '&#xe037;', 'icon-unlocked' : '&#xe038;', 'icon-locked' : '&#xe039;', 'icon-eject' : '&#xe03a;', 'icon-move' : '&#xe03b;', 'icon-expand' : '&#xe03c;', 'icon-cancel' : '&#xe03d;', 'icon-electricity' : '&#xe03e;', 'icon-compass' : '&#xe03f;', 'icon-location' : '&#xe040;', 'icon-directions' : '&#xe041;', 'icon-pin' : '&#xe042;', 'icon-mute' : '&#xe043;', 'icon-volume' : '&#xe044;', 'icon-globe-2' : '&#xe045;', 'icon-pencil-2' : '&#xe046;', 'icon-minus' : '&#xe047;', 'icon-equals' : '&#xe048;', 'icon-list-2' : '&#xe049;', 'icon-flag' : '&#xe04a;', 'icon-info' : '&#xe04b;', 'icon-question' : '&#xe04c;', 'icon-chat' : '&#xe04d;', 'icon-clock' : '&#xe04e;', 'icon-calendar' : '&#xe04f;', 'icon-sun' : '&#xe050;', 'icon-contrast' : '&#xe051;', 'icon-mobile' : '&#xe052;', 'icon-download' : '&#xe053;', 'icon-puzzle' : '&#xe054;', 'icon-music' : '&#xe055;', 'icon-scissors' : '&#xe056;', 'icon-bookmark' : '&#xe057;', 'icon-anchor' : '&#xe058;', 'icon-checkmark' : '&#xe059;', 'icon-phone-2' : '&#xe05a;', 'icon-mobile-2' : '&#xe05b;', 'icon-mouse' : '&#xe05c;', 'icon-directions-2' : '&#xe05d;', 'icon-mail-2' : '&#xe05e;', 'icon-paperplane' : '&#xe05f;', 'icon-pencil-3' : '&#xe060;', 'icon-feather' : '&#xe061;', 'icon-paperclip' : '&#xe062;', 'icon-drawer' : '&#xe063;', 'icon-reply' : '&#xe064;', 'icon-reply-all' : '&#xe065;', 'icon-forward-2' : '&#xe066;', 'icon-user-2' : '&#xe067;', 'icon-users-2' : '&#xe068;', 'icon-user-add' : '&#xe069;', 'icon-vcard' : '&#xe06a;', 'icon-export-2' : '&#xe06b;', 'icon-location-2' : '&#xe06c;', 'icon-map' : '&#xe06d;', 'icon-compass-2' : '&#xe06e;', 'icon-location-3' : '&#xe06f;', 'icon-target' : '&#xe070;', 'icon-share' : '&#xe071;', 'icon-sharable' : '&#xe072;', 'icon-heart-2' : '&#xe073;', 'icon-heart-3' : '&#xe074;', 'icon-star-2' : '&#xe075;', 'icon-star-3' : '&#xe076;', 'icon-thumbs-up-2' : '&#xe077;', 'icon-thumbs-down-2' : '&#xe078;', 'icon-chat-2' : '&#xe079;', 'icon-comment-2' : '&#xe07a;', 'icon-quote' : '&#xe07b;', 'icon-house' : '&#xe07c;', 'icon-popup' : '&#xe07d;', 'icon-search-2' : '&#xe07e;', 'icon-flashlight' : '&#xe07f;', 'icon-printer' : '&#xe080;', 'icon-bell' : '&#xe081;', 'icon-link' : '&#xe082;', 'icon-flag-2' : '&#xe083;', 'icon-cog-2' : '&#xe084;', 'icon-tools' : '&#xe085;', 'icon-trophy' : '&#xe086;', 'icon-tag-2' : '&#xe087;', 'icon-camera-2' : '&#xe088;', 'icon-megaphone' : '&#xe089;', 'icon-moon' : '&#xe08a;', 'icon-palette' : '&#xe08b;', 'icon-leaf' : '&#xe08c;', 'icon-music-2' : '&#xe08d;', 'icon-music-3' : '&#xe08e;', 'icon-new' : '&#xe08f;', 'icon-graduation' : '&#xe090;', 'icon-book' : '&#xe091;', 'icon-newspaper' : '&#xe092;', 'icon-bag' : '&#xe093;', 'icon-airplane' : '&#xe094;', 'icon-lifebuoy' : '&#xe095;', 'icon-eye-2' : '&#xe096;', 'icon-clock-2' : '&#xe097;', 'icon-microphone-2' : '&#xe098;', 'icon-calendar-2' : '&#xe099;', 'icon-bolt' : '&#xe09a;', 'icon-thunder' : '&#xe09b;', 'icon-droplet' : '&#xe09c;', 'icon-cd' : '&#xe09d;', 'icon-briefcase' : '&#xe09e;', 'icon-air' : '&#xe09f;', 'icon-hourglass' : '&#xe0a0;', 'icon-gauge' : '&#xe0a1;', 'icon-language' : '&#xe0a2;', 'icon-network' : '&#xe0a3;', 'icon-key-2' : '&#xe0a4;', 'icon-battery-2' : '&#xe0a5;', 'icon-bucket' : '&#xe0a6;', 'icon-magnet' : '&#xe0a7;', 'icon-drive' : '&#xe0a8;', 'icon-cup' : '&#xe0a9;', 'icon-rocket' : '&#xe0aa;', 'icon-brush' : '&#xe0ab;', 'icon-suitcase' : '&#xe0ac;', 'icon-cone' : '&#xe0ad;', 'icon-earth' : '&#xe0ae;', 'icon-keyboard' : '&#xe0af;', 'icon-browser' : '&#xe0b0;', 'icon-publish' : '&#xe0b1;', 'icon-progress-3' : '&#xe0b2;', 'icon-progress-2' : '&#xe0b3;', 'icon-brogress-1' : '&#xe0b4;', 'icon-progress-0' : '&#xe0b5;', 'icon-sun-2' : '&#xe0b6;', 'icon-sun-3' : '&#xe0b7;', 'icon-adjust' : '&#xe0b8;', 'icon-code' : '&#xe0b9;', 'icon-screen' : '&#xe0ba;', 'icon-infinity-2' : '&#xe0bb;', 'icon-light-bulb' : '&#xe0bc;', 'icon-credit-card' : '&#xe0bd;', 'icon-database' : '&#xe0be;', 'icon-voicemail' : '&#xe0bf;', 'icon-clipboard' : '&#xe0c0;', 'icon-cart' : '&#xe0c1;', 'icon-box' : '&#xe0c2;', 'icon-ticket' : '&#xe0c3;', 'icon-rss' : '&#xe0c4;', 'icon-signal' : '&#xe0c5;', 'icon-thermometer' : '&#xe0c6;', 'icon-droplets' : '&#xe0c7;', 'icon-untitled' : '&#xe0c8;', 'icon-statistics' : '&#xe0c9;', 'icon-pie' : '&#xe0ca;', 'icon-bars-2' : '&#xe0cb;', 'icon-graph' : '&#xe0cc;', 'icon-lock' : '&#xe0cd;', 'icon-lock-open' : '&#xe0ce;', 'icon-logout' : '&#xe0cf;', 'icon-login' : '&#xe0d0;', 'icon-checkmark-2' : '&#xe0d1;', 'icon-cross-2' : '&#xe0d2;', 'icon-minus-2' : '&#xe0d3;', 'icon-plus-2' : '&#xe0d4;', 'icon-cross-3' : '&#xe0d5;', 'icon-minus-3' : '&#xe0d6;', 'icon-plus-3' : '&#xe0d7;', 'icon-cross-4' : '&#xe0d8;', 'icon-minus-4' : '&#xe0d9;', 'icon-plus-4' : '&#xe0da;', 'icon-erase' : '&#xe0db;', 'icon-blocked' : '&#xe0dc;', 'icon-info-2' : '&#xe0dd;', 'icon-info-3' : '&#xe0de;', 'icon-question-2' : '&#xe0df;', 'icon-help' : '&#xe0e0;', 'icon-warning-2' : '&#xe0e1;', 'icon-cycle' : '&#xe0e2;', 'icon-cw' : '&#xe0e3;', 'icon-ccw' : '&#xe0e4;', 'icon-shuffle-2' : '&#xe0e5;', 'icon-arrow' : '&#xe0e6;', 'icon-arrow-2' : '&#xe0e7;', 'icon-retweet' : '&#xe0e8;', 'icon-loop-2' : '&#xe0e9;', 'icon-history' : '&#xe0ea;', 'icon-back-2' : '&#xe0eb;', 'icon-switch' : '&#xe0ec;', 'icon-list-3' : '&#xe0ed;', 'icon-add-to-list' : '&#xe0ee;', 'icon-layout' : '&#xe0ef;', 'icon-list-4' : '&#xe0f0;', 'icon-text' : '&#xe0f1;', 'icon-text-2' : '&#xe0f2;', 'icon-document' : '&#xe0f3;', 'icon-docs' : '&#xe0f4;', 'icon-landscape' : '&#xe0f5;', 'icon-pictures' : '&#xe0f6;', 'icon-video' : '&#xe0f7;', 'icon-music-4' : '&#xe0f8;', 'icon-folder' : '&#xe0f9;', 'icon-archive' : '&#xe0fa;', 'icon-trash' : '&#xe0fb;', 'icon-upload' : '&#xe0fc;', 'icon-download-2' : '&#xe0fd;', 'icon-disk' : '&#xe0fe;', 'icon-install' : '&#xe0ff;', 'icon-cloud' : '&#xe100;', 'icon-upload-2' : '&#xe101;', 'icon-bookmark-2' : '&#xe102;', 'icon-bookmarks' : '&#xe103;', 'icon-book-2' : '&#xe104;', 'icon-play' : '&#xe105;', 'icon-pause' : '&#xe106;', 'icon-record' : '&#xe107;', 'icon-stop' : '&#xe108;', 'icon-next' : '&#xe109;', 'icon-previous' : '&#xe10a;', 'icon-first' : '&#xe10b;', 'icon-last' : '&#xe10c;', 'icon-resize-enlarge' : '&#xe10d;', 'icon-resize-shrink' : '&#xe10e;', 'icon-volume-2' : '&#xe10f;', 'icon-sound' : '&#xe110;', 'icon-mute-2' : '&#xe111;', 'icon-flow-cascade' : '&#xe112;', 'icon-flow-branch' : '&#xe113;', 'icon-flow-tree' : '&#xe114;', 'icon-flow-line' : '&#xe115;', 'icon-flow-parallel' : '&#xe116;', 'icon-arrow-left-3' : '&#xe117;', 'icon-arrow-down-2' : '&#xe118;', 'icon-arrow-up--upload' : '&#xe119;', 'icon-arrow-right-3' : '&#xe11a;', 'icon-arrow-left-4' : '&#xe11b;', 'icon-arrow-down-3' : '&#xe11c;', 'icon-arrow-up-2' : '&#xe11d;', 'icon-arrow-right-4' : '&#xe11e;', 'icon-arrow-left-5' : '&#xe11f;', 'icon-arrow-down-4' : '&#xe120;', 'icon-arrow-up-3' : '&#xe121;', 'icon-arrow-right-5' : '&#xe122;', 'icon-arrow-left-6' : '&#xe123;', 'icon-arrow-down-5' : '&#xe124;', 'icon-arrow-up-4' : '&#xe125;', 'icon-arrow-right-6' : '&#xe126;', 'icon-arrow-left-7' : '&#xe127;', 'icon-arrow-down-6' : '&#xe128;', 'icon-arrow-up-5' : '&#xe129;', 'icon-arrow-right-7' : '&#xe12a;', 'icon-arrow-left-8' : '&#xe12b;', 'icon-arrow-down-7' : '&#xe12c;', 'icon-arrow-up-6' : '&#xe12d;', 'icon-arrow-right-8' : '&#xe12e;', 'icon-arrow-left-9' : '&#xe12f;', 'icon-arrow-down-8' : '&#xe130;', 'icon-arrow-up-7' : '&#xe131;', 'icon-untitled-2' : '&#xe132;', 'icon-arrow-left-10' : '&#xe133;', 'icon-arrow-down-9' : '&#xe134;', 'icon-arrow-up-8' : '&#xe135;', 'icon-arrow-right-9' : '&#xe136;', 'icon-menu' : '&#xe137;', 'icon-ellipsis' : '&#xe138;', 'icon-dots' : '&#xe139;', 'icon-dot' : '&#xe13a;', 'icon-cc' : '&#xe13b;', 'icon-cc-by' : '&#xe13c;', 'icon-cc-nc' : '&#xe13d;', 'icon-cc-nc-eu' : '&#xe13e;', 'icon-cc-nc-jp' : '&#xe13f;', 'icon-cc-sa' : '&#xe140;', 'icon-cc-nd' : '&#xe141;', 'icon-cc-pd' : '&#xe142;', 'icon-cc-zero' : '&#xe143;', 'icon-cc-share' : '&#xe144;', 'icon-cc-share-2' : '&#xe145;', 'icon-daniel-bruce' : '&#xe146;', 'icon-daniel-bruce-2' : '&#xe147;', 'icon-github' : '&#xe148;', 'icon-github-2' : '&#xe149;', 'icon-flickr' : '&#xe14a;', 'icon-flickr-2' : '&#xe14b;', 'icon-vimeo' : '&#xe14c;', 'icon-vimeo-2' : '&#xe14d;', 'icon-twitter' : '&#xe14e;', 'icon-twitter-2' : '&#xe14f;', 'icon-facebook' : '&#xe150;', 'icon-facebook-2' : '&#xe151;', 'icon-facebook-3' : '&#xe152;', 'icon-googleplus' : '&#xe153;', 'icon-googleplus-2' : '&#xe154;', 'icon-pinterest' : '&#xe155;', 'icon-pinterest-2' : '&#xe156;', 'icon-tumblr' : '&#xe157;', 'icon-tumblr-2' : '&#xe158;', 'icon-linkedin' : '&#xe159;', 'icon-linkedin-2' : '&#xe15a;', 'icon-dribbble' : '&#xe15b;', 'icon-dribbble-2' : '&#xe15c;', 'icon-stumbleupon' : '&#xe15d;', 'icon-stumbleupon-2' : '&#xe15e;', 'icon-lastfm' : '&#xe15f;', 'icon-lastfm-2' : '&#xe160;', 'icon-rdio' : '&#xe161;', 'icon-rdio-2' : '&#xe162;', 'icon-spotify' : '&#xe163;', 'icon-spotify-2' : '&#xe164;', 'icon-qq' : '&#xe165;', 'icon-instagram' : '&#xe166;', 'icon-dropbox' : '&#xe167;', 'icon-evernote' : '&#xe168;', 'icon-flattr' : '&#xe169;', 'icon-skype' : '&#xe16a;', 'icon-skype-2' : '&#xe16b;', 'icon-renren' : '&#xe16c;', 'icon-sina-weibo' : '&#xe16d;', 'icon-paypal' : '&#xe16e;', 'icon-picasa' : '&#xe16f;', 'icon-soundcloud' : '&#xe170;', 'icon-mixi' : '&#xe171;', 'icon-behance' : '&#xe172;', 'icon-circles' : '&#xe173;', 'icon-vk' : '&#xe174;', 'icon-smashing' : '&#xe175;', 'icon-home-2' : '&#xe176;', 'icon-home-3' : '&#xe177;', 'icon-home-4' : '&#xe178;', 'icon-office' : '&#xe179;', 'icon-newspaper-2' : '&#xe17a;', 'icon-pencil-4' : '&#xe17b;', 'icon-pencil-5' : '&#xe17c;', 'icon-quill' : '&#xe17d;', 'icon-pen' : '&#xe17e;', 'icon-blog' : '&#xe17f;', 'icon-droplet-2' : '&#xe180;', 'icon-paint-format' : '&#xe181;', 'icon-image' : '&#xe182;', 'icon-image-2' : '&#xe183;', 'icon-images' : '&#xe184;', 'icon-camera-3' : '&#xe185;', 'icon-music-5' : '&#xe186;', 'icon-headphones' : '&#xe187;', 'icon-play-2' : '&#xe188;', 'icon-film' : '&#xe189;', 'icon-camera-4' : '&#xe18a;', 'icon-dice' : '&#xe18b;', 'icon-pacman' : '&#xe18c;', 'icon-spades' : '&#xe18d;', 'icon-clubs' : '&#xe18e;', 'icon-diamonds' : '&#xe18f;', 'icon-pawn' : '&#xe190;', 'icon-bullhorn' : '&#xe191;', 'icon-connection' : '&#xe192;', 'icon-podcast' : '&#xe193;', 'icon-feed-2' : '&#xe194;', 'icon-book-3' : '&#xe195;', 'icon-books' : '&#xe196;', 'icon-library' : '&#xe197;', 'icon-file' : '&#xe198;', 'icon-profile' : '&#xe199;', 'icon-file-2' : '&#xe19a;', 'icon-file-3' : '&#xe19b;', 'icon-file-4' : '&#xe19c;', 'icon-copy' : '&#xe19d;', 'icon-copy-2' : '&#xe19e;', 'icon-copy-3' : '&#xe19f;', 'icon-paste' : '&#xe1a0;', 'icon-paste-2' : '&#xe1a1;', 'icon-paste-3' : '&#xe1a2;', 'icon-stack' : '&#xe1a3;', 'icon-folder-2' : '&#xe1a4;', 'icon-folder-open' : '&#xe1a5;', 'icon-tag-3' : '&#xe1a6;', 'icon-tags' : '&#xe1a7;', 'icon-barcode' : '&#xe1a8;', 'icon-qrcode' : '&#xe1a9;', 'icon-ticket-2' : '&#xe1aa;', 'icon-cart-2' : '&#xe1ab;', 'icon-cart-3' : '&#xe1ac;', 'icon-cart-4' : '&#xe1ad;', 'icon-coin' : '&#xe1ae;', 'icon-credit' : '&#xe1af;', 'icon-calculate' : '&#xe1b0;', 'icon-support' : '&#xe1b1;', 'icon-phone-3' : '&#xe1b2;', 'icon-phone-hang-up' : '&#xe1b3;', 'icon-address-book' : '&#xe1b4;', 'icon-notebook' : '&#xe1b5;', 'icon-envelop' : '&#xe1b6;', 'icon-pushpin' : '&#xe1b7;', 'icon-location-4' : '&#xe1b8;', 'icon-location-5' : '&#xe1b9;', 'icon-compass-3' : '&#xe1ba;', 'icon-map-2' : '&#xe1bb;', 'icon-map-3' : '&#xe1bc;', 'icon-history-2' : '&#xe1bd;', 'icon-clock-3' : '&#xe1be;', 'icon-clock-4' : '&#xe1bf;', 'icon-alarm' : '&#xe1c0;', 'icon-alarm-2' : '&#xe1c1;', 'icon-bell-2' : '&#xe1c2;', 'icon-stopwatch' : '&#xe1c3;', 'icon-calendar-3' : '&#xe1c4;', 'icon-calendar-4' : '&#xe1c5;', 'icon-print' : '&#xe1c6;', 'icon-keyboard-2' : '&#xe1c7;', 'icon-screen-2' : '&#xe1c8;', 'icon-laptop' : '&#xe1c9;', 'icon-mobile-3' : '&#xe1ca;', 'icon-mobile-4' : '&#xe1cb;', 'icon-tablet' : '&#xe1cc;', 'icon-tv' : '&#xe1cd;', 'icon-cabinet' : '&#xe1ce;', 'icon-drawer-2' : '&#xe1cf;', 'icon-drawer-3' : '&#xe1d0;', 'icon-drawer-4' : '&#xe1d1;', 'icon-box-add' : '&#xe1d2;', 'icon-box-remove' : '&#xe1d3;', 'icon-download-3' : '&#xe1d4;', 'icon-upload-3' : '&#xe1d5;', 'icon-disk-2' : '&#xe1d6;', 'icon-storage' : '&#xe1d7;', 'icon-undo' : '&#xe1d8;', 'icon-redo' : '&#xe1d9;', 'icon-flip' : '&#xe1da;', 'icon-flip-2' : '&#xe1db;', 'icon-undo-2' : '&#xe1dc;', 'icon-redo-2' : '&#xe1dd;', 'icon-forward-3' : '&#xe1de;', 'icon-reply-2' : '&#xe1df;', 'icon-bubble' : '&#xe1e0;', 'icon-bubbles' : '&#xe1e1;', 'icon-bubbles-2' : '&#xe1e2;', 'icon-bubble-2' : '&#xe1e3;', 'icon-bubbles-3' : '&#xe1e4;', 'icon-bubbles-4' : '&#xe1e5;', 'icon-user-3' : '&#xe1e6;', 'icon-users-3' : '&#xe1e7;', 'icon-user-4' : '&#xe1e8;', 'icon-users-4' : '&#xe1e9;', 'icon-user-5' : '&#xe1ea;', 'icon-user-6' : '&#xe1eb;', 'icon-quotes-left' : '&#xe1ec;', 'icon-busy' : '&#xe1ed;', 'icon-spinner' : '&#xe1ee;', 'icon-spinner-2' : '&#xe1ef;', 'icon-spinner-3' : '&#xe1f0;', 'icon-spinner-4' : '&#xe1f1;', 'icon-spinner-5' : '&#xe1f2;', 'icon-spinner-6' : '&#xe1f3;', 'icon-binoculars' : '&#xe1f4;', 'icon-search-3' : '&#xe1f5;', 'icon-zoom-in-2' : '&#xe1f6;', 'icon-zoom-out-2' : '&#xe1f7;', 'icon-expand-2' : '&#xe1f8;', 'icon-contract' : '&#xe1f9;', 'icon-expand-3' : '&#xe1fa;', 'icon-contract-2' : '&#xe1fb;', 'icon-key-3' : '&#xe1fc;', 'icon-key-4' : '&#xe1fd;', 'icon-lock-2' : '&#xe1fe;', 'icon-lock-3' : '&#xe1ff;', 'icon-unlocked-2' : '&#xe200;', 'icon-wrench-2' : '&#xe201;', 'icon-settings' : '&#xe202;', 'icon-equalizer' : '&#xe203;', 'icon-cog-3' : '&#xe204;', 'icon-cogs' : '&#xe205;', 'icon-cog-4' : '&#xe206;', 'icon-hammer' : '&#xe207;', 'icon-wand' : '&#xe208;', 'icon-aid' : '&#xe209;', 'icon-bug' : '&#xe20a;', 'icon-pie-2' : '&#xe20b;', 'icon-stats-2' : '&#xe20c;', 'icon-bars-3' : '&#xe20d;', 'icon-bars-4' : '&#xe20e;', 'icon-gift' : '&#xe20f;', 'icon-trophy-2' : '&#xe210;', 'icon-glass' : '&#xe211;', 'icon-mug' : '&#xe212;', 'icon-food' : '&#xe213;', 'icon-leaf-2' : '&#xe214;', 'icon-rocket-2' : '&#xe215;', 'icon-meter' : '&#xe216;', 'icon-meter2' : '&#xe217;', 'icon-dashboard' : '&#xe218;', 'icon-hammer-2' : '&#xe219;', 'icon-fire' : '&#xe21a;', 'icon-lab' : '&#xe21b;', 'icon-magnet-2' : '&#xe21c;', 'icon-remove' : '&#xe21d;', 'icon-remove-2' : '&#xe21e;', 'icon-briefcase-2' : '&#xe21f;', 'icon-airplane-2' : '&#xe220;', 'icon-truck' : '&#xe221;', 'icon-road' : '&#xe222;', 'icon-accessibility' : '&#xe223;', 'icon-target-2' : '&#xe224;', 'icon-shield' : '&#xe225;', 'icon-lightning' : '&#xe226;', 'icon-switch-2' : '&#xe227;', 'icon-power-cord' : '&#xe228;', 'icon-signup' : '&#xe229;', 'icon-list-5' : '&#xe22a;', 'icon-list-6' : '&#xe22b;', 'icon-numbered-list' : '&#xe22c;', 'icon-menu-2' : '&#xe22d;', 'icon-menu-3' : '&#xe22e;', 'icon-tree' : '&#xe22f;', 'icon-cloud-2' : '&#xe230;', 'icon-cloud-download' : '&#xe231;', 'icon-cloud-upload' : '&#xe232;', 'icon-download-4' : '&#xe233;', 'icon-upload-4' : '&#xe234;', 'icon-download-5' : '&#xe235;', 'icon-upload-5' : '&#xe236;', 'icon-globe-3' : '&#xe237;', 'icon-earth-2' : '&#xe238;', 'icon-link-2' : '&#xe239;', 'icon-flag-3' : '&#xe23a;', 'icon-attachment' : '&#xe23b;', 'icon-eye-3' : '&#xe23c;', 'icon-eye-blocked' : '&#xe23d;', 'icon-eye-4' : '&#xe23e;', 'icon-bookmark-3' : '&#xe23f;', 'icon-bookmarks-2' : '&#xe240;', 'icon-brightness-medium' : '&#xe241;', 'icon-brightness-contrast' : '&#xe242;', 'icon-contrast-2' : '&#xe243;', 'icon-star-4' : '&#xe244;', 'icon-star-5' : '&#xe245;', 'icon-star-6' : '&#xe246;', 'icon-heart-4' : '&#xe247;', 'icon-heart-5' : '&#xe248;', 'icon-heart-broken' : '&#xe249;', 'icon-thumbs-up-3' : '&#xe24a;', 'icon-thumbs-up-4' : '&#xe24b;', 'icon-happy' : '&#xe24c;', 'icon-happy-2' : '&#xe24d;', 'icon-smiley' : '&#xe24e;', 'icon-smiley-2' : '&#xe24f;', 'icon-tongue' : '&#xe250;', 'icon-tongue-2' : '&#xe251;', 'icon-sad' : '&#xe252;', 'icon-sad-2' : '&#xe253;', 'icon-wink' : '&#xe254;', 'icon-wink-2' : '&#xe255;', 'icon-grin' : '&#xe256;', 'icon-grin-2' : '&#xe257;', 'icon-cool' : '&#xe258;', 'icon-cool-2' : '&#xe259;', 'icon-angry' : '&#xe25a;', 'icon-angry-2' : '&#xe25b;', 'icon-evil' : '&#xe25c;', 'icon-evil-2' : '&#xe25d;', 'icon-shocked' : '&#xe25e;', 'icon-shocked-2' : '&#xe25f;', 'icon-confused' : '&#xe260;', 'icon-confused-2' : '&#xe261;', 'icon-neutral' : '&#xe262;', 'icon-neutral-2' : '&#xe263;', 'icon-wondering' : '&#xe264;', 'icon-wondering-2' : '&#xe265;', 'icon-point-up' : '&#xe266;', 'icon-point-right' : '&#xe267;', 'icon-point-down' : '&#xe268;', 'icon-point-left' : '&#xe269;', 'icon-warning-3' : '&#xe26a;', 'icon-notification' : '&#xe26b;', 'icon-question-3' : '&#xe26c;', 'icon-info-4' : '&#xe26d;', 'icon-info-5' : '&#xe26e;', 'icon-blocked-2' : '&#xe26f;', 'icon-cancel-circle' : '&#xe270;', 'icon-checkmark-circle' : '&#xe271;', 'icon-spam' : '&#xe272;', 'icon-close' : '&#xe273;', 'icon-checkmark-3' : '&#xe274;', 'icon-checkmark-4' : '&#xe275;', 'icon-spell-check' : '&#xe276;', 'icon-minus-5' : '&#xe277;', 'icon-plus-5' : '&#xe278;', 'icon-enter' : '&#xe279;', 'icon-exit' : '&#xe27a;', 'icon-play-3' : '&#xe27b;', 'icon-pause-2' : '&#xe27c;', 'icon-stop-2' : '&#xe27d;', 'icon-backward' : '&#xe27e;', 'icon-forward-4' : '&#xe27f;', 'icon-play-4' : '&#xe280;', 'icon-pause-3' : '&#xe281;', 'icon-stop-3' : '&#xe282;', 'icon-backward-2' : '&#xe283;', 'icon-forward-5' : '&#xe284;', 'icon-first-2' : '&#xe285;', 'icon-last-2' : '&#xe286;', 'icon-previous-2' : '&#xe287;', 'icon-next-2' : '&#xe288;', 'icon-eject-2' : '&#xe289;', 'icon-volume-high' : '&#xe28a;', 'icon-volume-medium' : '&#xe28b;', 'icon-volume-low' : '&#xe28c;', 'icon-volume-mute' : '&#xe28d;', 'icon-volume-mute-2' : '&#xe28e;', 'icon-volume-increase' : '&#xe28f;', 'icon-volume-decrease' : '&#xe290;', 'icon-loop-3' : '&#xe291;', 'icon-loop-4' : '&#xe292;', 'icon-loop-5' : '&#xe293;', 'icon-shuffle-3' : '&#xe294;', 'icon-arrow-up-left' : '&#xe295;', 'icon-arrow-up-9' : '&#xe296;', 'icon-arrow-up-right' : '&#xe297;', 'icon-arrow-right-10' : '&#xe298;', 'icon-arrow-down-right' : '&#xe299;', 'icon-arrow-down-10' : '&#xe29a;', 'icon-arrow-down-left' : '&#xe29b;', 'icon-arrow-left-11' : '&#xe29c;', 'icon-arrow-up-left-2' : '&#xe29d;', 'icon-arrow-up-10' : '&#xe29e;', 'icon-arrow-up-right-2' : '&#xe29f;', 'icon-arrow-right-11' : '&#xe2a0;', 'icon-arrow-down-right-2' : '&#xe2a1;', 'icon-arrow-down-11' : '&#xe2a2;', 'icon-arrow-down-left-2' : '&#xe2a3;', 'icon-arrow-left-12' : '&#xe2a4;', 'icon-arrow-up-left-3' : '&#xe2a5;', 'icon-arrow-up-11' : '&#xe2a6;', 'icon-arrow-up-right-3' : '&#xe2a7;', 'icon-arrow-right-12' : '&#xe2a8;', 'icon-arrow-down-right-3' : '&#xe2a9;', 'icon-arrow-down-12' : '&#xe2aa;', 'icon-arrow-down-left-3' : '&#xe2ab;', 'icon-arrow-left-13' : '&#xe2ac;', 'icon-tab' : '&#xe2ad;', 'icon-checkbox-checked' : '&#xe2ae;', 'icon-checkbox-unchecked' : '&#xe2af;', 'icon-checkbox-partial' : '&#xe2b0;', 'icon-radio-checked' : '&#xe2b1;', 'icon-radio-unchecked' : '&#xe2b2;', 'icon-crop' : '&#xe2b3;', 'icon-scissors-2' : '&#xe2b4;', 'icon-filter' : '&#xe2b5;', 'icon-filter-2' : '&#xe2b6;', 'icon-font' : '&#xe2b7;', 'icon-text-height' : '&#xe2b8;', 'icon-text-width' : '&#xe2b9;', 'icon-bold' : '&#xe2ba;', 'icon-underline' : '&#xe2bb;', 'icon-italic' : '&#xe2bc;', 'icon-strikethrough' : '&#xe2bd;', 'icon-omega' : '&#xe2be;', 'icon-sigma' : '&#xe2bf;', 'icon-table' : '&#xe2c0;', 'icon-table-2' : '&#xe2c1;', 'icon-insert-template' : '&#xe2c2;', 'icon-pilcrow' : '&#xe2c3;', 'icon-left-to-right' : '&#xe2c4;', 'icon-right-to-left' : '&#xe2c5;', 'icon-paragraph-left' : '&#xe2c6;', 'icon-paragraph-center' : '&#xe2c7;', 'icon-paragraph-right' : '&#xe2c8;', 'icon-paragraph-justify' : '&#xe2c9;', 'icon-paragraph-left-2' : '&#xe2ca;', 'icon-paragraph-center-2' : '&#xe2cb;', 'icon-paragraph-right-2' : '&#xe2cc;', 'icon-paragraph-justify-2' : '&#xe2cd;', 'icon-indent-increase' : '&#xe2ce;', 'icon-indent-decrease' : '&#xe2cf;', 'icon-new-tab' : '&#xe2d0;', 'icon-embed' : '&#xe2d1;', 'icon-code-2' : '&#xe2d2;', 'icon-console' : '&#xe2d3;', 'icon-share-2' : '&#xe2d4;', 'icon-mail-3' : '&#xe2d5;', 'icon-mail-4' : '&#xe2d6;', 'icon-mail-5' : '&#xe2d7;', 'icon-mail-6' : '&#xe2d8;', 'icon-google' : '&#xe2d9;', 'icon-google-plus' : '&#xe2da;', 'icon-google-plus-2' : '&#xe2db;', 'icon-google-plus-3' : '&#xe2dc;', 'icon-google-plus-4' : '&#xe2dd;', 'icon-google-drive' : '&#xe2de;', 'icon-facebook-4' : '&#xe2df;', 'icon-facebook-5' : '&#xe2e0;', 'icon-facebook-6' : '&#xe2e1;', 'icon-instagram-2' : '&#xe2e2;', 'icon-twitter-3' : '&#xe2e3;', 'icon-twitter-4' : '&#xe2e4;', 'icon-twitter-5' : '&#xe2e5;', 'icon-feed-3' : '&#xe2e6;', 'icon-feed-4' : '&#xe2e7;', 'icon-feed-5' : '&#xe2e8;', 'icon-youtube' : '&#xe2e9;', 'icon-youtube-2' : '&#xe2ea;', 'icon-vimeo-3' : '&#xe2eb;', 'icon-vimeo2' : '&#xe2ec;', 'icon-vimeo-4' : '&#xe2ed;', 'icon-lanyrd' : '&#xe2ee;', 'icon-flickr-3' : '&#xe2ef;', 'icon-flickr-4' : '&#xe2f0;', 'icon-flickr-5' : '&#xe2f1;', 'icon-flickr-6' : '&#xe2f2;', 'icon-picassa' : '&#xe2f3;', 'icon-picassa-2' : '&#xe2f4;', 'icon-dribbble-3' : '&#xe2f5;', 'icon-dribbble-4' : '&#xe2f6;', 'icon-dribbble-5' : '&#xe2f7;', 'icon-forrst' : '&#xe2f8;', 'icon-forrst-2' : '&#xe2f9;', 'icon-deviantart' : '&#xe2fa;', 'icon-deviantart-2' : '&#xe2fb;', 'icon-steam' : '&#xe2fc;', 'icon-steam-2' : '&#xe2fd;', 'icon-github-3' : '&#xe2fe;', 'icon-github-4' : '&#xe2ff;', 'icon-github-5' : '&#xe300;', 'icon-github-6' : '&#xe301;', 'icon-github-7' : '&#xe302;', 'icon-wordpress' : '&#xe303;', 'icon-wordpress-2' : '&#xe304;', 'icon-joomla' : '&#xe305;', 'icon-blogger' : '&#xe306;', 'icon-blogger-2' : '&#xe307;', 'icon-tumblr-3' : '&#xe308;', 'icon-tumblr-4' : '&#xe309;', 'icon-yahoo' : '&#xe30a;', 'icon-tux' : '&#xe30b;', 'icon-apple' : '&#xe30c;', 'icon-finder' : '&#xe30d;', 'icon-android' : '&#xe30e;', 'icon-windows' : '&#xe30f;', 'icon-windows8' : '&#xe310;', 'icon-soundcloud-2' : '&#xe311;', 'icon-soundcloud-3' : '&#xe312;', 'icon-skype-3' : '&#xe313;', 'icon-reddit' : '&#xe314;', 'icon-linkedin-3' : '&#xe315;', 'icon-lastfm-3' : '&#xe316;', 'icon-lastfm-4' : '&#xe317;', 'icon-delicious' : '&#xe318;', 'icon-stumbleupon-3' : '&#xe319;', 'icon-stumbleupon-4' : '&#xe31a;', 'icon-stackoverflow' : '&#xe31b;', 'icon-pinterest-3' : '&#xe31c;', 'icon-pinterest-4' : '&#xe31d;', 'icon-xing' : '&#xe31e;', 'icon-xing-2' : '&#xe31f;', 'icon-flattr-2' : '&#xe320;', 'icon-foursquare' : '&#xe321;', 'icon-foursquare-2' : '&#xe322;', 'icon-paypal-2' : '&#xe323;', 'icon-paypal-3' : '&#xe324;', 'icon-paypal-4' : '&#xe325;', 'icon-yelp' : '&#xe326;', 'icon-libreoffice' : '&#xe327;', 'icon-file-pdf' : '&#xe328;', 'icon-file-openoffice' : '&#xe329;', 'icon-file-word' : '&#xe32a;', 'icon-file-excel' : '&#xe32b;', 'icon-file-zip' : '&#xe32c;', 'icon-file-powerpoint' : '&#xe32d;', 'icon-file-xml' : '&#xe32e;', 'icon-file-css' : '&#xe32f;', 'icon-html5' : '&#xe330;', 'icon-html5-2' : '&#xe331;', 'icon-css3' : '&#xe332;', 'icon-chrome' : '&#xe333;', 'icon-firefox' : '&#xe334;', 'icon-IE' : '&#xe335;', 'icon-opera' : '&#xe336;', 'icon-safari' : '&#xe337;', 'icon-IcoMoon' : '&#xe338;', 'icon-warning-4' : '&#xe339;', 'icon-cloud-3' : '&#xe33a;', 'icon-locked-2' : '&#xe33b;', 'icon-inbox' : '&#xe33c;', 'icon-comment-3' : '&#xe33d;', 'icon-mic' : '&#xe33e;', 'icon-envelope' : '&#xe33f;', 'icon-briefcase-3' : '&#xe340;', 'icon-cart-5' : '&#xe341;', 'icon-contrast-3' : '&#xe342;', 'icon-clock-5' : '&#xe343;', 'icon-user-7' : '&#xe344;', 'icon-cog-5' : '&#xe345;', 'icon-music-6' : '&#xe346;', 'icon-twitter-6' : '&#xe347;', 'icon-pencil-6' : '&#xe348;', 'icon-frame' : '&#xe349;', 'icon-switch-3' : '&#xe34a;', 'icon-star-7' : '&#xe34b;', 'icon-key-5' : '&#xe34c;', 'icon-chart-2' : '&#xe34d;', 'icon-apple-2' : '&#xe34e;', 'icon-file-5' : '&#xe34f;', 'icon-plus-6' : '&#xe350;', 'icon-minus-6' : '&#xe351;', 'icon-picture' : '&#xe352;', 'icon-folder-3' : '&#xe353;', 'icon-camera-5' : '&#xe354;', 'icon-search-4' : '&#xe355;', 'icon-dribbble-6' : '&#xe356;', 'icon-forrst-3' : '&#xe357;', 'icon-feed-6' : '&#xe358;', 'icon-blocked-3' : '&#xe359;', 'icon-target-3' : '&#xe35a;', 'icon-play-5' : '&#xe35b;', 'icon-pause-4' : '&#xe35c;', 'icon-bug-2' : '&#xe35d;', 'icon-console-2' : '&#xe35e;', 'icon-film-2' : '&#xe35f;', 'icon-type' : '&#xe360;', 'icon-home-5' : '&#xe361;', 'icon-earth-3' : '&#xe362;', 'icon-location-6' : '&#xe363;', 'icon-info-6' : '&#xe364;', 'icon-eye-5' : '&#xe365;', 'icon-heart-6' : '&#xe366;', 'icon-bookmark-4' : '&#xe367;', 'icon-wrench-3' : '&#xe368;', 'icon-calendar-5' : '&#xe369;', 'icon-window' : '&#xe36a;', 'icon-monitor' : '&#xe36b;', 'icon-mobile-5' : '&#xe36c;', 'icon-droplet-3' : '&#xe36d;', 'icon-mouse-2' : '&#xe36e;', 'icon-refresh-3' : '&#xe36f;', 'icon-location-7' : '&#xe370;', 'icon-tag-4' : '&#xe371;', 'icon-phone-4' : '&#xe372;', 'icon-star-8' : '&#xe373;', 'icon-pointer' : '&#xe374;', 'icon-thumbs-up-5' : '&#xe375;', 'icon-thumbs-down-3' : '&#xe376;', 'icon-headphones-2' : '&#xe377;', 'icon-move-2' : '&#xe378;', 'icon-checkmark-5' : '&#xe379;', 'icon-cancel-2' : '&#xe37a;', 'icon-skype-4' : '&#xe37b;', 'icon-gift-2' : '&#xe37c;', 'icon-cone-2' : '&#xe37d;', 'icon-alarm-3' : '&#xe37e;', 'icon-coffee' : '&#xe37f;', 'icon-basket' : '&#xe380;', 'icon-flag-4' : '&#xe381;', 'icon-ipod' : '&#xe382;', 'icon-trashcan-2' : '&#xe383;', 'icon-bolt-2' : '&#xe384;', 'icon-ampersand' : '&#xe385;', 'icon-compass-4' : '&#xe386;', 'icon-list-7' : '&#xe387;', 'icon-grid-2' : '&#xe388;', 'icon-volume-3' : '&#xe389;', 'icon-volume-4' : '&#xe38a;', 'icon-stats-3' : '&#xe38b;', 'icon-target-4' : '&#xe38c;', 'icon-forward-6' : '&#xe38d;', 'icon-paperclip-2' : '&#xe38e;', 'icon-keyboard-3' : '&#xe38f;', 'icon-crop-2' : '&#xe390;', 'icon-floppy' : '&#xe391;', 'icon-filter-3' : '&#xe392;', 'icon-trophy-3' : '&#xe393;', 'icon-diary' : '&#xe394;', 'icon-address-book-2' : '&#xe395;', 'icon-stop-4' : '&#xe396;', 'icon-smiley-3' : '&#xe397;', 'icon-shit' : '&#xe398;', 'icon-bookmark-5' : '&#xe399;', 'icon-camera-6' : '&#xe39a;', 'icon-lamp' : '&#xe39b;', 'icon-disk-3' : '&#xe39c;', 'icon-button' : '&#xe39d;', 'icon-database-2' : '&#xe39e;', 'icon-credit-card-2' : '&#xe39f;', 'icon-atom' : '&#xe3a0;', 'icon-winsows' : '&#xe3a1;', 'icon-target-5' : '&#xe3a2;', 'icon-battery-3' : '&#xe3a3;', 'icon-code-3' : '&#xe3a4;', 'icon-sunrise' : '&#xe3a5;', 'icon-sun-4' : '&#xe3a6;', 'icon-moon-2' : '&#xe3a7;', 'icon-sun-5' : '&#xe3a8;', 'icon-windy' : '&#xe3a9;', 'icon-wind' : '&#xe3aa;', 'icon-snowflake' : '&#xe3ab;', 'icon-cloudy' : '&#xe3ac;', 'icon-cloud-4' : '&#xe3ad;', 'icon-weather' : '&#xe3ae;', 'icon-weather-2' : '&#xe3af;', 'icon-weather-3' : '&#xe3b0;', 'icon-lines' : '&#xe3b1;', 'icon-cloud-5' : '&#xe3b2;', 'icon-lightning-2' : '&#xe3b3;', 'icon-lightning-3' : '&#xe3b4;', 'icon-rainy' : '&#xe3b5;', 'icon-rainy-2' : '&#xe3b6;', 'icon-windy-2' : '&#xe3b7;', 'icon-windy-3' : '&#xe3b8;', 'icon-snowy' : '&#xe3b9;', 'icon-snowy-2' : '&#xe3ba;', 'icon-snowy-3' : '&#xe3bb;', 'icon-weather-4' : '&#xe3bc;', 'icon-cloudy-2' : '&#xe3bd;', 'icon-cloud-6' : '&#xe3be;', 'icon-lightning-4' : '&#xe3bf;', 'icon-sun-6' : '&#xe3c0;', 'icon-moon-3' : '&#xe3c1;', 'icon-cloudy-3' : '&#xe3c2;', 'icon-cloud-7' : '&#xe3c3;', 'icon-cloud-8' : '&#xe3c4;', 'icon-lightning-5' : '&#xe3c5;', 'icon-rainy-3' : '&#xe3c6;', 'icon-rainy-4' : '&#xe3c7;', 'icon-windy-4' : '&#xe3c8;', 'icon-windy-5' : '&#xe3c9;', 'icon-snowy-4' : '&#xe3ca;', 'icon-snowy-5' : '&#xe3cb;', 'icon-weather-5' : '&#xe3cc;', 'icon-cloudy-4' : '&#xe3cd;', 'icon-lightning-6' : '&#xe3ce;', 'icon-thermometer-2' : '&#xe3cf;', 'icon-compass-5' : '&#xe3d0;', 'icon-none' : '&#xe3d1;', 'icon-Celsius' : '&#xe3d2;', 'icon-Fahrenheit' : '&#xe3d3;', 'icon-chat-3' : '&#xe3d4;', 'icon-chat-alt-stroke' : '&#xe3d5;', 'icon-chat-alt-fill' : '&#xe3d6;', 'icon-comment-alt1-stroke' : '&#xe3d7;', 'icon-comment-alt1-fill' : '&#xe3d8;', 'icon-comment-stroke' : '&#xe3d9;', 'icon-comment-fill' : '&#xe3da;', 'icon-comment-alt2-stroke' : '&#xe3db;', 'icon-comment-alt2-fill' : '&#xe3dc;', 'icon-checkmark-6' : '&#xe3dd;', 'icon-check-alt' : '&#xe3de;', 'icon-x' : '&#xe3df;', 'icon-x-altx-alt' : '&#xe3e0;', 'icon-denied' : '&#xe3e1;', 'icon-cursor' : '&#xe3e2;', 'icon-rss-2' : '&#xe3e3;', 'icon-rss-alt' : '&#xe3e4;', 'icon-wrench-4' : '&#xe3e5;', 'icon-dial' : '&#xe3e6;', 'icon-cog-6' : '&#xe3e7;', 'icon-calendar-6' : '&#xe3e8;', 'icon-calendar-alt-stroke' : '&#xe3e9;', 'icon-calendar-alt-fill' : '&#xe3ea;', 'icon-share-3' : '&#xe3eb;', 'icon-mail-7' : '&#xe3ec;', 'icon-heart-stroke' : '&#xe3ed;', 'icon-heart-fill' : '&#xe3ee;', 'icon-movie' : '&#xe3ef;', 'icon-document-alt-stroke' : '&#xe3f0;', 'icon-document-alt-fill' : '&#xe3f1;', 'icon-document-stroke' : '&#xe3f2;', 'icon-document-fill' : '&#xe3f3;', 'icon-plus-7' : '&#xe3f4;', 'icon-plus-alt' : '&#xe3f5;', 'icon-minus-7' : '&#xe3f6;', 'icon-minus-alt' : '&#xe3f7;', 'icon-pin-2' : '&#xe3f8;', 'icon-link-3' : '&#xe3f9;', 'icon-bolt-3' : '&#xe3fa;', 'icon-move-3' : '&#xe3fb;', 'icon-move-alt1' : '&#xe3fc;', 'icon-move-alt2' : '&#xe3fd;', 'icon-equalizer-2' : '&#xe3fe;', 'icon-award-fill' : '&#xe3ff;', 'icon-award-stroke' : '&#xe400;', 'icon-magnifying-glass' : '&#xe401;', 'icon-trash-stroke' : '&#xe402;', 'icon-trash-fill' : '&#xe403;', 'icon-beaker-alt' : '&#xe404;', 'icon-beaker' : '&#xe405;', 'icon-key-stroke' : '&#xe406;', 'icon-key-fill' : '&#xe407;', 'icon-new-window' : '&#xe408;', 'icon-lightbulb' : '&#xe409;', 'icon-spin-alt' : '&#xe40a;', 'icon-spin' : '&#xe40b;', 'icon-curved-arrow' : '&#xe40c;', 'icon-undo-3' : '&#xe40d;', 'icon-reload' : '&#xe40e;', 'icon-reload-alt' : '&#xe40f;', 'icon-loop-6' : '&#xe410;', 'icon-loop-alt1' : '&#xe411;', 'icon-loop-alt2' : '&#xe412;', 'icon-loop-alt3' : '&#xe413;', 'icon-loop-alt4' : '&#xe414;', 'icon-transfer' : '&#xe415;', 'icon-move-vertical' : '&#xe416;', 'icon-move-vertical-alt1' : '&#xe417;', 'icon-move-vertical-alt2' : '&#xe418;', 'icon-move-horizontal' : '&#xe419;', 'icon-move-horizontal-alt1' : '&#xe41a;', 'icon-move-horizontal-alt2' : '&#xe41b;', 'icon-arrow-left-14' : '&#xe41c;', 'icon-arrow-left-alt1' : '&#xe41d;', 'icon-arrow-left-alt2' : '&#xe41e;', 'icon-arrow-right-13' : '&#xe41f;', 'icon-arrow-right-alt1' : '&#xe420;', 'icon-arrow-right-alt2' : '&#xe421;', 'icon-arrow-up-12' : '&#xe422;', 'icon-arrow-up-alt1' : '&#xe423;', 'icon-arrow-up-alt2' : '&#xe424;', 'icon-arrow-down-13' : '&#xe425;', 'icon-arrow-down-alt1' : '&#xe426;', 'icon-arrow-down-alt2' : '&#xe427;', 'icon-cd-2' : '&#xe428;', 'icon-steering-wheel' : '&#xe429;', 'icon-microphone-3' : '&#xe42a;', 'icon-headphones-3' : '&#xe42b;', 'icon-volume-5' : '&#xe42c;', 'icon-volume-mute-3' : '&#xe42d;', 'icon-play-6' : '&#xe42e;', 'icon-pause-5' : '&#xe42f;', 'icon-stop-5' : '&#xe430;', 'icon-eject-3' : '&#xe431;', 'icon-first-3' : '&#xe432;', 'icon-last-3' : '&#xe433;', 'icon-play-alt' : '&#xe434;', 'icon-fullscreen-exit' : '&#xe435;', 'icon-fullscreen-exit-alt' : '&#xe436;', 'icon-fullscreen' : '&#xe437;', 'icon-fullscreen-alt' : '&#xe438;', 'icon-iphone' : '&#xe439;', 'icon-battery-empty' : '&#xe43a;', 'icon-battery-half' : '&#xe43b;', 'icon-battery-full-2' : '&#xe43c;', 'icon-battery-charging-2' : '&#xe43d;', 'icon-compass-6' : '&#xe43e;', 'icon-box-2' : '&#xe43f;', 'icon-folder-stroke' : '&#xe440;', 'icon-folder-fill' : '&#xe441;', 'icon-at' : '&#xe442;', 'icon-ampersand-2' : '&#xe443;', 'icon-info-7' : '&#xe444;', 'icon-question-mark' : '&#xe445;', 'icon-pilcrow-2' : '&#xe446;', 'icon-hash' : '&#xe447;', 'icon-left-quote' : '&#xe448;', 'icon-right-quote' : '&#xe449;', 'icon-left-quote-alt' : '&#xe44a;', 'icon-right-quote-alt' : '&#xe44b;', 'icon-article' : '&#xe44c;', 'icon-read-more' : '&#xe44d;', 'icon-list-8' : '&#xe44e;', 'icon-list-nested' : '&#xe44f;', 'icon-book-4' : '&#xe450;', 'icon-book-alt' : '&#xe451;', 'icon-book-alt2' : '&#xe452;', 'icon-pen-2' : '&#xe453;', 'icon-pen-alt-stroke' : '&#xe454;', 'icon-pen-alt-fill' : '&#xe455;', 'icon-pen-alt2' : '&#xe456;', 'icon-brush-2' : '&#xe457;', 'icon-brush-alt' : '&#xe458;', 'icon-eyedropper' : '&#xe459;', 'icon-layers-alt' : '&#xe45a;', 'icon-layers' : '&#xe45b;', 'icon-image-3' : '&#xe45c;', 'icon-camera-7' : '&#xe45d;', 'icon-aperture' : '&#xe45e;', 'icon-aperture-alt' : '&#xe45f;', 'icon-chart-3' : '&#xe460;', 'icon-chart-alt' : '&#xe461;', 'icon-bars-5' : '&#xe462;', 'icon-bars-alt' : '&#xe463;', 'icon-eye-6' : '&#xe464;', 'icon-user-8' : '&#xe465;', 'icon-home-6' : '&#xe466;', 'icon-clock-6' : '&#xe467;', 'icon-lock-stroke' : '&#xe468;', 'icon-lock-fill' : '&#xe469;', 'icon-unlock-stroke' : '&#xe46a;', 'icon-unlock-fill' : '&#xe46b;', 'icon-tag-stroke' : '&#xe46c;', 'icon-tag-fill' : '&#xe46d;', 'icon-sun-stroke' : '&#xe46e;', 'icon-sun-fill' : '&#xe46f;', 'icon-moon-stroke' : '&#xe470;', 'icon-moon-fill' : '&#xe471;', 'icon-cloud-9' : '&#xe472;', 'icon-rain' : '&#xe473;', 'icon-umbrella' : '&#xe474;', 'icon-star-9' : '&#xe475;', 'icon-map-pin-stroke' : '&#xe476;', 'icon-map-pin-fill' : '&#xe477;', 'icon-map-pin-alt' : '&#xe478;', 'icon-target-6' : '&#xe479;', 'icon-download-6' : '&#xe47a;', 'icon-upload-6' : '&#xe47b;', 'icon-cloud-download-2' : '&#xe47c;', 'icon-cloud-upload-2' : '&#xe47d;', 'icon-fork' : '&#xe47e;', 'icon-paperclip-3' : '&#xe47f;' }, els = document.getElementsByTagName('*'), i, attr, html, c, el; for (i = 0; i < els.length; i += 1) { el = els[i]; attr = el.getAttribute('data-icon'); if (attr) { addIcon(el, attr); } c = el.className; c = c.match(/icon-[^\s'"]+/); if (c && icons[c[0]]) { addIcon(el, icons[c[0]]); } } }; /* ========================================================== * bootpanorama-panorama.js v1.0 * http://aozora.github.com/bootpanorama/ * ========================================================== * Copyright 2012 Marcello Palmitessa * * 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. * ========================================================== */ !function ($) { "use strict"; /* PIVOT CLASS DEFINITION * ========================= */ var Panorama = function (element, options) { this.$element = $(element) this.options = options // this.options.slide && this.slide(this.options.slide) this.$groups = $('.panorama-sections .panorama-section') this.$current = 0 this.init() } Panorama.prototype = { // init panorama workspace init: function(){ var $this = this // arrange the panorama height this.$element.height( this.$element.parent().height() - $('#nav-bar').outerHeight() ) // arrange the section container width $this.resize(); // setup mousewheel // win8: wheel-down => scroll to right -1 0 -1 // wheel-up => scroll to left 1 0 1 if (this.options.mousewheel){ $('.panorama-sections').mousewheel(function(event, delta, deltaX, deltaY) { //e.preventDefault(); //console.log(delta, deltaX, deltaY); if (delta > 0){ $this.prev() } else{ $this.next() } }); } // Arrange Tiles like Win8 ones if (this.options.arrangetiles){ $('.panorama-sections .panorama-section').each(function(index, el){ }); } // parallax can be activated only if there is CSS3 transition support if (this.options.parallax){ // add a class to enable css3 transition $('body').addClass("panorama-parallax"); } if (this.options.showscrollbuttons){ var $p = $('.panorama-sections'); $('#panorama-scroll-prev').click(function(e){ e.preventDefault(); $this.prev() }); $("#panorama-scroll-next").click(function(e){ e.preventDefault(); $this.next() }); } else { $('#panorama-scroll-prev').hide() $('#panorama-scroll-next').hide() } //Enable swiping... $(".panorama").swipe( { //Generic swipe handler for all directions swipe:function(event, direction, distance, duration, fingerCount) { if (direction=='right'){ $this.prev() } if (direction=='left'){ $this.next() } } ,threshold: 0 //ingers: 'all' }); $this.setButtons() if (this.options.keyboard){ $(document).on('keyup', function ( e ) { if (e.which == 37) { // left-arrow $this.prev() } if (e.which == 39) { // right-arrow $this.next() } }) } // $(window).resize(function() { // // // call resize function // // }); } // end init , next: function () { var $this = this this.$current++ if (this.$current >= this.$groups.length){ this.$current = this.$groups.length - 1 } var $p = $('.panorama-sections'); var targetOffset = $(this.$groups[this.$current]).position().left if (this.options.parallax && $.support.transition){ $('body').css('background-position', (targetOffset / 2) + 'px 0px') } $p.animate({ marginLeft: -targetOffset }, { duration: 200, easing: 'swing' ,complete: function(){$this.setButtons()} } ); } , prev: function () { var $this = this this.$current-- if (this.$current < 0){ this.$current = 0 } var $p = $('.panorama-sections'); var targetOffset = $(this.$groups[this.$current]).position().left if (this.options.parallax && $.support.transition){ $('body').css('background-position', (targetOffset / 2) + 'px 0px') } $p.animate({ marginLeft: -targetOffset }, { duration: 200, easing: 'swing' ,complete: function(){$this.setButtons()} } ); } , resize: function(){ // arrange the section container width var totalWidth = 0 $('.panorama-sections .panorama-section').each(function(index, el){ totalWidth += $(el).outerWidth(true) }); $('.panorama-sections') .width(totalWidth) .height( this.$element.parent().height()) } , setButtons: function () { if (!this.options.showscrollbuttons){ return false; } if (this.$current === 0){ $("#panorama-scroll-prev").hide(); } else { $("#panorama-scroll-prev").show(); } if (this.$current === this.$groups.length - 1){ $("#panorama-scroll-next").hide(); } else { $("#panorama-scroll-next").show(); } } } /* PANORAMA PLUGIN DEFINITION * ========================== */ $.fn.panorama = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('panorama') , options = $.extend({}, $.fn.panorama.defaults, typeof option == 'object' && option) , action = typeof option == 'string' ? option : options.slide if (!data) { $this.data('panorama', (data = new Panorama(this, options))) } // if (typeof option == 'number') data.to(option) else if (action){ data[action]() } }) } $.fn.panorama.defaults = { showscrollbuttons: true, parallax: false, keyboard: true, mousewheel: true, arrangetiles: true } $.fn.panorama.Constructor = Panorama }(window.jQuery); /* ========================================================== * bootstrap-pivot.js v1.0.0 alpha1 * http://aozora.github.com/bootmetro/ * ========================================================== * Copyright 2013 Marcello Palmitessa * ========================================================== */ !function ($) { "use strict"; /* PIVOT CLASS DEFINITION * ========================= */ var Pivot = function (element, options) { this.$element = $(element) this.options = options this.options.slide && this.slide(this.options.slide) } Pivot.prototype = { to: function (pos) { var $active = this.$element.find('> .pivot-items > .pivot-item.active').eq(0) , children = $active.parent().children() , activePos = children.index($active) , that = this if (pos > (children.length - 1) || pos < 0) return if (this.sliding) { return this.$element.one('slid', function () { that.to(pos) }) return } if (pos === activePos) return return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos])) } , next: function () { if (this.sliding) return return this.slide('next') } , prev: function () { if (this.sliding) return return this.slide('prev') } , slide: function (type, next) { var $active = this.$element.find('> .pivot-items > .pivot-item.active').eq(0) , $next = next || $active[type]() , direction = type == 'next' ? 'left' : 'right' , fallback = type == 'next' ? 'first' : 'last' , that = this , e this.sliding = true $next = $next.length ? $next : this.$element.find('> .pivot-items > .pivot-item')[fallback]() e = $.Event('slide', { relatedTarget: $next[0] }) if ($next.hasClass('active')) { that.sliding = false // this should prevent issue #45 return } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) this.$element.one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid') }, 0) }) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid') } return this } } /* PIVOT PLUGIN DEFINITION * ========================== */ $.fn.pivot = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('pivot') , options = $.extend({}, $.fn.pivot.defaults, typeof option == 'object' && option) , action = typeof option == 'string' ? option : options.slide if (!data) $this.data('pivot', (data = new Pivot(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() }) } $.fn.pivot.defaults = { } $.fn.pivot.Constructor = Pivot /* PIVOT DATA-API * ================= */ $(document).on('click.pivot.data-api', '[data-pivot-index]', function (e) { var $this = $(this), href , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 , options = $.extend({}, $target.data(), $this.data()) , $index = parseInt($this.attr('data-pivot-index'), 10); $('[data-pivot-index].active').removeClass('active') $this.addClass('active') $target.pivot($index) e.preventDefault() }) }(window.jQuery);
JavaScript
/* * @fileOverview TouchSwipe - jQuery Plugin * @version 1.6.3 * * @author Matt Bryson http://www.github.com/mattbryson * @see https://github.com/mattbryson/TouchSwipe-Jquery-Plugin * @see http://labs.skinkers.com/touchSwipe/ * @see http://plugins.jquery.com/project/touchSwipe * * Copyright (c) 2010 Matt Bryson * Dual licensed under the MIT or GPL Version 2 licenses. * * * Changelog * $Date: 2010-12-12 (Wed, 12 Dec 2010) $ * $version: 1.0.0 * $version: 1.0.1 - removed multibyte comments * * $Date: 2011-21-02 (Mon, 21 Feb 2011) $ * $version: 1.1.0 - added allowPageScroll property to allow swiping and scrolling of page * - changed handler signatures so one handler can be used for multiple events * $Date: 2011-23-02 (Wed, 23 Feb 2011) $ * $version: 1.2.0 - added click handler. This is fired if the user simply clicks and does not swipe. The event object and click target are passed to handler. * - If you use the http://code.google.com/p/jquery-ui-for-ipad-and-iphone/ plugin, you can also assign jQuery mouse events to children of a touchSwipe object. * $version: 1.2.1 - removed console log! * * $version: 1.2.2 - Fixed bug where scope was not preserved in callback methods. * * $Date: 2011-28-04 (Thurs, 28 April 2011) $ * $version: 1.2.4 - Changed licence terms to be MIT or GPL inline with jQuery. Added check for support of touch events to stop non compatible browsers erroring. * * $Date: 2011-27-09 (Tues, 27 September 2011) $ * $version: 1.2.5 - Added support for testing swipes with mouse on desktop browser (thanks to https://github.com/joelhy) * * $Date: 2012-14-05 (Mon, 14 May 2012) $ * $version: 1.2.6 - Added timeThreshold between start and end touch, so user can ignore slow swipes (thanks to Mark Chase). Default is null, all swipes are detected * * $Date: 2012-05-06 (Tues, 05 June 2012) $ * $version: 1.2.7 - Changed time threshold to have null default for backwards compatibility. Added duration param passed back in events, and refactored how time is handled. * * $Date: 2012-05-06 (Tues, 05 June 2012) $ * $version: 1.2.8 - Added the possibility to return a value like null or false in the trigger callback. In that way we can control when the touch start/move should take effect or not (simply by returning in some cases return null; or return false;) This effects the ontouchstart/ontouchmove event. * * $Date: 2012-06-06 (Wed, 06 June 2012) $ * $version: 1.3.0 - Refactored whole plugin to allow for methods to be executed, as well as exposed defaults for user override. Added 'enable', 'disable', and 'destroy' methods * * $Date: 2012-05-06 (Fri, 05 June 2012) $ * $version: 1.3.1 - Bug fixes - bind() with false as last argument is no longer supported in jQuery 1.6, also, if you just click, the duration is now returned correctly. * * $Date: 2012-29-07 (Sun, 29 July 2012) $ * $version: 1.3.2 - Added fallbackToMouseEvents option to NOT capture mouse events on non touch devices. * - Added "all" fingers value to the fingers property, so any combinatin of fingers triggers the swipe, allowing event handlers to check the finger count * * $Date: 2012-09-08 (Thurs, 9 Aug 2012) $ * $version: 1.3.3 - Code tidy prep for minified version * * $Date: 2012-04-10 (wed, 4 Oct 2012) $ * $version: 1.4.0 - Added pinch support, pinchIn and pinchOut * * $Date: 2012-11-10 (Thurs, 11 Oct 2012) $ * $version: 1.5.0 - Added excludedElements, a jquery selector that specifies child elements that do NOT trigger swipes. By default, this is one select that removes all form, input select, button and anchor elements. * * $Date: 2012-22-10 (Mon, 22 Oct 2012) $ * $version: 1.5.1 - Fixed bug with jQuery 1.8 and trailing comma in excludedElements * - Fixed bug with IE and eventPreventDefault() * $Date: 2013-01-12 (Fri, 12 Jan 2013) $ * $version: 1.6.0 - Fixed bugs with pinching, mainly when both pinch and swipe enabled, as well as adding time threshold for multifinger gestures, so releasing one finger beofre the other doesnt trigger as single finger gesture. * - made the demo site all static local HTML pages so they can be run locally by a developer * - added jsDoc comments and added documentation for the plugin * - code tidy * - added triggerOnTouchLeave property that will end the event when the user swipes off the element. * $Date: 2013-03-23 (Sat, 23 Mar 2013) $ * $version: 1.6.1 - Added support for ie8 touch events * $version: 1.6.2 - Added support for events binding with on / off / bind in jQ for all callback names. * - Deprecated the 'click' handler in favour of tap. * - added cancelThreshold property * - added option method to update init options at runtime * * $version 1.6.3 - added doubletap, longtap events and longTapThreshold, doubleTapThreshold property * $Date: 2013-04-04 (Thurs, 04 April 2013) $ * $version 1.6.4 - Fixed bug with cancelThreshold introduced in 1.6.3, where swipe status no longer fired start event, and stopped once swiping back. */ /** * See (http://jquery.com/). * @name $ * @class * See the jQuery Library (http://jquery.com/) for full details. This just * documents the function and classes that are added to jQuery by this plug-in. */ /** * See (http://jquery.com/) * @name fn * @class * See the jQuery Library (http://jquery.com/) for full details. This just * documents the function and classes that are added to jQuery by this plug-in. * @memberOf $ */ (function ($) { "use strict"; //Constants var LEFT = "left", RIGHT = "right", UP = "up", DOWN = "down", IN = "in", OUT = "out", NONE = "none", AUTO = "auto", SWIPE = "swipe", PINCH = "pinch", TAP = "tap", DOUBLE_TAP = "doubletap", LONG_TAP = "longtap", HORIZONTAL = "horizontal", VERTICAL = "vertical", ALL_FINGERS = "all", DOUBLE_TAP_THRESHOLD = 10, PHASE_START = "start", PHASE_MOVE = "move", PHASE_END = "end", PHASE_CANCEL = "cancel", SUPPORTS_TOUCH = 'ontouchstart' in window, PLUGIN_NS = 'TouchSwipe'; /** * The default configuration, and available options to configure touch swipe with. * You can set the default values by updating any of the properties prior to instantiation. * @name $.fn.swipe.defaults * @namespace * @property {int} [fingers=1] The number of fingers to detect in a swipe. Any swipes that do not meet this requirement will NOT trigger swipe handlers. * @property {int} [threshold=75] The number of pixels that the user must move their finger by before it is considered a swipe. * @property {int} [cancelThreshold=null] The number of pixels that the user must move their finger back from the original swipe direction to cancel the gesture. * @property {int} [pinchThreshold=20] The number of pixels that the user must pinch their finger by before it is considered a pinch. * @property {int} [maxTimeThreshold=null] Time, in milliseconds, between touchStart and touchEnd must NOT exceed in order to be considered a swipe. * @property {int} [fingerReleaseThreshold=250] Time in milliseconds between releasing multiple fingers. If 2 fingers are down, and are released one after the other, if they are within this threshold, it counts as a simultaneous release. * @property {int} [longTapThreshold=500] Time in milliseconds between tap and release for a long tap * @property {int} [doubleTapThreshold=200] Time in milliseconds between 2 taps to count as a doubletap * @property {function} [swipe=null] A handler to catch all swipes. See {@link $.fn.swipe#event:swipe} * @property {function} [swipeLeft=null] A handler that is triggered for "left" swipes. See {@link $.fn.swipe#event:swipeLeft} * @property {function} [swipeRight=null] A handler that is triggered for "right" swipes. See {@link $.fn.swipe#event:swipeRight} * @property {function} [swipeUp=null] A handler that is triggered for "up" swipes. See {@link $.fn.swipe#event:swipeUp} * @property {function} [swipeDown=null] A handler that is triggered for "down" swipes. See {@link $.fn.swipe#event:swipeDown} * @property {function} [swipeStatus=null] A handler triggered for every phase of the swipe. See {@link $.fn.swipe#event:swipeStatus} * @property {function} [pinchIn=null] A handler triggered for pinch in events. See {@link $.fn.swipe#event:pinchIn} * @property {function} [pinchOut=null] A handler triggered for pinch out events. See {@link $.fn.swipe#event:pinchOut} * @property {function} [pinchStatus=null] A handler triggered for every phase of a pinch. See {@link $.fn.swipe#event:pinchStatus} * @property {function} [tap=null] A handler triggered when a user just taps on the item, rather than swipes it. If they do not move, tap is triggered, if they do move, it is not. * @property {function} [doubleTap=null] A handler triggered when a user double taps on the item. The delay between taps can be set with the doubleTapThreshold property. See {@link $.fn.swipe.defaults#doubleTapThreshold} * @property {function} [longTap=null] A handler triggered when a user long taps on the item. The delay between start and end can be set with the longTapThreshold property. See {@link $.fn.swipe.defaults#doubleTapThreshold} * @property {boolean} [triggerOnTouchEnd=true] If true, the swipe events are triggered when the touch end event is received (user releases finger). If false, it will be triggered on reaching the threshold, and then cancel the touch event automatically. * @property {boolean} [triggerOnTouchLeave=false] If true, then when the user leaves the swipe object, the swipe will end and trigger appropriate handlers. * @property {string} [allowPageScroll='auto'] How the browser handles page scrolls when the user is swiping on a touchSwipe object. See {@link $.fn.swipe.pageScroll}. <br/><br/> <code>"auto"</code> : all undefined swipes will cause the page to scroll in that direction. <br/> <code>"none"</code> : the page will not scroll when user swipes. <br/> <code>"horizontal"</code> : will force page to scroll on horizontal swipes. <br/> <code>"vertical"</code> : will force page to scroll on vertical swipes. <br/> * @property {boolean} [fallbackToMouseEvents=true] If true mouse events are used when run on a non touch device, false will stop swipes being triggered by mouse events on non tocuh devices. * @property {string} [excludedElements="button, input, select, textarea, a, .noSwipe"] A jquery selector that specifies child elements that do NOT trigger swipes. By default this excludes all form, input, select, button, anchor and .noSwipe elements. */ var defaults = { fingers: 1, threshold: 75, cancelThreshold:null, pinchThreshold:20, maxTimeThreshold: null, fingerReleaseThreshold:250, longTapThreshold:500, doubleTapThreshold:200, swipe: null, swipeLeft: null, swipeRight: null, swipeUp: null, swipeDown: null, swipeStatus: null, pinchIn:null, pinchOut:null, pinchStatus:null, click:null, //Deprecated since 1.6.2 tap:null, doubleTap:null, longTap:null, triggerOnTouchEnd: true, triggerOnTouchLeave:false, allowPageScroll: "auto", fallbackToMouseEvents: true, excludedElements:"button, input, select, textarea, a, .noSwipe" }; /** * Applies TouchSwipe behaviour to one or more jQuery objects. * The TouchSwipe plugin can be instantiated via this method, or methods within * TouchSwipe can be executed via this method as per jQuery plugin architecture. * @see TouchSwipe * @class * @param {Mixed} method If the current DOMNode is a TouchSwipe object, and <code>method</code> is a TouchSwipe method, then * the <code>method</code> is executed, and any following arguments are passed to the TouchSwipe method. * If <code>method</code> is an object, then the TouchSwipe class is instantiated on the current DOMNode, passing the * configuration properties defined in the object. See TouchSwipe * */ $.fn.swipe = function (method) { var $this = $(this), plugin = $this.data(PLUGIN_NS); //Check if we are already instantiated and trying to execute a method if (plugin && typeof method === 'string') { if (plugin[method]) { return plugin[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else { $.error('Method ' + method + ' does not exist on jQuery.swipe'); } } //Else not instantiated and trying to pass init object (or nothing) else if (!plugin && (typeof method === 'object' || !method)) { return init.apply(this, arguments); } return $this; }; //Expose our defaults so a user could override the plugin defaults $.fn.swipe.defaults = defaults; /** * The phases that a touch event goes through. The <code>phase</code> is passed to the event handlers. * These properties are read only, attempting to change them will not alter the values passed to the event handlers. * @namespace * @readonly * @property {string} PHASE_START Constant indicating the start phase of the touch event. Value is <code>"start"</code>. * @property {string} PHASE_MOVE Constant indicating the move phase of the touch event. Value is <code>"move"</code>. * @property {string} PHASE_END Constant indicating the end phase of the touch event. Value is <code>"end"</code>. * @property {string} PHASE_CANCEL Constant indicating the cancel phase of the touch event. Value is <code>"cancel"</code>. */ $.fn.swipe.phases = { PHASE_START: PHASE_START, PHASE_MOVE: PHASE_MOVE, PHASE_END: PHASE_END, PHASE_CANCEL: PHASE_CANCEL }; /** * The direction constants that are passed to the event handlers. * These properties are read only, attempting to change them will not alter the values passed to the event handlers. * @namespace * @readonly * @property {string} LEFT Constant indicating the left direction. Value is <code>"left"</code>. * @property {string} RIGHT Constant indicating the right direction. Value is <code>"right"</code>. * @property {string} UP Constant indicating the up direction. Value is <code>"up"</code>. * @property {string} DOWN Constant indicating the down direction. Value is <code>"cancel"</code>. * @property {string} IN Constant indicating the in direction. Value is <code>"in"</code>. * @property {string} OUT Constant indicating the out direction. Value is <code>"out"</code>. */ $.fn.swipe.directions = { LEFT: LEFT, RIGHT: RIGHT, UP: UP, DOWN: DOWN, IN : IN, OUT: OUT }; /** * The page scroll constants that can be used to set the value of <code>allowPageScroll</code> option * These properties are read only * @namespace * @readonly * @see $.fn.swipe.defaults#allowPageScroll * @property {string} NONE Constant indicating no page scrolling is allowed. Value is <code>"none"</code>. * @property {string} HORIZONTAL Constant indicating horizontal page scrolling is allowed. Value is <code>"horizontal"</code>. * @property {string} VERTICAL Constant indicating vertical page scrolling is allowed. Value is <code>"vertical"</code>. * @property {string} AUTO Constant indicating either horizontal or vertical will be allowed, depending on the swipe handlers registered. Value is <code>"auto"</code>. */ $.fn.swipe.pageScroll = { NONE: NONE, HORIZONTAL: HORIZONTAL, VERTICAL: VERTICAL, AUTO: AUTO }; /** * Constants representing the number of fingers used in a swipe. These are used to set both the value of <code>fingers</code> in the * options object, as well as the value of the <code>fingers</code> event property. * These properties are read only, attempting to change them will not alter the values passed to the event handlers. * @namespace * @readonly * @see $.fn.swipe.defaults#fingers * @property {string} ONE Constant indicating 1 finger is to be detected / was detected. Value is <code>1</code>. * @property {string} TWO Constant indicating 2 fingers are to be detected / were detected. Value is <code>1</code>. * @property {string} THREE Constant indicating 3 finger are to be detected / were detected. Value is <code>1</code>. * @property {string} ALL Constant indicating any combination of finger are to be detected. Value is <code>"all"</code>. */ $.fn.swipe.fingers = { ONE: 1, TWO: 2, THREE: 3, ALL: ALL_FINGERS }; /** * Initialise the plugin for each DOM element matched * This creates a new instance of the main TouchSwipe class for each DOM element, and then * saves a reference to that instance in the elements data property. * @internal */ function init(options) { //Prep and extend the options if (options && (options.allowPageScroll === undefined && (options.swipe !== undefined || options.swipeStatus !== undefined))) { options.allowPageScroll = NONE; } //Check for deprecated options //Ensure that any old click handlers are assigned to the new tap, unless we have a tap if(options.click!==undefined && options.tap===undefined) { options.tap = options.click; } if (!options) { options = {}; } //pass empty object so we dont modify the defaults options = $.extend({}, $.fn.swipe.defaults, options); //For each element instantiate the plugin return this.each(function () { var $this = $(this); //Check we havent already initialised the plugin var plugin = $this.data(PLUGIN_NS); if (!plugin) { plugin = new TouchSwipe(this, options); $this.data(PLUGIN_NS, plugin); } }); } /** * Main TouchSwipe Plugin Class. * Do not use this to construct your TouchSwipe object, use the jQuery plugin method $.fn.swipe(); {@link $.fn.swipe} * @private * @name TouchSwipe * @param {DOMNode} element The HTML DOM object to apply to plugin to * @param {Object} options The options to configure the plugin with. @link {$.fn.swipe.defaults} * @see $.fh.swipe.defaults * @see $.fh.swipe * @class */ function TouchSwipe(element, options) { var useTouchEvents = (SUPPORTS_TOUCH || !options.fallbackToMouseEvents), START_EV = useTouchEvents ? 'touchstart' : 'mousedown', MOVE_EV = useTouchEvents ? 'touchmove' : 'mousemove', END_EV = useTouchEvents ? 'touchend' : 'mouseup', LEAVE_EV = useTouchEvents ? null : 'mouseleave', //we manually detect leave on touch devices, so null event here CANCEL_EV = 'touchcancel'; //touch properties var distance = 0, direction = null, duration = 0, startTouchesDistance = 0, endTouchesDistance = 0, pinchZoom = 1, pinchDistance = 0, pinchDirection = 0, maximumsMap=null; //jQuery wrapped element for this instance var $element = $(element); //Current phase of th touch cycle var phase = "start"; // the current number of fingers being used. var fingerCount = 0; //track mouse points / delta var fingerData=null; //track times var startTime = 0, endTime = 0, previousTouchEndTime=0, previousTouchFingerCount=0, doubleTapStartTime=0; //Timeouts var singleTapTimeout=null; // Add gestures to all swipable areas if supported try { $element.bind(START_EV, touchStart); $element.bind(CANCEL_EV, touchCancel); } catch (e) { $.error('events not supported ' + START_EV + ',' + CANCEL_EV + ' on jQuery.swipe'); } // //Public methods // /** * re-enables the swipe plugin with the previous configuration * @function * @name $.fn.swipe#enable * @return {DOMNode} The Dom element that was registered with TouchSwipe * @example $("#element").swipe("enable"); */ this.enable = function () { $element.bind(START_EV, touchStart); $element.bind(CANCEL_EV, touchCancel); return $element; }; /** * disables the swipe plugin * @function * @name $.fn.swipe#disable * @return {DOMNode} The Dom element that is now registered with TouchSwipe * @example $("#element").swipe("disable"); */ this.disable = function () { removeListeners(); return $element; }; /** * Destroy the swipe plugin completely. To use any swipe methods, you must re initialise the plugin. * @function * @name $.fn.swipe#destroy * @return {DOMNode} The Dom element that was registered with TouchSwipe * @example $("#element").swipe("destroy"); */ this.destroy = function () { removeListeners(); $element.data(PLUGIN_NS, null); return $element; }; /** * Allows run time updating of the swipe configuration options. * @function * @name $.fn.swipe#option * @param {String} property The option property to get or set * @param {Object} [value] The value to set the property to * @return {Object} If only a property name is passed, then that property value is returned. * @example $("#element").swipe("option", "threshold"); // return the threshold * @example $("#element").swipe("option", "threshold", 100); // set the threshold after init * @see $.fn.swipe.defaults * */ this.option = function (property, value) { if(options[property]!==undefined) { if(value===undefined) { return options[property]; } else { options[property] = value; } } else { $.error('Option ' + property + ' does not exist on jQuery.swipe.options'); } } // // Private methods // // // EVENTS // /** * Event handler for a touch start event. * Stops the default click event from triggering and stores where we touched * @inner * @param {object} jqEvent The normalised jQuery event object. */ function touchStart(jqEvent) { //If we already in a touch event (a finger already in use) then ignore subsequent ones.. if( getTouchInProgress() ) return; //Check if this element matches any in the excluded elements selectors, or its parent is excluded, if so, DONT swipe if( $(jqEvent.target).closest( options.excludedElements, $element ).length>0 ) return; //As we use Jquery bind for events, we need to target the original event object //If these events are being programatically triggered, we dont have an orignal event object, so use the Jq one. var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent; var ret, evt = SUPPORTS_TOUCH ? event.touches[0] : event; phase = PHASE_START; //If we support touches, get the finger count if (SUPPORTS_TOUCH) { // get the total number of fingers touching the screen fingerCount = event.touches.length; } //Else this is the desktop, so stop the browser from dragging the image else { jqEvent.preventDefault(); //call this on jq event so we are cross browser } //clear vars.. distance = 0; direction = null; pinchDirection=null; duration = 0; startTouchesDistance=0; endTouchesDistance=0; pinchZoom = 1; pinchDistance = 0; fingerData=createAllFingerData(); maximumsMap=createMaximumsData(); cancelMultiFingerRelease(); // check the number of fingers is what we are looking for, or we are capturing pinches if (!SUPPORTS_TOUCH || (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || hasPinches()) { // get the coordinates of the touch createFingerData( 0, evt ); startTime = getTimeStamp(); if(fingerCount==2) { //Keep track of the initial pinch distance, so we can calculate the diff later //Store second finger data as start createFingerData( 1, event.touches[1] ); startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start); } if (options.swipeStatus || options.pinchStatus) { ret = triggerHandler(event, phase); } } else { //A touch with more or less than the fingers we are looking for, so cancel ret = false; } //If we have a return value from the users handler, then return and cancel if (ret === false) { phase = PHASE_CANCEL; triggerHandler(event, phase); return ret; } else { setTouchInProgress(true); } }; /** * Event handler for a touch move event. * If we change fingers during move, then cancel the event * @inner * @param {object} jqEvent The normalised jQuery event object. */ function touchMove(jqEvent) { //As we use Jquery bind for events, we need to target the original event object //If these events are being programatically triggered, we dont have an orignal event object, so use the Jq one. var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent; //If we are ending, cancelling, or within the threshold of 2 fingers being released, dont track anything.. if (phase === PHASE_END || phase === PHASE_CANCEL || inMultiFingerRelease()) return; var ret, evt = SUPPORTS_TOUCH ? event.touches[0] : event; //Update the finger data var currentFinger = updateFingerData(evt); endTime = getTimeStamp(); if (SUPPORTS_TOUCH) { fingerCount = event.touches.length; } phase = PHASE_MOVE; //If we have 2 fingers get Touches distance as well if(fingerCount==2) { //Keep track of the initial pinch distance, so we can calculate the diff later //We do this here as well as the start event, incase they start with 1 finger, and the press 2 fingers if(startTouchesDistance==0) { //Create second finger if this is the first time... createFingerData( 1, event.touches[1] ); startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start); } else { //Else just update the second finger updateFingerData(event.touches[1]); endTouchesDistance = calculateTouchesDistance(fingerData[0].end, fingerData[1].end); pinchDirection = calculatePinchDirection(fingerData[0].end, fingerData[1].end); } pinchZoom = calculatePinchZoom(startTouchesDistance, endTouchesDistance); pinchDistance = Math.abs(startTouchesDistance - endTouchesDistance); } if ( (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !SUPPORTS_TOUCH || hasPinches() ) { direction = calculateDirection(currentFinger.start, currentFinger.end); //Check if we need to prevent default evnet (page scroll / pinch zoom) or not validateDefaultEvent(jqEvent, direction); //Distance and duration are all off the main finger distance = calculateDistance(currentFinger.start, currentFinger.end); duration = calculateDuration(); //Cache the maximum distance we made in this direction setMaxDistance(direction, distance); if (options.swipeStatus || options.pinchStatus) { ret = triggerHandler(event, phase); } //If we trigger end events when threshold are met, or trigger events when touch leves element if(!options.triggerOnTouchEnd || options.triggerOnTouchLeave) { var inBounds = true; //If checking if we leave the element, run the bounds check (we can use touchleave as its not supported on webkit) if(options.triggerOnTouchLeave) { var bounds = getbounds( this ); inBounds = isInBounds( currentFinger.end, bounds ); } //Trigger end handles as we swipe if thresholds met or if we have left the element if the user has asked to check these.. if(!options.triggerOnTouchEnd && inBounds) { phase = getNextPhase( PHASE_MOVE ); } //We end if out of bounds here, so set current phase to END, and check if its modified else if(options.triggerOnTouchLeave && !inBounds ) { phase = getNextPhase( PHASE_END ); } if(phase==PHASE_CANCEL || phase==PHASE_END) { triggerHandler(event, phase); } } } else { phase = PHASE_CANCEL; triggerHandler(event, phase); } if (ret === false) { phase = PHASE_CANCEL; triggerHandler(event, phase); } } /** * Event handler for a touch end event. * Calculate the direction and trigger events * @inner * @param {object} jqEvent The normalised jQuery event object. */ function touchEnd(jqEvent) { //As we use Jquery bind for events, we need to target the original event object var event = jqEvent.originalEvent; //If we are still in a touch with another finger return //This allows us to wait a fraction and see if the other finger comes up, if it does within the threshold, then we treat it as a multi release, not a single release. if (SUPPORTS_TOUCH) { if(event.touches.length>0) { startMultiFingerRelease(); return true; } } //If a previous finger has been released, check how long ago, if within the threshold, then assume it was a multifinger release. //This is used to allow 2 fingers to release fractionally after each other, whilst maintainig the event as containg 2 fingers, not 1 if(inMultiFingerRelease()) { fingerCount=previousTouchFingerCount; } //call this on jq event so we are cross browser jqEvent.preventDefault(); //Set end of swipe endTime = getTimeStamp(); //Get duration incase move was never fired duration = calculateDuration(); //If we trigger handlers at end of swipe OR, we trigger during, but they didnt trigger and we are still in the move phase if(didSwipeBackToCancel()) { phase = PHASE_CANCEL; triggerHandler(event, phase); } else if (options.triggerOnTouchEnd || (options.triggerOnTouchEnd == false && phase === PHASE_MOVE)) { phase = PHASE_END; triggerHandler(event, phase); } //Special cases - A tap should always fire on touch end regardless, //So here we manually trigger the tap end handler by itself //We dont run trigger handler as it will re-trigger events that may have fired already else if (!options.triggerOnTouchEnd && hasTap()) { //Trigger the pinch events... phase = PHASE_END; triggerHandlerForGesture(event, phase, TAP); } else if (phase === PHASE_MOVE) { phase = PHASE_CANCEL; triggerHandler(event, phase); } setTouchInProgress(false); } /** * Event handler for a touch cancel event. * Clears current vars * @inner */ function touchCancel() { // reset the variables back to default values fingerCount = 0; endTime = 0; startTime = 0; startTouchesDistance=0; endTouchesDistance=0; pinchZoom=1; //If we were in progress of tracking a possible multi touch end, then re set it. cancelMultiFingerRelease(); setTouchInProgress(false); } /** * Event handler for a touch leave event. * This is only triggered on desktops, in touch we work this out manually * as the touchleave event is not supported in webkit * @inner */ function touchLeave(jqEvent) { var event = jqEvent.originalEvent; //If we have the trigger on leve property set.... if(options.triggerOnTouchLeave) { phase = getNextPhase( PHASE_END ); triggerHandler(event, phase); } } /** * Removes all listeners that were associated with the plugin * @inner */ function removeListeners() { $element.unbind(START_EV, touchStart); $element.unbind(CANCEL_EV, touchCancel); $element.unbind(MOVE_EV, touchMove); $element.unbind(END_EV, touchEnd); //we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit if(LEAVE_EV) { $element.unbind(LEAVE_EV, touchLeave); } setTouchInProgress(false); } /** * Checks if the time and distance thresholds have been met, and if so then the appropriate handlers are fired. */ function getNextPhase(currentPhase) { var nextPhase = currentPhase; // Ensure we have valid swipe (under time and over distance and check if we are out of bound...) var validTime = validateSwipeTime(); var validDistance = validateSwipeDistance(); var didCancel = didSwipeBackToCancel(); //If we have exceeded our time, then cancel if(!validTime || didCancel) { nextPhase = PHASE_CANCEL; } //Else if we are moving, and have reached distance then end else if (validDistance && currentPhase == PHASE_MOVE && (!options.triggerOnTouchEnd || options.triggerOnTouchLeave) ) { nextPhase = PHASE_END; } //Else if we have ended by leaving and didnt reach distance, then cancel else if (!validDistance && currentPhase==PHASE_END && options.triggerOnTouchLeave) { nextPhase = PHASE_CANCEL; } return nextPhase; } /** * Trigger the relevant event handler * The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down" * @param {object} event the original event object * @param {string} phase the phase of the swipe (start, end cancel etc) {@link $.fn.swipe.phases} * @inner */ function triggerHandler(event, phase) { var ret = undefined; // SWIPE GESTURES if(didSwipe() || hasSwipes()) { //hasSwipes as status needs to fire even if swipe is invalid //Trigger the swipe events... ret = triggerHandlerForGesture(event, phase, SWIPE); } // PINCH GESTURES (if the above didnt cancel) else if((didPinch() || hasPinches()) && ret!==false) { //Trigger the pinch events... ret = triggerHandlerForGesture(event, phase, PINCH); } // CLICK / TAP (if the above didnt cancel) if(didDoubleTap() && ret!==false) { //Trigger the tap events... ret = triggerHandlerForGesture(event, phase, DOUBLE_TAP); } // CLICK / TAP (if the above didnt cancel) else if(didLongTap() && ret!==false) { //Trigger the tap events... ret = triggerHandlerForGesture(event, phase, LONG_TAP); } // CLICK / TAP (if the above didnt cancel) else if(didTap() && ret!==false) { //Trigger the tap event.. ret = triggerHandlerForGesture(event, phase, TAP); } // If we are cancelling the gesture, then manually trigger the reset handler if (phase === PHASE_CANCEL) { touchCancel(event); } // If we are ending the gesture, then manually trigger the reset handler IF all fingers are off if(phase === PHASE_END) { //If we support touch, then check that all fingers are off before we cancel if (SUPPORTS_TOUCH) { if(event.touches.length==0) { touchCancel(event); } } else { touchCancel(event); } } return ret; } /** * Trigger the relevant event handler * The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down" * @param {object} event the original event object * @param {string} phase the phase of the swipe (start, end cancel etc) {@link $.fn.swipe.phases} * @param {string} gesture the gesture to triger a handler for : PINCH or SWIPE {@link $.fn.swipe.gestures} * @return Boolean False, to indicate that the event should stop propagation, or void. * @inner */ function triggerHandlerForGesture(event, phase, gesture) { var ret=undefined; //SWIPES.... if(gesture==SWIPE) { //Trigger status every time.. //Trigger the event... $element.trigger('swipeStatus', [phase, direction || null, distance || 0, duration || 0, fingerCount]); //Fire the callback if (options.swipeStatus) { ret = options.swipeStatus.call($element, event, phase, direction || null, distance || 0, duration || 0, fingerCount); //If the status cancels, then dont run the subsequent event handlers.. if(ret===false) return false; } if (phase == PHASE_END && validateSwipe()) { //Fire the catch all event $element.trigger('swipe', [direction, distance, duration, fingerCount]); //Fire catch all callback if (options.swipe) { ret = options.swipe.call($element, event, direction, distance, duration, fingerCount); //If the status cancels, then dont run the subsequent event handlers.. if(ret===false) return false; } //trigger direction specific event handlers switch (direction) { case LEFT: //Trigger the event $element.trigger('swipeLeft', [direction, distance, duration, fingerCount]); //Fire the callback if (options.swipeLeft) { ret = options.swipeLeft.call($element, event, direction, distance, duration, fingerCount); } break; case RIGHT: //Trigger the event $element.trigger('swipeRight', [direction, distance, duration, fingerCount]); //Fire the callback if (options.swipeRight) { ret = options.swipeRight.call($element, event, direction, distance, duration, fingerCount); } break; case UP: //Trigger the event $element.trigger('swipeUp', [direction, distance, duration, fingerCount]); //Fire the callback if (options.swipeUp) { ret = options.swipeUp.call($element, event, direction, distance, duration, fingerCount); } break; case DOWN: //Trigger the event $element.trigger('swipeDown', [direction, distance, duration, fingerCount]); //Fire the callback if (options.swipeDown) { ret = options.swipeDown.call($element, event, direction, distance, duration, fingerCount); } break; } } } //PINCHES.... if(gesture==PINCH) { //Trigger the event $element.trigger('pinchStatus', [phase, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom]); //Fire the callback if (options.pinchStatus) { ret = options.pinchStatus.call($element, event, phase, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom); //If the status cancels, then dont run the subsequent event handlers.. if(ret===false) return false; } if(phase==PHASE_END && validatePinch()) { switch (pinchDirection) { case IN: //Trigger the event $element.trigger('pinchIn', [pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom]); //Fire the callback if (options.pinchIn) { ret = options.pinchIn.call($element, event, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom); } break; case OUT: //Trigger the event $element.trigger('pinchOut', [pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom]); //Fire the callback if (options.pinchOut) { ret = options.pinchOut.call($element, event, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom); } break; } } } if(gesture==TAP) { if(phase === PHASE_CANCEL || phase === PHASE_END) { //Cancel any existing double tap clearTimeout(singleTapTimeout); //If we are also looking for doubelTaps, wait incase this is one... if(hasDoubleTap() && !inDoubleTap()) { //Cache the time of this tap doubleTapStartTime = getTimeStamp(); //Now wait for the double tap timeout, and trigger this single tap //if its not cancelled by a double tap singleTapTimeout = setTimeout($.proxy(function() { doubleTapStartTime=null; //Trigger the event $element.trigger('tap', [event.target]); //Fire the callback if(options.tap) { ret = options.tap.call($element, event, event.target); } }, this), options.doubleTapThreshold ); } else { doubleTapStartTime=null; //Trigger the event $element.trigger('tap', [event.target]); //Fire the callback if(options.tap) { ret = options.tap.call($element, event, event.target); } } } } else if (gesture==DOUBLE_TAP) { if(phase === PHASE_CANCEL || phase === PHASE_END) { //Cancel any pending singletap clearTimeout(singleTapTimeout); doubleTapStartTime=null; //Trigger the event $element.trigger('doubletap', [event.target]); //Fire the callback if(options.doubleTap) { ret = options.doubleTap.call($element, event, event.target); } } } else if (gesture==LONG_TAP) { if(phase === PHASE_CANCEL || phase === PHASE_END) { //Cancel any pending singletap (shouldnt be one) clearTimeout(singleTapTimeout); doubleTapStartTime=null; //Trigger the event $element.trigger('longtap', [event.target]); //Fire the callback if(options.longTap) { ret = options.longTap.call($element, event, event.target); } } } return ret; } // // GESTURE VALIDATION // /** * Checks the user has swipe far enough * @return Boolean if <code>threshold</code> has been set, return true if the threshold was met, else false. * If no threshold was set, then we return true. * @inner */ function validateSwipeDistance() { var valid = true; //If we made it past the min swipe distance.. if (options.threshold !== null) { valid = distance >= options.threshold; } return valid; } /** * Checks the user has swiped back to cancel. * @return Boolean if <code>cancelThreshold</code> has been set, return true if the cancelThreshold was met, else false. * If no cancelThreshold was set, then we return true. * @inner */ function didSwipeBackToCancel() { var cancelled = false; if(options.cancelThreshold !== null && direction !==null) { cancelled = (getMaxDistance( direction ) - distance) >= options.cancelThreshold; } return cancelled; } /** * Checks the user has pinched far enough * @return Boolean if <code>pinchThreshold</code> has been set, return true if the threshold was met, else false. * If no threshold was set, then we return true. * @inner */ function validatePinchDistance() { if (options.pinchThreshold !== null) { return pinchDistance >= options.pinchThreshold; } return true; } /** * Checks that the time taken to swipe meets the minimum / maximum requirements * @return Boolean * @inner */ function validateSwipeTime() { var result; //If no time set, then return true if (options.maxTimeThreshold) { if (duration >= options.maxTimeThreshold) { result = false; } else { result = true; } } else { result = true; } return result; } /** * Checks direction of the swipe and the value allowPageScroll to see if we should allow or prevent the default behaviour from occurring. * This will essentially allow page scrolling or not when the user is swiping on a touchSwipe object. * @param {object} jqEvent The normalised jQuery representation of the event object. * @param {string} direction The direction of the event. See {@link $.fn.swipe.directions} * @see $.fn.swipe.directions * @inner */ function validateDefaultEvent(jqEvent, direction) { if (options.allowPageScroll === NONE || hasPinches()) { jqEvent.preventDefault(); } else { var auto = options.allowPageScroll === AUTO; switch (direction) { case LEFT: if ((options.swipeLeft && auto) || (!auto && options.allowPageScroll != HORIZONTAL)) { jqEvent.preventDefault(); } break; case RIGHT: if ((options.swipeRight && auto) || (!auto && options.allowPageScroll != HORIZONTAL)) { jqEvent.preventDefault(); } break; case UP: if ((options.swipeUp && auto) || (!auto && options.allowPageScroll != VERTICAL)) { jqEvent.preventDefault(); } break; case DOWN: if ((options.swipeDown && auto) || (!auto && options.allowPageScroll != VERTICAL)) { jqEvent.preventDefault(); } break; } } } // PINCHES /** * Returns true of the current pinch meets the thresholds * @return Boolean * @inner */ function validatePinch() { var hasCorrectFingerCount = validateFingers(); var hasEndPoint = validateEndPoint(); var hasCorrectDistance = validatePinchDistance(); return hasCorrectFingerCount && hasEndPoint && hasCorrectDistance; } /** * Returns true if any Pinch events have been registered * @return Boolean * @inner */ function hasPinches() { //Enure we dont return 0 or null for false values return !!(options.pinchStatus || options.pinchIn || options.pinchOut); } /** * Returns true if we are detecting pinches, and have one * @return Boolean * @inner */ function didPinch() { //Enure we dont return 0 or null for false values return !!(validatePinch() && hasPinches()); } // SWIPES /** * Returns true if the current swipe meets the thresholds * @return Boolean * @inner */ function validateSwipe() { //Check validity of swipe var hasValidTime = validateSwipeTime(); var hasValidDistance = validateSwipeDistance(); var hasCorrectFingerCount = validateFingers(); var hasEndPoint = validateEndPoint(); var didCancel = didSwipeBackToCancel(); // if the user swiped more than the minimum length, perform the appropriate action // hasValidDistance is null when no distance is set var valid = !didCancel && hasEndPoint && hasCorrectFingerCount && hasValidDistance && hasValidTime; return valid; } /** * Returns true if any Swipe events have been registered * @return Boolean * @inner */ function hasSwipes() { //Enure we dont return 0 or null for false values return !!(options.swipe || options.swipeStatus || options.swipeLeft || options.swipeRight || options.swipeUp || options.swipeDown); } /** * Returns true if we are detecting swipes and have one * @return Boolean * @inner */ function didSwipe() { //Enure we dont return 0 or null for false values return !!(validateSwipe() && hasSwipes()); } /** * Returns true if we have matched the number of fingers we are looking for * @return Boolean * @inner */ function validateFingers() { //The number of fingers we want were matched, or on desktop we ignore return ((fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !SUPPORTS_TOUCH); } /** * Returns true if we have an end point for the swipe * @return Boolean * @inner */ function validateEndPoint() { //We have an end value for the finger return fingerData[0].end.x !== 0; } // TAP / CLICK /** * Returns true if a click / tap events have been registered * @return Boolean * @inner */ function hasTap() { //Enure we dont return 0 or null for false values return !!(options.tap) ; } /** * Returns true if a double tap events have been registered * @return Boolean * @inner */ function hasDoubleTap() { //Enure we dont return 0 or null for false values return !!(options.doubleTap) ; } /** * Returns true if any long tap events have been registered * @return Boolean * @inner */ function hasLongTap() { //Enure we dont return 0 or null for false values return !!(options.longTap) ; } /** * Returns true if we could be in the process of a double tap (one tap has occurred, we are listening for double taps, and the threshold hasn't past. * @return Boolean * @inner */ function validateDoubleTap() { if(doubleTapStartTime==null){ return false; } var now = getTimeStamp(); return (hasDoubleTap() && ((now-doubleTapStartTime) <= options.doubleTapThreshold)); } /** * Returns true if we could be in the process of a double tap (one tap has occurred, we are listening for double taps, and the threshold hasn't past. * @return Boolean * @inner */ function inDoubleTap() { return validateDoubleTap(); } /** * Returns true if we have a valid tap * @return Boolean * @inner */ function validateTap() { return ((fingerCount === 1 || !SUPPORTS_TOUCH) && (isNaN(distance) || distance === 0)); } /** * Returns true if we have a valid long tap * @return Boolean * @inner */ function validateLongTap() { //slight threshold on moving finger return ((duration > options.longTapThreshold) && (distance < DOUBLE_TAP_THRESHOLD)); } /** * Returns true if we are detecting taps and have one * @return Boolean * @inner */ function didTap() { //Enure we dont return 0 or null for false values return !!(validateTap() && hasTap()); } /** * Returns true if we are detecting double taps and have one * @return Boolean * @inner */ function didDoubleTap() { //Enure we dont return 0 or null for false values return !!(validateDoubleTap() && hasDoubleTap()); } /** * Returns true if we are detecting long taps and have one * @return Boolean * @inner */ function didLongTap() { //Enure we dont return 0 or null for false values return !!(validateLongTap() && hasLongTap()); } // MULTI FINGER TOUCH /** * Starts tracking the time between 2 finger releases, and keeps track of how many fingers we initially had up * @inner */ function startMultiFingerRelease() { previousTouchEndTime = getTimeStamp(); previousTouchFingerCount = event.touches.length+1; } /** * Cancels the tracking of time between 2 finger releases, and resets counters * @inner */ function cancelMultiFingerRelease() { previousTouchEndTime = 0; previousTouchFingerCount = 0; } /** * Checks if we are in the threshold between 2 fingers being released * @return Boolean * @inner */ function inMultiFingerRelease() { var withinThreshold = false; if(previousTouchEndTime) { var diff = getTimeStamp() - previousTouchEndTime if( diff<=options.fingerReleaseThreshold ) { withinThreshold = true; } } return withinThreshold; } /** * gets a data flag to indicate that a touch is in progress * @return Boolean * @inner */ function getTouchInProgress() { //strict equality to ensure only true and false are returned return !!($element.data(PLUGIN_NS+'_intouch') === true); } /** * Sets a data flag to indicate that a touch is in progress * @param {boolean} val The value to set the property to * @inner */ function setTouchInProgress(val) { //Add or remove event listeners depending on touch status if(val===true) { $element.bind(MOVE_EV, touchMove); $element.bind(END_EV, touchEnd); //we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit if(LEAVE_EV) { $element.bind(LEAVE_EV, touchLeave); } } else { $element.unbind(MOVE_EV, touchMove, false); $element.unbind(END_EV, touchEnd, false); //we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit if(LEAVE_EV) { $element.unbind(LEAVE_EV, touchLeave, false); } } //strict equality to ensure only true and false can update the value $element.data(PLUGIN_NS+'_intouch', val === true); } /** * Creates the finger data for the touch/finger in the event object. * @param {int} index The index in the array to store the finger data (usually the order the fingers were pressed) * @param {object} evt The event object containing finger data * @return finger data object * @inner */ function createFingerData( index, evt ) { var id = evt.identifier!==undefined ? evt.identifier : 0; fingerData[index].identifier = id; fingerData[index].start.x = fingerData[index].end.x = evt.pageX||evt.clientX; fingerData[index].start.y = fingerData[index].end.y = evt.pageY||evt.clientY; return fingerData[index]; } /** * Updates the finger data for a particular event object * @param {object} evt The event object containing the touch/finger data to upadte * @return a finger data object. * @inner */ function updateFingerData(evt) { var id = evt.identifier!==undefined ? evt.identifier : 0; var f = getFingerData( id ); f.end.x = evt.pageX||evt.clientX; f.end.y = evt.pageY||evt.clientY; return f; } /** * Returns a finger data object by its event ID. * Each touch event has an identifier property, which is used * to track repeat touches * @param {int} id The unique id of the finger in the sequence of touch events. * @return a finger data object. * @inner */ function getFingerData( id ) { for(var i=0; i<fingerData.length; i++) { if(fingerData[i].identifier == id) { return fingerData[i]; } } } /** * Creats all the finger onjects and returns an array of finger data * @return Array of finger objects * @inner */ function createAllFingerData() { var fingerData=[]; for (var i=0; i<=5; i++) { fingerData.push({ start:{ x: 0, y: 0 }, end:{ x: 0, y: 0 }, identifier:0 }); } return fingerData; } /** * Sets the maximum distance swiped in the given direction. * If the new value is lower than the current value, the max value is not changed. * @param {string} direction The direction of the swipe * @param {int} distance The distance of the swipe * @inner */ function setMaxDistance(direction, distance) { distance = Math.max(distance, getMaxDistance(direction) ); maximumsMap[direction].distance = distance; } /** * gets the maximum distance swiped in the given direction. * @param {string} direction The direction of the swipe * @return int The distance of the swipe * @inner */ function getMaxDistance(direction) { return maximumsMap[direction].distance; } /** * Creats a map of directions to maximum swiped values. * @return Object A dictionary of maximum values, indexed by direction. * @inner */ function createMaximumsData() { var maxData={}; maxData[LEFT]=createMaximumVO(LEFT); maxData[RIGHT]=createMaximumVO(RIGHT); maxData[UP]=createMaximumVO(UP); maxData[DOWN]=createMaximumVO(DOWN); return maxData; } /** * Creates a map maximum swiped values for a given swipe direction * @param {string} The direction that these values will be associated with * @return Object Maximum values * @inner */ function createMaximumVO(dir) { return { direction:dir, distance:0 } } // // MATHS / UTILS // /** * Calculate the duration of the swipe * @return int * @inner */ function calculateDuration() { return endTime - startTime; } /** * Calculate the distance between 2 touches (pinch) * @param {point} startPoint A point object containing x and y co-ordinates * @param {point} endPoint A point object containing x and y co-ordinates * @return int; * @inner */ function calculateTouchesDistance(startPoint, endPoint) { var diffX = Math.abs(startPoint.x - endPoint.x); var diffY = Math.abs(startPoint.y - endPoint.y); return Math.round(Math.sqrt(diffX*diffX+diffY*diffY)); } /** * Calculate the zoom factor between the start and end distances * @param {int} startDistance Distance (between 2 fingers) the user started pinching at * @param {int} endDistance Distance (between 2 fingers) the user ended pinching at * @return float The zoom value from 0 to 1. * @inner */ function calculatePinchZoom(startDistance, endDistance) { var percent = (endDistance/startDistance) * 1; return percent.toFixed(2); } /** * Returns the pinch direction, either IN or OUT for the given points * @return string Either {@link $.fn.swipe.directions.IN} or {@link $.fn.swipe.directions.OUT} * @see $.fn.swipe.directions * @inner */ function calculatePinchDirection() { if(pinchZoom<1) { return OUT; } else { return IN; } } /** * Calculate the length / distance of the swipe * @param {point} startPoint A point object containing x and y co-ordinates * @param {point} endPoint A point object containing x and y co-ordinates * @return int * @inner */ function calculateDistance(startPoint, endPoint) { return Math.round(Math.sqrt(Math.pow(endPoint.x - startPoint.x, 2) + Math.pow(endPoint.y - startPoint.y, 2))); } /** * Calculate the angle of the swipe * @param {point} startPoint A point object containing x and y co-ordinates * @param {point} endPoint A point object containing x and y co-ordinates * @return int * @inner */ function calculateAngle(startPoint, endPoint) { var x = startPoint.x - endPoint.x; var y = endPoint.y - startPoint.y; var r = Math.atan2(y, x); //radians var angle = Math.round(r * 180 / Math.PI); //degrees //ensure value is positive if (angle < 0) { angle = 360 - Math.abs(angle); } return angle; } /** * Calculate the direction of the swipe * This will also call calculateAngle to get the latest angle of swipe * @param {point} startPoint A point object containing x and y co-ordinates * @param {point} endPoint A point object containing x and y co-ordinates * @return string Either {@link $.fn.swipe.directions.LEFT} / {@link $.fn.swipe.directions.RIGHT} / {@link $.fn.swipe.directions.DOWN} / {@link $.fn.swipe.directions.UP} * @see $.fn.swipe.directions * @inner */ function calculateDirection(startPoint, endPoint ) { var angle = calculateAngle(startPoint, endPoint); if ((angle <= 45) && (angle >= 0)) { return LEFT; } else if ((angle <= 360) && (angle >= 315)) { return LEFT; } else if ((angle >= 135) && (angle <= 225)) { return RIGHT; } else if ((angle > 45) && (angle < 135)) { return DOWN; } else { return UP; } } /** * Returns a MS time stamp of the current time * @return int * @inner */ function getTimeStamp() { var now = new Date(); return now.getTime(); } /** * Returns a bounds object with left, right, top and bottom properties for the element specified. * @param {DomNode} The DOM node to get the bounds for. */ function getbounds( el ) { el = $(el); var offset = el.offset(); var bounds = { left:offset.left, right:offset.left+el.outerWidth(), top:offset.top, bottom:offset.top+el.outerHeight() } return bounds; } /** * Checks if the point object is in the bounds object. * @param {object} point A point object. * @param {int} point.x The x value of the point. * @param {int} point.y The x value of the point. * @param {object} bounds The bounds object to test * @param {int} bounds.left The leftmost value * @param {int} bounds.right The righttmost value * @param {int} bounds.top The topmost value * @param {int} bounds.bottom The bottommost value */ function isInBounds(point, bounds) { return (point.x > bounds.left && point.x < bounds.right && point.y > bounds.top && point.y < bounds.bottom); }; } /** * A catch all handler that is triggered for all swipe directions. * @name $.fn.swipe#swipe * @event * @default null * @param {EventObject} event The original event object * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions} * @param {int} distance The distance the user swiped * @param {int} duration The duration of the swipe in milliseconds * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers} */ /** * A handler that is triggered for "left" swipes. * @name $.fn.swipe#swipeLeft * @event * @default null * @param {EventObject} event The original event object * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions} * @param {int} distance The distance the user swiped * @param {int} duration The duration of the swipe in milliseconds * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers} */ /** * A handler that is triggered for "right" swipes. * @name $.fn.swipe#swipeRight * @event * @default null * @param {EventObject} event The original event object * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions} * @param {int} distance The distance the user swiped * @param {int} duration The duration of the swipe in milliseconds * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers} */ /** * A handler that is triggered for "up" swipes. * @name $.fn.swipe#swipeUp * @event * @default null * @param {EventObject} event The original event object * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions} * @param {int} distance The distance the user swiped * @param {int} duration The duration of the swipe in milliseconds * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers} */ /** * A handler that is triggered for "down" swipes. * @name $.fn.swipe#swipeDown * @event * @default null * @param {EventObject} event The original event object * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions} * @param {int} distance The distance the user swiped * @param {int} duration The duration of the swipe in milliseconds * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers} */ /** * A handler triggered for every phase of the swipe. This handler is constantly fired for the duration of the pinch. * This is triggered regardless of swipe thresholds. * @name $.fn.swipe#swipeStatus * @event * @default null * @param {EventObject} event The original event object * @param {string} phase The phase of the swipe event. See {@link $.fn.swipe.phases} * @param {string} direction The direction the user swiped in. This is null if the user has yet to move. See {@link $.fn.swipe.directions} * @param {int} distance The distance the user swiped. This is 0 if the user has yet to move. * @param {int} duration The duration of the swipe in milliseconds * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers} */ /** * A handler triggered for pinch in events. * @name $.fn.swipe#pinchIn * @event * @default null * @param {EventObject} event The original event object * @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions} * @param {int} distance The distance the user pinched * @param {int} duration The duration of the swipe in milliseconds * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers} * @param {int} zoom The zoom/scale level the user pinched too, 0-1. */ /** * A handler triggered for pinch out events. * @name $.fn.swipe#pinchOut * @event * @default null * @param {EventObject} event The original event object * @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions} * @param {int} distance The distance the user pinched * @param {int} duration The duration of the swipe in milliseconds * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers} * @param {int} zoom The zoom/scale level the user pinched too, 0-1. */ /** * A handler triggered for all pinch events. This handler is constantly fired for the duration of the pinch. This is triggered regardless of thresholds. * @name $.fn.swipe#pinchStatus * @event * @default null * @param {EventObject} event The original event object * @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions} * @param {int} distance The distance the user pinched * @param {int} duration The duration of the swipe in milliseconds * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers} * @param {int} zoom The zoom/scale level the user pinched too, 0-1. */ /** * A click handler triggered when a user simply clicks, rather than swipes on an element. * This is deprecated since version 1.6.2, any assignment to click will be assigned to the tap handler. * You cannot use <code>on</code> to bind to this event as the default jQ <code>click</code> event will be triggered. * Use the <code>tap</code> event instead. * @name $.fn.swipe#click * @event * @deprecated since version 1.6.2, please use {@link $.fn.swipe#tap} instead * @default null * @param {EventObject} event The original event object * @param {DomObject} target The element clicked on. */ /** * A click / tap handler triggered when a user simply clicks or taps, rather than swipes on an element. * @name $.fn.swipe#tap * @event * @default null * @param {EventObject} event The original event object * @param {DomObject} target The element clicked on. */ /** * A double tap handler triggered when a user double clicks or taps on an element. * You can set the time delay for a double tap with the {@link $.fn.swipe.defaults#doubleTapThreshold} property. * Note: If you set both <code>doubleTap</code> and <code>tap</code> handlers, the <code>tap</code> event will be delayed by the <code>doubleTapThreshold</code> * as the script needs to check if its a double tap. * @name $.fn.swipe#doubleTap * @see $.fn.swipe.defaults#doubleTapThreshold * @event * @default null * @param {EventObject} event The original event object * @param {DomObject} target The element clicked on. */ /** * A long tap handler triggered when a user long clicks or taps on an element. * You can set the time delay for a long tap with the {@link $.fn.swipe.defaults#longTapThreshold} property. * @name $.fn.swipe#longTap * @see $.fn.swipe.defaults#longTapThreshold * @event * @default null * @param {EventObject} event The original event object * @param {DomObject} target The element clicked on. */ })(jQuery);
JavaScript
/** * @package Joomla.Installation * @subpackage JavaScript * @copyright Copyright (C) 2005 - 2012 Open Source Matters. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ var Installation = new Class({ initialize: function(container, base) { this.sampleDataLoaded = false; this.busy = false; this.container = container; this.spinner = new Spinner(this.container); this.baseUrl = base; this.view = ''; this.pageInit(); }, pageInit: function() { this.addToggler(); // Attach the validator $$('form.form-validate').each(function(form){ this.attachToForm(form); }, document.formvalidator); if (this.view == 'site' && this.sampleDataLoaded) { var select = document.id('jform_sample_file'); var button = document.id('theDefault').children[0]; button.setAttribute('disabled', 'disabled'); select.setAttribute('disabled', 'disabled'); button.setAttribute('value', Locale.get('installation.sampleDataLoaded')); } }, submitform: function() { var form = document.id('adminForm'); if (this.busy) { return false; } var req = new Request.JSON({ method: 'post', url: this.baseUrl, onRequest: function() { this.spinner.show(true); this.busy = true; Joomla.removeMessages(); }.bind(this), onSuccess: function(r) { Joomla.replaceTokens(r.token); if (r.messages) { Joomla.renderMessages(r.messages); } var lang = $$('html').getProperty('lang')[0]; if (lang.toLowerCase() === r.lang.toLowerCase()) { Install.goToPage(r.data.view, true); } else { window.location = this.baseUrl+'?view='+r.data.view; } }.bind(this), onFailure: function(xhr) { this.spinner.hide(true); this.busy = false; var r = JSON.decode(xhr.responseText); if (r) { Joomla.replaceTokens(r.token); alert(r.message); } }.bind(this) }); req.post(form.toQueryString()+'&task='+form.task.value+'&format=json'); return false; }, goToPage: function(page, fromSubmit) { var url = this.baseUrl+'?tmpl=body&view='+page; var req = new Request.HTML({ method: 'get', url: url, onRequest: function() { if (!fromSubmit) { Joomla.removeMessages(); this.spinner.show(true); } }.bind(this), onSuccess: function (r) { this.view = page; document.id(this.container).empty().adopt(r); // Attach JS behaviors to the newly loaded HTML this.pageInit(); this.spinner.hide(true); this.busy = false; //Take care of the sidebar var active = $$('.active'); active.removeClass('active'); var nextStep = document.id(page); nextStep.addClass('active'); }.bind(this) }).send(); return false; }, /** * Method to install sample data via AJAX request. */ sampleData: function(el, filename) { el = document.id(el); filename = document.id(filename); var req = new Request.JSON({ method: 'get', url: 'index.php?'+document.id(el.form).toQueryString(), data: {'task':'setup.loadSampleData', 'format':'json'}, onRequest: function() { el.set('disabled', 'disabled'); filename.set('disabled', 'disabled'); document.id('theDefaultError').setStyle('display','none'); }, onSuccess: function(r) { if (r) { Joomla.replaceTokens(r.token); this.sampleDataLoaded = r.data.sampleDataLoaded; if (r.error == false) { el.set('value', Locale.get('installation.sampleDataLoaded')); el.set('onclick',''); el.set('disabled', 'disabled'); filename.set('disabled', 'disabled'); document.id('jform_sample_installed').set('value','1'); } else { document.id('theDefaultError').setStyle('display','block'); document.id('theDefaultErrorMessage').set('html', r.message); el.set('disabled', ''); filename.set('disabled', ''); } } else { document.id('theDefaultError').setStyle('display','block'); document.id('theDefaultErrorMessage').set('html', response ); el.set('disabled', 'disabled'); filename.set('disabled', 'disabled'); } }.bind(this), onFailure: function(xhr) { var r = JSON.decode(xhr.responseText); if (r) { Joomla.replaceTokens(r.token); document.id('theDefaultError').setStyle('display','block'); document.id('theDefaultErrorMessage').set('html', r.message); } el.set('disabled', ''); filename.set('disabled', ''); } }).send(); }, /** * Method to detect the FTP root via AJAX request. */ detectFtpRoot: function(el) { el = document.id(el); var req = new Request.JSON({ method: 'get', url: 'index.php?'+document.id(el.form).toQueryString(), data: {'task':'setup.detectFtpRoot', 'format':'json'}, onRequest: function() { el.set('disabled', 'disabled'); }, onFailure: function(xhr) { var r = JSON.decode(xhr.responseText); if (r) { Joomla.replaceTokens(r.token) alert(xhr.status+': '+r.message); } else { alert(xhr.status+': '+xhr.statusText); } }, onSuccess: function(r) { if (r) { Joomla.replaceTokens(r.token) if (r.error == false) { document.id('jform_ftp_root').set('value', r.data.root); } else { alert(r.message); } } el.set('disabled', ''); } }).send(); }, verifyFtpSettings: function(el) { // make the ajax call el = document.id(el); var req = new Request.JSON({ method: 'get', url: 'index.php?'+document.id(el.form).toQueryString(), data: {'task':'setup.verifyFtpSettings', 'format':'json'}, onRequest: function() { el.set('disabled', 'disabled'); }, onFailure: function(xhr) { var r = JSON.decode(xhr.responseText); if (r) { Joomla.replaceTokens(r.token) alert(xhr.status+': '+r.message); } else { alert(xhr.status+': '+xhr.statusText); } }, onSuccess: function(r) { if (r) { Joomla.replaceTokens(r.token) if (r.error == false) { alert(Joomla.JText._('INSTL_FTP_SETTINGS_CORRECT')); } else { alert(r.message); } } el.set('disabled', ''); }, onError: function(response) { alert('error'); } }).send(); }, /** * Method to remove the installation Folder after a successful installation. */ removeFolder: function(el) { el = document.id(el); var req = new Request.JSON({ method: 'get', url: 'index.php?'+document.id(el.form).toQueryString(), data: {'task':'setup.removeFolder', 'format':'json'}, onRequest: function() { el.set('disabled', 'disabled'); document.id('theDefaultError').setStyle('display','none'); }, onComplete: function(r) { if (r) { Joomla.replaceTokens(r.token); if (r.error == false) { el.set('value', r.data.text); el.set('onclick',''); el.set('disabled', 'disabled'); } else { document.id('theDefaultError').setStyle('display','block'); document.id('theDefaultErrorMessage').set('html', r.message); el.set('disabled', ''); } } else { document.id('theDefaultError').setStyle('display','block'); document.id('theDefaultErrorMessage').set('html', response ); el.set('disabled', 'disabled'); } }, onFailure: function(xhr) { var r = JSON.decode(xhr.responseText); if (r) { Joomla.replaceTokens(r.token); document.id('theDefaultError').setStyle('display','block'); document.id('theDefaultErrorMessage').set('html', r.message); } el.set('disabled', ''); } }).send(); }, addToggler: function() { new Fx.Accordion($$('h4.moofx-toggler'), $$('div.moofx-slider'), { onActive: function(toggler, i) { toggler.addClass('moofx-toggler-down'); }, onBackground: function(toggler, i) { toggler.removeClass('moofx-toggler-down'); }, duration: 300, opacity: false, alwaysHide:true, show: 1 }); } });
JavaScript
/** * @package Joomla.Administrator * @subpackage templates.bluestork * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ var Joomla = Joomla || {}; /** * Joomla Menu javascript behavior */ Joomla.Menu = new Class({ Implements: [Options], options: { disabled: false }, initialize: function(element, options) { this.setOptions(options); this.element = document.id(element); // equalize width of the child LI elements this.element.getElements('li').filter('.node').getElement('ul').each(this._equalizeWidths); if (!this.options.disabled) { this._addMouseEvents(); } this.element.store('menu', this); }, disable: function() { var elements = this.element.getElements('li'); $$(this.element, elements).addClass('disabled'); elements.removeEvents('mouseenter').removeEvents('mouseleave'); }, enable: function() { $$(this.element, this.element.getElements('li')).removeClass('disabled'); this._addMouseEvents(); }, _addMouseEvents: function() { this.element.getElements('li') .removeEvents('mouseenter') .removeEvents('mouseleave') .addEvents({ 'mouseenter': function() { var ul = this.getElement('ul'); if (ul) { ul.fireEvent('show'); } this.addClass('hover'); }, 'mouseleave': function() { var ul = this.getElement('ul'); if (ul) { ul.fireEvent('hide'); } this.removeClass('hover'); } }); }, _equalizeWidths: function(el) { var offsetWidth = 0; var children = el.getElements('li'); //find longest child children.each(function(node) { offsetWidth = (offsetWidth >= node.offsetWidth) ? offsetWidth : node.offsetWidth; }); $$(children, el).setStyle('width', offsetWidth); } }); window.addEvent('domready', function() { var el = document.id('menu'); new Joomla.Menu(el, (el.hasClass('disabled') ? {disabled: true} : {})); });
JavaScript
/** * @package Hathor * @copyright Copyright (C) 2005 - 2009 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * Functions */ /** * Set focus to username on the login screen */ function setFocus() { if (document.id("login-page")) { document.id("form-login").username.select(); document.id("form-login").username.focus(); } } /** * Change the skip nav target to work with webkit browsers (Safari/Chrome) and * Opera */ function setSkip() { if (Browser.Engine.webkit || Browser.opera) { var target = document.id('skiptarget'); target.href = "#skiptarget"; target.innerText = "Start of main content"; target.setAttribute("tabindex", "0"); document.id('skiplink').setAttribute("onclick", "document.id('skiptarget').focus();"); } } /** * Set the Aria Role based on the id * * @param id * @param rolevalue * @return */ function setRoleAttribute(id, rolevalue) { if (document.id(id)) { document.id(id).setAttribute("role", rolevalue); } } /** * Set the WAI-ARIA Roles Specify the html id then aria role * * @return */ function setAriaRoleElementsById() { setRoleAttribute("header", "banner"); setRoleAttribute("element-box", "main"); setRoleAttribute("footer", "contentinfo"); setRoleAttribute("nav", "navigation"); setRoleAttribute("submenu", "navigation"); setRoleAttribute("system-message", "alert"); } /** * This sets the given Aria Property state to true for the given element * * @param el * The element (tag.class) * @param prop * The property to set to true * @return */ function setPropertyAttribute(el, prop) { if (document.getElements(el)) { document.getElements(el).set(prop, "true"); } } /** * Set the WAI-ARIA Properties Specify the tag.class then the aria property to * set to true If classes are changed on the fly (i.e. aria-invalid) they need * to be changed there instead of here. * * @return */ function setAriaProperties() { setPropertyAttribute("input.required", "aria-required"); setPropertyAttribute("textarea.required", "aria-required"); setPropertyAttribute("input.readonly", "aria-readonly"); setPropertyAttribute("input.invalid", "aria-invalid"); setPropertyAttribute("textarea.invalid", "aria-invalid"); } /** * Process file */ /** from accessible suckerfish menu by Matt Carroll, * mootooled by Bill Tomczak */ window.addEvent('domready', function(){ var menu = document.id('menu'); if (menu && !menu.hasClass('disabled')) { menu.getElements('li').each(function(cel){ cel.addEvent('mouseenter', function(){ this.addClass('sfhover'); }); cel.addEvent('mouseleave', function() { this.removeClass('sfhover'); }); }); menu.getElements('a').each(function(ael) { ael.addEvent('focus', function() { this.addClass('sffocus'); this.getParents('li').addClass('sfhover'); }); ael.addEvent('blur', function() { this.removeClass('sffocus'); this.getParents('li').removeClass('sfhover'); }); }); } }); window.addEvent('domready', function() { setFocus(); setSkip(); setAriaRoleElementsById(); setAriaProperties(); }); /** * For IE6 - Background flicker fix */ try { document.execCommand('BackgroundImageCache', false, true); } catch (e) { }
JavaScript
/*global window, localStorage, fontSizeTitle, bigger, reset, smaller, biggerTitle, resetTitle, smallerTitle, Cookie */ var prefsLoaded = false; var defaultFontSize = 100; var currentFontSize = defaultFontSize; var fontSizeTitle; var bigger; var smaller; var reset; var biggerTitle; var smallerTitle; var resetTitle; Object.append(Browser.Features, { localstorage: (function() { return ('localStorage' in window) && window.localStorage !== null; })() }); function setFontSize(fontSize) { document.body.style.fontSize = fontSize + '%'; } function changeFontSize(sizeDifference) { currentFontSize = parseInt(currentFontSize, 10) + parseInt(sizeDifference * 5, 10); if (currentFontSize > 180) { currentFontSize = 180; } else if (currentFontSize < 60) { currentFontSize = 60; } setFontSize(currentFontSize); } function revertStyles() { currentFontSize = defaultFontSize; changeFontSize(0); } function writeFontSize(value) { if (Browser.Features.localstorage) { localStorage.fontSize = value; } else { Cookie.write("fontSize", value, {duration: 180}); } } function readFontSize() { if (Browser.Features.localstorage) { return localStorage.fontSize; } else { return Cookie.read("fontSize"); } } function setUserOptions() { if (!prefsLoaded) { var size = readFontSize(); currentFontSize = size ? size : defaultFontSize; setFontSize(currentFontSize); prefsLoaded = true; } } function addControls() { var container = document.id('fontsize'); var content = '<h3>'+ fontSizeTitle +'</h3><p><a title="'+ biggerTitle +'" href="#" onclick="changeFontSize(2); return false">'+ bigger +'</a><span class="unseen">.</span><a href="#" title="'+resetTitle+'" onclick="revertStyles(); return false">'+ reset +'</a><span class="unseen">.</span><a href="#" title="'+ smallerTitle +'" onclick="changeFontSize(-2); return false">'+ smaller +'</a></p>'; container.set('html', content); } function saveSettings() { writeFontSize(currentFontSize); } window.addEvent('domready', setUserOptions); window.addEvent('domready', addControls); window.addEvent('unload', saveSettings);
JavaScript
// Angie Radtke 2009 // /*global window, localStorage, Cookie, altopen, altclose, big, small, rightopen, rightclose, bildauf, bildzu */ Object.append(Browser.Features, { localstorage: (function() { return ('localStorage' in window) && window.localStorage !== null; })() }); function saveIt(name) { var x = document.id(name).style.display; if (!x) { alert('No cookie available'); } else { if (Browser.Features.localstorage) { localStorage[name] = x; } else { Cookie.write(name, x, {duration: 7}); } } } function readIt(name) { if (Browser.Features.localstorage) { return localStorage[name]; } else { return Cookie.read(name); } } function wrapperwidth(width) { document.id('wrapper').setStyle('width', width); } // add Wai-Aria landmark-roles window.addEvent('domready', function () { if (document.id('nav')) { document.id('nav').setProperties( { role : 'navigation' }); } if (document.id('mod-search-searchword')) { document.id(document.id('mod-search-searchword').form).set( { role : 'search' }); } if (document.id('main')) { document.id('main').setProperties( { role : 'main' }); } if (document.id('right')) { document.id('right').setProperties( { role : 'contentinfo' }); } }); window.addEvent('domready', function() { // get ankers var myankers = document.id(document.body).getElements('a.opencloselink'); myankers.each(function(element) { element.setProperty('role', 'tab'); var myid = element.getProperty('id'); myid = myid.split('_'); myid = 'module_' + myid[1]; document.id(element).setProperty('aria-controls', myid); }); var list = document.id(document.body).getElements('div.moduletable_js'); list.each(function(element) { if (element.getElement('div.module_content')) { var el = element.getElement('div.module_content'); el.setProperty('role', 'tabpanel'); var myid = el.getProperty('id'); myid = myid.split('_'); myid = 'link_' + myid[1]; el.setProperty('aria-labelledby', myid); var myclass = el.get('class'); var one = myclass.split(' '); // search for active menu-item var listelement = el.getElement('a.active'); var unique = el.id; var nocookieset = readIt(unique); if ((listelement) || ((one[1] == 'open') && (nocookieset == null))) { el.setStyle('display', 'block'); var eltern = el.getParent(); var elternh = eltern.getElement('h3'); var elternbild = eltern.getElement('img'); elternbild.setProperties( { alt : altopen, src : bildzu }); elternbild.focus(); } else { el.setStyle('display', 'none'); el.setProperty('aria-expanded', 'false'); } unique = el.id; var cookieset = readIt(unique); if (cookieset == 'block') { el.setStyle('display', 'block'); el.setProperty('aria-expanded', 'true'); } } }); }); window.addEvent('domready', function() { var what = document.id('right'); // if rightcolumn if (what != null) { var whatid = what.id; var rightcookie = readIt(whatid); if (rightcookie == 'none') { what.setStyle('display', 'none'); document.id('nav').addClass('leftbigger'); wrapperwidth(big); var grafik = document.id('bild'); grafik.innerHTML = rightopen; grafik.focus(); } } }); function auf(key) { var el = document.id(key); if (el.style.display == 'none') { el.setStyle('display', 'block'); el.setProperty('aria-expanded', 'true'); if (key != 'right') { el.slide('hide').slide('in'); el.getParent().setProperty('class', 'slide'); eltern = el.getParent().getParent(); elternh = eltern.getElement('h3'); elternh.addClass('high'); elternbild = eltern.getElement('img'); // elternbild.focus(); el.focus(); elternbild.setProperties( { alt : altopen, src : bildzu }); } if (key == 'right') { document.id('right').setStyle('display', 'block'); wrapperwidth(small); document.id('nav').removeClass('leftbigger'); grafik = document.id('bild'); document.id('bild').innerHTML = rightclose; grafik.focus(); } } else { el.setStyle('display', 'none'); el.setProperty('aria-expanded', 'false'); el.removeClass('open'); if (key != 'right') { eltern = el.getParent().getParent(); elternh = eltern.getElement('h3'); elternh.removeClass('high'); elternbild = eltern.getElement('img'); // alert(bildauf); elternbild.setProperties( { alt : altclose, src : bildauf }); elternbild.focus(); } if (key == 'right') { document.id('right').setStyle('display', 'none'); wrapperwidth(big); document.id('nav').addClass('leftbigger'); grafik = document.id('bild'); grafik.innerHTML = rightopen; grafik.focus(); } } // write cookie saveIt(key); } // ########### Tabfunctions #################### window.addEvent('domready', function() { var alldivs = document.id(document.body).getElements('div.tabcontent'); var outerdivs = document.id(document.body).getElements('div.tabouter'); outerdivs = outerdivs.getProperty('id'); for (var i = 0; i < outerdivs.length; i++) { alldivs = document.id(outerdivs[i]).getElements('div.tabcontent'); count = 0; alldivs.each(function(element) { count++; var el = document.id(element); el.setProperty('role', 'tabpanel'); el.setProperty('aria-hidden', 'false'); el.setProperty('aria-expanded', 'true'); elid = el.getProperty('id'); elid = elid.split('_'); elid = 'link_' + elid[1]; el.setProperty('aria-labelledby', elid); if (count != 1) { el.addClass('tabclosed').removeClass('tabopen'); el.setProperty('aria-hidden', 'true'); el.setProperty('aria-expanded', 'false'); } }); countankers = 0; allankers = document.id(outerdivs[i]).getElement('ul.tabs').getElements('a'); allankers.each(function(element) { countankers++; var el = document.id(element); el.setProperty('aria-selected', 'true'); el.setProperty('role', 'tab'); linkid = el.getProperty('id'); moduleid = linkid.split('_'); moduleid = 'module_' + moduleid[1]; el.setProperty('aria-controls', moduleid); if (countankers != 1) { el.addClass('linkclosed').removeClass('linkopen'); el.setProperty('aria-selected', 'false'); } }); } }); function tabshow(elid) { var el = document.id(elid); var outerdiv = el.getParent(); outerdiv = outerdiv.getProperty('id'); var alldivs = document.id(outerdiv).getElements('div.tabcontent'); var liste = document.id(outerdiv).getElement('ul.tabs'); liste.getElements('a').setProperty('aria-selected', 'false'); alldivs.each(function(element) { element.addClass('tabclosed').removeClass('tabopen'); element.setProperty('aria-hidden', 'true'); element.setProperty('aria-expanded', 'false'); }); el.addClass('tabopen').removeClass('tabclosed'); el.setProperty('aria-hidden', 'false'); el.setProperty('aria-expanded', 'true'); el.focus(); var getid = elid.split('_'); var activelink = 'link_' + getid[1]; document.id(activelink).setProperty('aria-selected', 'true'); liste.getElements('a').addClass('linkclosed').removeClass('linkopen'); document.id(activelink).addClass('linkopen').removeClass('linkclosed'); } function nexttab(el) { var outerdiv = document.id(el).getParent(); var liste = outerdiv.getElement('ul.tabs'); var getid = el.split('_'); var activelink = 'link_' + getid[1]; var aktiverlink = document.id(activelink).getProperty('aria-selected'); var tablinks = liste.getElements('a').getProperty('id'); for ( var i = 0; i < tablinks.length; i++) { if (tablinks[i] == activelink) { if (document.id(tablinks[i + 1]) != null) { document.id(tablinks[i + 1]).onclick(); break; } } } }
JavaScript
(function($){ $.fn.tipTip = function(options) { var defaults = { activation: "hover", keepAlive: false, maxWidth: "180px", edgeOffset: 0, defaultPosition: "right", delay: 100, fadeIn: 100, fadeOut: 100, attribute: "title", content: false, enter: function(){}, exit: function(){} }; var opts = $.extend(defaults, options); if($("#tipHolder").length <= 0){ var tipHolder = $('<div id="tipHolder" style="max-width:'+ opts.maxWidth +';"></div>'); var tipContent = $('<div id="tipContent"></div>'); var tipArrow = $('<div id="tipArrow"></div>'); $("body").append(tipHolder.html(tipContent).prepend(tipArrow.html('<div id="tipArrowInner"></div>'))); } else { var tipHolder = $("#tipHolder"); var tipContent = $("#tipContent"); var tipArrow = $("#tipArrow"); } return this.each(function(){ var org_elem = $(this); if(opts.content){ var org_title = opts.content; } else { var org_title = org_elem.attr(opts.attribute); } if(org_title != ""){ if(!opts.content){ org_elem.removeAttr(opts.attribute); } var timeout = false; if(opts.activation == "hover"){ org_elem.hover(function(){ active_tiptip(); }, function(){ if(!opts.keepAlive){ deactive_tiptip(); } }); if(opts.keepAlive){ tipHolder.hover(function(){}, function(){ deactive_tiptip(); }); } } else if(opts.activation == "focus"){ org_elem.focus(function(){ active_tiptip(); }).blur(function(){ deactive_tiptip(); }); } else if(opts.activation == "click"){ org_elem.click(function(){ active_tiptip(); return false; }).hover(function(){},function(){ if(!opts.keepAlive){ deactive_tiptip(); } }); if(opts.keepAlive){ tipHolder.hover(function(){}, function(){ deactive_tiptip(); }); } } function active_tiptip(){ opts.enter.call(this); tipContent.html(org_title); tipHolder.hide().removeAttr("class").css("margin","0"); tipArrow.removeAttr("style"); var top = parseInt(org_elem.offset()['top']); var left = parseInt(org_elem.offset()['left']); var org_width = parseInt(org_elem.outerWidth()); var org_height = parseInt(org_elem.outerHeight()); var tip_w = tipHolder.outerWidth(); var tip_h = tipHolder.outerHeight(); var w_compare = Math.round((org_width - tip_w) / 2); var h_compare = Math.round((org_height - tip_h) / 2); var marg_left = Math.round(left + w_compare); var marg_top = Math.round(top + org_height + opts.edgeOffset); var t_class = ""; var arrow_top = ""; var arrow_left = Math.round(tip_w - 12) / 2; if(opts.defaultPosition == "bottom"){ t_class = "Bottom"; } else if(opts.defaultPosition == "top"){ t_class = "Top"; } else if(opts.defaultPosition == "left"){ t_class = "Left"; } else if(opts.defaultPosition == "right"){ t_class = "Right"; } var right_compare = (w_compare + left) < parseInt($(window).scrollLeft()); var left_compare = (tip_w + left) > parseInt($(window).width()); if((right_compare && w_compare < 0) || (t_class == "Right" && !left_compare) || (t_class == "Left" && left < (tip_w + opts.edgeOffset + 5))){ t_class = "Right"; arrow_top = Math.round(tip_h - 13) / 2; arrow_left = -12; marg_left = Math.round(left + org_width + opts.edgeOffset); marg_top = Math.round(top + h_compare); } else if((left_compare && w_compare < 0) || (t_class == "Left" && !right_compare)){ t_class = "Left"; arrow_top = Math.round(tip_h - 13) / 2; arrow_left = Math.round(tip_w); marg_left = Math.round(left - (tip_w + opts.edgeOffset + 5)); marg_top = Math.round(top + h_compare); } var top_compare = (top + org_height + opts.edgeOffset + tip_h + 8) > parseInt($(window).height() + $(window).scrollTop()); var bottom_compare = ((top + org_height) - (opts.edgeOffset + tip_h + 8)) < 0; if(top_compare || (t_class == "Bottom" && top_compare) || (t_class == "Top" && !bottom_compare)){ if(t_class == "Top" || t_class == "Bottom"){ t_class = "Top"; } else { t_class = t_class+"Top"; } arrow_top = tip_h; marg_top = Math.round(top - (tip_h + 5 + opts.edgeOffset)); } else if(bottom_compare | (t_class == "Top" && bottom_compare) || (t_class == "Bottom" && !top_compare)){ if(t_class == "Top" || t_class == "Bottom"){ t_class = "Bottom"; } else { t_class = t_class+"Bottom"; } arrow_top = -12; marg_top = Math.round(top + org_height + opts.edgeOffset); } if(t_class == "RightTop" || t_class == "LeftTop"){ marg_top = marg_top + 5; } else if(t_class == "RightBottom" || t_class == "LeftBottom"){ marg_top = marg_top - 5; } if(t_class == "LeftTop" || t_class == "LeftBottom"){ marg_left = marg_left + 5; } tipArrow.css({"margin-left": arrow_left+"px", "margin-top": arrow_top+"px"}); tipHolder.css({"margin-left": marg_left+"px", "margin-top": marg_top+"px"}).attr("class","Tip"+t_class); if (timeout){ clearTimeout(timeout); } timeout = setTimeout(function(){ tipHolder.stop(true,true).fadeIn(opts.fadeIn); }, opts.delay); } function deactive_tiptip(){ opts.exit.call(this); if (timeout){ clearTimeout(timeout); } tipHolder.fadeOut(opts.fadeOut); } } }); } })(jQuery);
JavaScript
/* * jQuery Watermark Plugin * http://updatepanel.net/2009/04/17/jquery-watermark-plugin/ * * Copyright (c) 2009 Ting Zwei Kuei * * Dual licensed under the MIT and GPL licenses. * http://www.opensource.org/licenses/mit-license.php * http://www.opensource.org/licenses/gpl-3.0.html */ (function($) { $.fn.updnWatermark = function(options) { options = $.extend({}, $.fn.updnWatermark.defaults, options); return this.each(function() { var $input = $(this); var $watermark = $input.data("watermark"); // only create watermark if title attribute exists if (!$watermark && this.title) { var $watermark = $("<label/>") .insertBefore(this) .text(this.title) .attr("for", this.id) .addClass(options.cssClass) .hide() .bind("position", function() { var pos = $input.position(); $(this).css({ position: "absolute", zIndex:2, left: pos.left, top: pos.top }) }) .bind("show", function() { $(this).fadeIn("fast"); }) .bind("hide", function() { $(this).hide(); }) .bind("update", function() { ($input.is(":visible") ? $(this).trigger("position").show() : $(this).hide()); }); $input.data("watermark", $watermark); } if ($watermark) { $input .focus(function(ev) { $watermark.trigger("hide"); }) .blur(function(ev) { if (!$(this).val()) { $watermark.trigger("show"); } }); // set initial state if (!$input.val()) { $watermark.trigger("position").show(); } } }); }; $.fn.updnWatermark.defaults = { cssClass: "UpdnWatermark" }; $.updnWatermark = { attachAll: function(options) { $.updnWatermark.all = $("input:text[title!=''],input:password[title!=''],textarea[title!=''],input:file[title!='']").updnWatermark(options); }, updateAll: function() { ($.updnWatermark.all && $.updnWatermark.all.each(function() { var $watermark = $(this).data("watermark"); ($watermark && $watermark.trigger("update")); })); } }; })(jQuery);
JavaScript
/* * Copyright (c) 2007 Josh Bush (digitalbush.com) * * 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. */ /* * Version: 1.1 * Release: 2007-09-08 */ (function($) { //Helper Functions for Caret positioning function getCaretPosition(ctl){ var res = {begin: 0, end: 0 }; if (ctl.setSelectionRange){ res.begin = ctl.selectionStart; res.end = ctl.selectionEnd; }else if (document.selection && document.selection.createRange){ var range = document.selection.createRange(); res.begin = 0 - range.duplicate().moveStart('character', -100000); res.end = res.begin + range.text.length; } return res; }; function setCaretPosition(ctl, pos){ if(ctl.setSelectionRange){ ctl.focus(); ctl.setSelectionRange(pos,pos); }else if (ctl.createTextRange){ var range = ctl.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }; //Predefined character definitions var charMap={ '9':"[0-9]", 'a':"[A-Za-z]", '*':"[A-Za-z0-9]" }; //Helper method to inject character definitions $.mask={ addPlaceholder : function(c,r){ charMap[c]=r; } }; $.fn.unmask=function(){ return this.trigger("unmask"); }; //Main Method $.fn.mask = function(mask,settings) { settings = $.extend({ placeholder: "_", completed: null }, settings); //Build Regex for format validation var reString="^"; for(var i=0;i<mask.length;i++) reString+=(charMap[mask.charAt(i)] || ("\\"+mask.charAt(i))); reString+="$"; var re = new RegExp(reString); return this.each(function(){ var input=$(this); var buffer=new Array(mask.length); var locked=new Array(mask.length); //Build buffer layout from mask for(var i=0;i<mask.length;i++){ locked[i]=charMap[mask.charAt(i)]==null; buffer[i]=locked[i]?mask.charAt(i):settings.placeholder; } /*Event Bindings*/ function focusEvent(){ checkVal(); writeBuffer(); setTimeout(function(){ setCaretPosition(input[0],0); },0); }; input.bind("focus",focusEvent); input.bind("blur",checkVal); //Paste events for IE and Mozilla thanks to Kristinn Sigmundsson if ($.browser.msie) this.onpaste= function(){setTimeout(checkVal,0);}; else if ($.browser.mozilla) this.addEventListener('input',checkVal,false); var ignore=false; //Variable for ignoring control keys function keydownEvent(e){ var pos=getCaretPosition(this); var k = e.keyCode; ignore=(k < 16 || (k > 16 && k < 32 ) || (k > 32 && k < 41)); //delete selection before proceeding if((pos.begin-pos.end)!=0 && (!ignore || k==8 || k==46)){ clearBuffer(pos.begin,pos.end); } //backspace and delete get special treatment if(k==8){//backspace while(pos.begin-->=0){ if(!locked[pos.begin]){ buffer[pos.begin]=settings.placeholder; if($.browser.opera){ //Opera won't let you cancel the backspace, so we'll let it backspace over a dummy character. writeBuffer(pos.begin); setCaretPosition(this,pos.begin+1); }else{ writeBuffer(); setCaretPosition(this,pos.begin); } return false; } } }else if(k==46){//delete clearBuffer(pos.begin,pos.begin+1); writeBuffer(); setCaretPosition(this,pos.begin); return false; }else if (k==27){ clearBuffer(0,mask.length); writeBuffer(); setCaretPosition(this,0); return false; } }; input.bind("keydown",keydownEvent); function keypressEvent(e){ if(ignore){ ignore=false; return; } e=e||window.event; var k=e.charCode||e.keyCode||e.which; var pos=getCaretPosition(this); var caretPos=pos.begin; if(e.ctrlKey || e.altKey){//Ignore return true; }else if ((k>=41 && k<=122) ||k==32 || k>186){//typeable characters while(pos.begin<mask.length){ var reString=charMap[mask.charAt(pos.begin)]; var match; if(reString){ var reChar=new RegExp(reString); match=String.fromCharCode(k).match(reChar); }else{//we're on a mask char, go forward and try again pos.begin+=1; pos.end=pos.begin; caretPos+=1; continue; } if(match) buffer[pos.begin]=String.fromCharCode(k); else return false;//reject char while(++caretPos<mask.length){//seek forward to next typable position if(!locked[caretPos]) break; } break; } }else return false; writeBuffer(); if(settings.completed && caretPos>=buffer.length) settings.completed.call(input); else setCaretPosition(this,caretPos); return false; }; input.bind("keypress",keypressEvent); /*Helper Methods*/ function clearBuffer(start,end){ for(var i=start;i<end;i++){ if(!locked[i]) buffer[i]=settings.placeholder; } }; function writeBuffer(pos){ var s=""; for(var i=0;i<mask.length;i++){ s+=buffer[i]; if(i==pos) s+=settings.placeholder; } input.val(s); return s; }; function checkVal(){ //try to place charcters where they belong var test=input.val(); var pos=0; for(var i=0;i<mask.length;i++){ if(!locked[i]){ while(pos++<test.length){ //Regex Test each char here. var reChar=new RegExp(charMap[mask.charAt(i)]); if(test.charAt(pos-1).match(reChar)){ buffer[i]=test.charAt(pos-1); break; } } } } var s=writeBuffer(); if(!s.match(re)){ input.val(""); clearBuffer(0,mask.length); } }; input.one("unmask",function(){ input.unbind("focus",focusEvent); input.unbind("blur",checkVal); input.unbind("keydown",keydownEvent); input.unbind("keypress",keypressEvent); if ($.browser.msie) this.onpaste= null; else if ($.browser.mozilla) this.removeEventListener('input',checkVal,false); }); }); }; })(jQuery);
JavaScript
/*! * jQuery UI 1.8.17 * * Copyright 2011, 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 */ (function( $, undefined ) { // prevent duplicate loading // this is only a problem because we proxy existing functions // and we don't want to double proxy them $.ui = $.ui || {}; if ( $.ui.version ) { return; } $.extend( $.ui, { version: "1.8.17", 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 } }); // plugins $.fn.extend({ propAttr: $.fn.prop || $.fn.attr, _focus: $.fn.focus, focus: function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : this._focus.apply( this, arguments ); }, scrollParent: function() { var scrollParent; if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); }).eq(0); } return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent; }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; }, disableSelection: function() { return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }, enableSelection: function() { return this.unbind( ".ui-disableSelection" ); } }); $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.curCSS( elem, "padding" + this, true) ) || 0; if ( border ) { size -= parseFloat( $.curCSS( elem, "border" + this + "Width", true) ) || 0; } if ( margin ) { size -= parseFloat( $.curCSS( elem, "margin" + this, true) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); // selectors function focusable( element, isTabIndexNotNaN ) { var nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { var map = element.parentNode, mapName = map.name, img; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap=#" + mapName + "]" )[0]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" == nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) // the element and all of its ancestors must be visible && visible( element ); } function visible( element ) { return !$( element ).parents().andSelf().filter(function() { return $.curCSS( this, "visibility" ) === "hidden" || $.expr.filters.hidden( this ); }).length; } $.extend( $.expr[ ":" ], { data: function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support $(function() { var body = document.body, div = body.appendChild( div = document.createElement( "div" ) ); $.extend( div.style, { minHeight: "100px", height: "auto", padding: 0, borderWidth: 0 }); $.support.minHeight = div.offsetHeight === 100; $.support.selectstart = "onselectstart" in div; // set display to none to avoid a layout bug in IE // http://dev.jquery.com/ticket/4014 body.removeChild( div ).style.display = "none"; }); // deprecated $.extend( $.ui, { // $.ui.plugin is deprecated. Use the proxy pattern instead. plugin: { add: function( module, option, set ) { var proto = $.ui[ module ].prototype; for ( var i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args ) { var set = instance.plugins[ name ]; if ( !set || !instance.element[ 0 ].parentNode ) { return; } for ( var i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }, // will be deprecated when we switch to jQuery 1.4 - use jQuery.contains() contains: function( a, b ) { return document.compareDocumentPosition ? a.compareDocumentPosition( b ) & 16 : a !== b && a.contains( b ); }, // only used by resizable hasScroll: function( el, a ) { //If overflow is hidden, the element might have extra content, but the user wants to hide it if ( $( el ).css( "overflow" ) === "hidden") { return false; } var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", has = false; if ( el[ scroll ] > 0 ) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[ scroll ] = 1; has = ( el[ scroll ] > 0 ); el[ scroll ] = 0; return has; }, // these are odd functions, fix the API or move into individual plugins isOverAxis: function( x, reference, size ) { //Determines when x coordinate is over "b" element axis return ( x > reference ) && ( x < ( reference + size ) ); }, isOver: function( y, x, top, left, height, width ) { //Determines when x, y coordinates is over "b" element return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width ); } }); })( jQuery ); /*! * jQuery UI Widget 1.8.17 * * Copyright 2011, 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++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _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() { try { $( this ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} }); } } 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 ), methodValue = instance && $.isFunction( instance[options] ) ? instance[ options ].apply( instance, args ) : instance; // TODO: add this back in 1.9 and use $.error() (see #5972) // 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() { return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; }, _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 prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction(callback) && callback.call( this.element[0], event, data ) === false || event.isDefaultPrevented() ); } }; })( jQuery ); /* * jQuery UI Datepicker 1.8.17 * * Copyright 2011, 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/Datepicker * * Depends: * jquery.ui.core.js */ (function( $, undefined ) { $.extend($.ui, { datepicker: { version: "1.8.17" } }); var PROP_NAME = 'datepicker'; var dpuuid = new Date().getTime(); var instActive; /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this.debug = false; // Change this to true to start debugging this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class this._appendClass = 'ui-datepicker-append'; // The name of the append marker class this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings closeText: 'Done', // Display text for close link prevText: 'Prev', // Display text for previous month link nextText: 'Next', // Display text for next month link currentText: 'Today', // Display text for current month link monthNames: ['January','February','March','April','May','June', 'July','August','September','October','November','December'], // Names of months for drop-down and formatting monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday weekHeader: 'Wk', // Column header for week of the year dateFormat: 'mm/dd/yy', // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: '' // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: 'focus', // 'focus' for popup on focus, // 'button' for trigger button, or 'both' for either showAnim: 'fadeIn', // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: '', // Display text following the input box, e.g. showing the format buttonText: 'Klik her for at vælge en dato', // Text for trigger button buttonImage: '', // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: 'c-10:c+10', // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: '+10', // Short year values < this are in the current century, // > this are in the previous century, // string value starting with '+' for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: 'fast', // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '', // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: '', // Selector for an alternate field to store selected dates into altFormat: '', // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.extend(this._defaults, this.regional['']); this.dpDiv = bindHover($('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: 'hasDatepicker', //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, /* Debug logging (if enabled). */ log: function () { if (this.debug) console.log.apply('', arguments); }, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. @param settings object - the new settings to use as defaults (anonymous object) @return the manager object */ setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. @param target element - the target input field or division or span @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { // check for settings on the control itself - in namespace 'date:' var inlineSettings = null; for (var attrName in this._defaults) { var attrValue = target.getAttribute('date:' + attrName); if (attrValue) { inlineSettings = inlineSettings || {}; try { inlineSettings[attrName] = eval(attrValue); } catch (err) { inlineSettings[attrName] = attrValue; } } } var nodeName = target.nodeName.toLowerCase(); var inline = (nodeName == 'div' || nodeName == 'span'); if (!target.id) { this.uuid += 1; target.id = 'dp' + this.uuid; } var inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}, inlineSettings || {}); if (nodeName == 'input') { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div bindHover($('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) return; this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp). bind("setData.datepicker", function(event, key, value) { inst.settings[key] = value; }).bind("getData.datepicker", function(event, key) { return this._get(inst, key); }); this._autoSize(inst); $.data(target, PROP_NAME, inst); //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var appendText = this._get(inst, 'appendText'); var isRTL = this._get(inst, 'isRTL'); if (inst.append) inst.append.remove(); if (appendText) { inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>'); input[isRTL ? 'before' : 'after'](inst.append); } input.unbind('focus', this._showDatepicker); if (inst.trigger) inst.trigger.remove(); var showOn = this._get(inst, 'showOn'); if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field input.focus(this._showDatepicker); if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked var buttonText = this._get(inst, 'buttonText'); var buttonImage = this._get(inst, 'buttonImage'); inst.trigger = $(this._get(inst, 'buttonImageOnly') ? $('<img/>').addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $('<button type="button"></button>').addClass(this._triggerClass). html(buttonImage == '' ? buttonText : $('<img/>').attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? 'before' : 'after'](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput == input[0]) $.datepicker._hideDatepicker(); else $.datepicker._showDatepicker(input[0]); return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, 'autoSize') && !inst.inline) { var date = new Date(2009, 12 - 1, 20); // Ensure double digits var dateFormat = this._get(inst, 'dateFormat'); if (dateFormat.match(/[DM]/)) { var findMax = function(names) { var max = 0; var maxI = 0; for (var i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? 'monthNames' : 'monthNamesShort')))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? 'dayNames' : 'dayNamesShort'))) + 20 - date.getDay()); } inst.input.attr('size', this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) return; divSpan.addClass(this.markerClassName).append(inst.dpDiv). bind("setData.datepicker", function(event, key, value){ inst.settings[key] = value; }).bind("getData.datepicker", function(event, key){ return this._get(inst, key); }); $.data(target, PROP_NAME, inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); //If disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. @param input element - ignored @param date string or Date - the initial date to display @param onSelect function - the function to call when a date is selected @param settings object - update the dialog date picker instance's settings (anonymous object) @param pos int[2] - coordinates for the dialog's position within the screen or event - with x/y coordinates or leave empty for default (screen centre) @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; var id = 'dp' + this.uuid; this._dialogInput = $('<input type="text" id="' + id + '" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>'); this._dialogInput.keydown(this._doKeyDown); $('body').append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], PROP_NAME, inst); } extendRemove(inst.settings, settings || {}); date = (date && date.constructor == Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { var browserWidth = document.documentElement.clientWidth; var browserHeight = document.documentElement.clientHeight; var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css('left', (this._pos[0] + 20) + 'px').css('top', this._pos[1] + 'px'); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) $.blockUI(this.dpDiv); $.data(this._dialogInput[0], PROP_NAME, inst); return this; }, /* Detach a datepicker from its control. @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); $.removeData(target, PROP_NAME); if (nodeName == 'input') { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind('focus', this._showDatepicker). unbind('keydown', this._doKeyDown). unbind('keypress', this._doKeyPress). unbind('keyup', this._doKeyUp); } else if (nodeName == 'div' || nodeName == 'span') $target.removeClass(this.markerClassName).empty(); }, /* Enable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = false; inst.trigger.filter('button'). each(function() { this.disabled = false; }).end(). filter('img').css({opacity: '1.0', cursor: ''}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().removeClass('ui-state-disabled'); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). removeAttr("disabled"); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = true; inst.trigger.filter('button'). each(function() { this.disabled = true; }).end(). filter('img').css({opacity: '0.5', cursor: 'default'}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().addClass('ui-state-disabled'); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). attr("disabled", "disabled"); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? @param target element - the target input field or division or span @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] == target) return true; } return false; }, /* Retrieve the instance data for the target control. @param target element - the target input field or division or span @return object - the associated instance data @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, PROP_NAME); } catch (err) { throw 'Missing instance data for this datepicker'; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. @param target element - the target input field or division or span @param name object - the new settings to update or string - the name of the setting to change or retrieve, when retrieving also 'all' for all instance settings or 'defaults' for all global defaults @param value any - the new value for the setting (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var inst = this._getInst(target); if (arguments.length == 2 && typeof name == 'string') { return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) : (inst ? (name == 'all' ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } var settings = name || {}; if (typeof name == 'string') { settings = {}; settings[name] = value; } if (inst) { if (this._curInst == inst) { this._hideDatepicker(); } var date = this._getDateDatepicker(target, true); var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); extendRemove(inst.settings, settings); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided if (minDate !== null && settings['dateFormat'] !== undefined && settings['minDate'] === undefined) inst.settings.minDate = this._formatDate(inst, minDate); if (maxDate !== null && settings['dateFormat'] !== undefined && settings['maxDate'] === undefined) inst.settings.maxDate = this._formatDate(inst, maxDate); this._attachments($(target), inst); this._autoSize(inst); this._setDate(inst, date); this._updateAlternate(inst); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. @param target element - the target input field or division or span @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. @param target element - the target input field or division or span @param noDefault boolean - true if no default date is to be used @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) this._setDateFromField(inst, noDefault); return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var inst = $.datepicker._getInst(event.target); var handled = true; var isRTL = inst.dpDiv.is('.ui-datepicker-rtl'); inst._keyEvent = true; if ($.datepicker._datepickerShowing) switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: var sel = $('td.' + $.datepicker._dayOverClass + ':not(.' + $.datepicker._currentClass + ')', inst.dpDiv); if (sel[0]) $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); var onSelect = $.datepicker._get(inst, 'onSelect'); if (onSelect) { var dateStr = $.datepicker._formatDate(inst); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else $.datepicker._hideDatepicker(); return false; // don't submit the form break; // select the value on enter case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target); handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target); handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D'); handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D'); handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D'); handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D'); handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home $.datepicker._showDatepicker(this); else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, 'constrainInput')) { var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')); var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode); return event.ctrlKey || event.metaKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var inst = $.datepicker._getInst(event.target); if (inst.input.val() != inst.lastVal) { try { var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (event) { $.datepicker.log(event); } } return true; }, /* Pop-up the date picker for a given input field. If false returned from beforeShow event handler do not show. @param input element - the input field attached to the date picker or event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger input = $('input', input.parentNode)[0]; if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here return; var inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst != inst) { $.datepicker._curInst.dpDiv.stop(true, true); if ( inst && $.datepicker._datepickerShowing ) { $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); } } var beforeShow = $.datepicker._get(inst, 'beforeShow'); var beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ //false return; } extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) // hide cursor input.value = ''; if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } var isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css('position') == 'fixed'; return !isFixed; }); if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled $.datepicker._pos[0] -= document.documentElement.scrollLeft; $.datepicker._pos[1] -= document.documentElement.scrollTop; } var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none', left: offset.left + 'px', top: offset.top + 'px'}); if (!inst.inline) { var showAnim = $.datepicker._get(inst, 'showAnim'); var duration = $.datepicker._get(inst, 'duration'); var postProcess = function() { var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only if( !! cover.length ){ var borders = $.datepicker._getBorders(inst.dpDiv); cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}); } }; inst.dpDiv.zIndex($(input).zIndex()+1); $.datepicker._datepickerShowing = true; if ($.effects && $.effects[showAnim]) inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess); if (!showAnim || !duration) postProcess(); if (inst.input.is(':visible') && !inst.input.is(':disabled')) inst.input.focus(); $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { var self = this; self.maxRows = 4; //Reset the max number of rows being displayed (see #7043) var borders = $.datepicker._getBorders(inst.dpDiv); instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only if( !!cover.length ){ //avoid call to outerXXXX() when not in IE6 cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}) } inst.dpDiv.find('.' + this._dayOverClass + ' a').mouseover(); var numMonths = this._getNumberOfMonths(inst); var cols = numMonths[1]; var width = 17; inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width(''); if (cols > 1) inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em'); inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') + 'Class']('ui-datepicker-multi'); inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') + 'Class']('ui-datepicker-rtl'); if (inst == $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input && // #6694 - don't focus the input if it's already focused // this breaks the change event in IE inst.input.is(':visible') && !inst.input.is(':disabled') && inst.input[0] != document.activeElement) inst.input.focus(); // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ var origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find('select.ui-datepicker-year:first').replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, /* Retrieve the size of left and top borders for an element. @param elem (jQuery object) the element of interest @return (number[2]) the left and top borders */ _getBorders: function(elem) { var convert = function(value) { return {thin: 1, medium: 2, thick: 3}[value] || value; }; return [parseFloat(convert(elem.css('border-left-width'))), parseFloat(convert(elem.css('border-top-width')))]; }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(); var dpHeight = inst.dpDiv.outerHeight(); var inputWidth = inst.input ? inst.input.outerWidth() : 0; var inputHeight = inst.input ? inst.input.outerHeight() : 0; var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft(); var viewHeight = document.documentElement.clientHeight + $(document).scrollTop(); offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var inst = this._getInst(obj); var isRTL = this._get(inst, 'isRTL'); while (obj && (obj.type == 'hidden' || obj.nodeType != 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? 'previousSibling' : 'nextSibling']; } var position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var inst = this._curInst; if (!inst || (input && inst != $.data(input, PROP_NAME))) return; if (this._datepickerShowing) { var showAnim = this._get(inst, 'showAnim'); var duration = this._get(inst, 'duration'); var self = this; var postProcess = function() { $.datepicker._tidyDialog(inst); self._curInst = null; }; if ($.effects && $.effects[showAnim]) inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' : (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess); if (!showAnim) postProcess(); this._datepickerShowing = false; var onClose = this._get(inst, 'onClose'); if (onClose) onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]); this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' }); if ($.blockUI) { $.unblockUI(); $('body').append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar'); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) return; var $target = $(event.target), inst = $.datepicker._getInst($target[0]); if ( ( ( $target[0].id != $.datepicker._mainDivId && $target.parents('#' + $.datepicker._mainDivId).length == 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.hasClass($.datepicker._triggerClass) && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst != inst ) ) $.datepicker._hideDatepicker(); }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id); var inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var target = $(id); var inst = this._getInst(target[0]); if (this._get(inst, 'gotoCurrent') && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { var date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id); var inst = this._getInst(target[0]); inst['selected' + (period == 'M' ? 'Month' : 'Year')] = inst['draw' + (period == 'M' ? 'Month' : 'Year')] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } var inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $('a', td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); var inst = this._getInst(target[0]); this._selectDate(target, ''); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var target = $(id); var inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) inst.input.val(dateStr); this._updateAlternate(inst); var onSelect = this._get(inst, 'onSelect'); if (onSelect) onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback else if (inst.input) inst.input.trigger('change'); // fire the change event if (inst.inline) this._updateDatepicker(inst); else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) != 'object') inst.input.focus(); // restore focus this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altField = this._get(inst, 'altField'); if (altField) { // update alternate field too var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat'); var date = this._getDate(inst); var dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. @param date Date - the date to customise @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), '']; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. @param date Date - the date to get the week for @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); var time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. See formatDate below for the possible formats. @param format string - the expected format of the date @param value string - the date in the above format @param settings Object - attributes include: shortYearCutoff number - the cutoff year for determining the century (optional) dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) throw 'Invalid arguments'; value = (typeof value == 'object' ? value.toString() : value + ''); if (value == '') return null; var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff; shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; var year = -1; var month = -1; var day = -1; var doy = -1; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Extract a number from the string value var getNumber = function(match) { var isDoubled = lookAhead(match); var size = (match == '@' ? 14 : (match == '!' ? 20 : (match == 'y' && isDoubled ? 4 : (match == 'o' ? 3 : 2)))); var digits = new RegExp('^\\d{1,' + size + '}'); var num = value.substring(iValue).match(digits); if (!num) throw 'Missing number at position ' + iValue; iValue += num[0].length; return parseInt(num[0], 10); }; // Extract a name from the string value and convert to an index var getName = function(match, shortNames, longNames) { var names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); var index = -1; $.each(names, function (i, pair) { var name = pair[1]; if (value.substr(iValue, name.length).toLowerCase() == name.toLowerCase()) { index = pair[0]; iValue += name.length; return false; } }); if (index != -1) return index + 1; else throw 'Unknown name at position ' + iValue; }; // Confirm that a literal character matches the string value var checkLiteral = function() { if (value.charAt(iValue) != format.charAt(iFormat)) throw 'Unexpected literal at position ' + iValue; iValue++; }; var iValue = 0; for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else checkLiteral(); else switch (format.charAt(iFormat)) { case 'd': day = getNumber('d'); break; case 'D': getName('D', dayNamesShort, dayNames); break; case 'o': doy = getNumber('o'); break; case 'm': month = getNumber('m'); break; case 'M': month = getName('M', monthNamesShort, monthNames); break; case 'y': year = getNumber('y'); break; case '@': var date = new Date(getNumber('@')); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case '!': var date = new Date((getNumber('!') - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")) checkLiteral(); else literal = true; break; default: checkLiteral(); } } if (iValue < value.length){ throw "Extra/unparsed characters found in date: " + value.substring(iValue); } if (year == -1) year = new Date().getFullYear(); else if (year < 100) year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); if (doy > -1) { month = 1; day = doy; do { var dim = this._getDaysInMonth(year, month - 1); if (day <= dim) break; month++; day -= dim; } while (true); } var date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) throw 'Invalid date'; // E.g. 31/02/00 return date; }, /* Standard date formats. */ ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601) COOKIE: 'D, dd M yy', ISO_8601: 'yy-mm-dd', RFC_822: 'D, d M y', RFC_850: 'DD, dd-M-y', RFC_1036: 'D, d M y', RFC_1123: 'D, d M yy', RFC_2822: 'D, d M yy', RSS: 'D, d M y', // RFC 822 TICKS: '!', TIMESTAMP: '@', W3C: 'yy-mm-dd', // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. The format can be combinations of the following: d - day of month (no leading zero) dd - day of month (two digit) o - day of year (no leading zeros) oo - day of year (three digit) D - day name short DD - day name long m - month of year (no leading zero) mm - month of year (two digit) M - month name short MM - month name long y - year (two digit) yy - year (four digit) @ - Unix timestamp (ms since 01/01/1970) ! - Windows ticks (100ns since 01/01/0001) '...' - literal text '' - single quote @param format string - the desired format of the date @param date Date - the date value to format @param settings Object - attributes include: dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) return ''; var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Format a number, with leading zero if necessary var formatNumber = function(match, value, len) { var num = '' + value; if (lookAhead(match)) while (num.length < len) num = '0' + num; return num; }; // Format a name, short or long as requested var formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }; var output = ''; var literal = false; if (date) for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else output += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': output += formatNumber('d', date.getDate(), 2); break; case 'D': output += formatName('D', date.getDay(), dayNamesShort, dayNames); break; case 'o': output += formatNumber('o', Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); break; case 'm': output += formatNumber('m', date.getMonth() + 1, 2); break; case 'M': output += formatName('M', date.getMonth(), monthNamesShort, monthNames); break; case 'y': output += (lookAhead('y') ? date.getFullYear() : (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100); break; case '@': output += date.getTime(); break; case '!': output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) output += "'"; else literal = true; break; default: output += format.charAt(iFormat); } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var chars = ''; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; for (var iFormat = 0; iFormat < format.length; iFormat++) if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else chars += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': case 'm': case 'y': case '@': chars += '0123456789'; break; case 'D': case 'M': return null; // Accept anything case "'": if (lookAhead("'")) chars += "'"; else literal = true; break; default: chars += format.charAt(iFormat); } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() == inst.lastVal) { return; } var dateFormat = this._get(inst, 'dateFormat'); var dates = inst.lastVal = inst.input ? inst.input.val() : null; var date, defaultDate; date = defaultDate = this._getDefaultDate(inst); var settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { this.log(event); dates = (noDefault ? '' : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, 'defaultDate'), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }; var offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(); var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDate(); var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g; var matches = pattern.exec(offset); while (matches) { switch (matches[2] || 'd') { case 'd' : case 'D' : day += parseInt(matches[1],10); break; case 'w' : case 'W' : day += parseInt(matches[1],10) * 7; break; case 'm' : case 'M' : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case 'y': case 'Y' : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }; var newDate = (date == null || date === '' ? defaultDate : (typeof date == 'string' ? offsetString(date) : (typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); newDate = (newDate && newDate.toString() == 'Invalid Date' ? defaultDate : newDate); if (newDate) { newDate.setHours(0); newDate.setMinutes(0); newDate.setSeconds(0); newDate.setMilliseconds(0); } return this._daylightSavingAdjust(newDate); }, /* Handle switch to/from daylight saving. Hours may be non-zero on daylight saving cut-over: > 12 when midnight changeover, but then cannot generate midnight datetime, so jump to 1AM, otherwise reset. @param date (Date) the date to check @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) return null; date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !date; var origMonth = inst.selectedMonth; var origYear = inst.selectedYear; var newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = newDate.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); if ((origMonth != inst.selectedMonth || origYear != inst.selectedYear) && !noChange) this._notifyChange(inst); this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? '' : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var today = new Date(); today = this._daylightSavingAdjust( new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time var isRTL = this._get(inst, 'isRTL'); var showButtonPanel = this._get(inst, 'showButtonPanel'); var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext'); var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat'); var numMonths = this._getNumberOfMonths(inst); var showCurrentAtPos = this._get(inst, 'showCurrentAtPos'); var stepMonths = this._get(inst, 'stepMonths'); var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1); var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var drawMonth = inst.drawMonth - showCurrentAtPos; var drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; var prevText = this._get(inst, 'prevText'); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? '<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_' + dpuuid + '.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' + ' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>')); var nextText = this._get(inst, 'nextText'); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? '<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_' + dpuuid + '.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' + ' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>')); var currentText = this._get(inst, 'currentText'); var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_' + dpuuid + '.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : ''); var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') + (this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_' + dpuuid + '.datepicker._gotoToday(\'#' + inst.id + '\');"' + '>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : ''; var firstDay = parseInt(this._get(inst, 'firstDay'),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); var showWeek = this._get(inst, 'showWeek'); var dayNames = this._get(inst, 'dayNames'); var dayNamesShort = this._get(inst, 'dayNamesShort'); var dayNamesMin = this._get(inst, 'dayNamesMin'); var monthNames = this._get(inst, 'monthNames'); var monthNamesShort = this._get(inst, 'monthNamesShort'); var beforeShowDay = this._get(inst, 'beforeShowDay'); var showOtherMonths = this._get(inst, 'showOtherMonths'); var selectOtherMonths = this._get(inst, 'selectOtherMonths'); var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week; var defaultDate = this._getDefaultDate(inst); var html = ''; for (var row = 0; row < numMonths[0]; row++) { var group = ''; this.maxRows = 4; for (var col = 0; col < numMonths[1]; col++) { var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); var cornerClass = ' ui-corner-all'; var calender = ''; if (isMultiMonth) { calender += '<div class="ui-datepicker-group'; if (numMonths[1] > 1) switch (col) { case 0: calender += ' ui-datepicker-group-first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break; case numMonths[1]-1: calender += ' ui-datepicker-group-last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break; default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break; } calender += '">'; } calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' + (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') + (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers '</div><table class="ui-datepicker-calendar"><thead>' + '<tr>'; var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : ''); for (var dow = 0; dow < 7; dow++) { // days of the week var day = (dow + firstDay) % 7; thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' + '<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>'; } calender += thead + '</tr></thead><tbody>'; var daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth) inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; var curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate var numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += '<tr>'; var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' + this._get(inst, 'calculateWeek')(printDate) + '</td>'); for (var dow = 0; dow < 7; dow++) { // create date picker days var daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']); var otherMonth = (printDate.getMonth() != drawMonth); var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += '<td class="' + ((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate ' ' + this._dayOverClass : '') + // highlight selected day (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates (printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title (unselectable ? '' : ' onclick="DP_jQuery_' + dpuuid + '.datepicker._selectDay(\'#' + inst.id + '\',' + printDate.getMonth() + ',' + printDate.getFullYear() + ', this);return false;"') + '>' + // actions (otherMonth && !showOtherMonths ? '&#xa0;' : // display for other months (unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' + (printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') + (printDate.getTime() == currentDate.getTime() ? ' ui-state-active' : '') + // highlight selected day (otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + '</tr>'; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += '</tbody></table>' + (isMultiMonth ? '</div>' + ((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : ''); group += calender; } html += group; } html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : ''); inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var changeMonth = this._get(inst, 'changeMonth'); var changeYear = this._get(inst, 'changeYear'); var showMonthAfterYear = this._get(inst, 'showMonthAfterYear'); var html = '<div class="ui-datepicker-title">'; var monthHtml = ''; // month selection if (secondary || !changeMonth) monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>'; else { var inMinYear = (minDate && minDate.getFullYear() == drawYear); var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear); monthHtml += '<select class="ui-datepicker-month" ' + 'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' + '>'; for (var month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) monthHtml += '<option value="' + month + '"' + (month == drawMonth ? ' selected="selected"' : '') + '>' + monthNamesShort[month] + '</option>'; } monthHtml += '</select>'; } if (!showMonthAfterYear) html += monthHtml + (secondary || !(changeMonth && changeYear) ? '&#xa0;' : ''); // year selection if ( !inst.yearshtml ) { inst.yearshtml = ''; if (secondary || !changeYear) html += '<span class="ui-datepicker-year">' + drawYear + '</span>'; else { // determine range of years to display var years = this._get(inst, 'yearRange').split(':'); var thisYear = new Date().getFullYear(); var determineYear = function(value) { var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; var year = determineYear(years[0]); var endYear = Math.max(year, determineYear(years[1] || '')); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += '<select class="ui-datepicker-year" ' + 'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' + '>'; for (; year <= endYear; year++) { inst.yearshtml += '<option value="' + year + '"' + (year == drawYear ? ' selected="selected"' : '') + '>' + year + '</option>'; } inst.yearshtml += '</select>'; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, 'yearSuffix'); if (showMonthAfterYear) html += (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '') + monthHtml; html += '</div>'; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period == 'Y' ? offset : 0); var month = inst.drawMonth + (period == 'M' ? offset : 0); var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period == 'D' ? offset : 0); var date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period == 'M' || period == 'Y') this._notifyChange(inst); }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var newDate = (minDate && date < minDate ? minDate : date); newDate = (maxDate && newDate > maxDate ? maxDate : newDate); return newDate; }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, 'onChangeMonthYear'); if (onChange) onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, 'numberOfMonths'); return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + 'Date'), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst); var date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime())); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, 'shortYearCutoff'); shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'), monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day == 'object' ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function bindHover(dpDiv) { var selector = 'button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a'; return dpDiv.bind('mouseout', function(event) { var elem = $( event.target ).closest( selector ); if ( !elem.length ) { return; } elem.removeClass( "ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover" ); }) .bind('mouseover', function(event) { var elem = $( event.target ).closest( selector ); if ($.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0]) || !elem.length ) { return; } elem.parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover'); elem.addClass('ui-state-hover'); if (elem.hasClass('ui-datepicker-prev')) elem.addClass('ui-datepicker-prev-hover'); if (elem.hasClass('ui-datepicker-next')) elem.addClass('ui-datepicker-next-hover'); }); } /* jQuery extend now ignores nulls! */ function extendRemove(target, props) { $.extend(target, props); for (var name in props) if (props[name] == null || props[name] == undefined) target[name] = props[name]; return target; }; /* Determine whether an object is an array. */ function isArray(a) { return (a && (($.browser.safari && typeof a == 'object' && a.length) || (a.constructor && a.constructor.toString().match(/\Array\(\)/)))); }; /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick). find('body').append($.datepicker.dpDiv); $.datepicker.initialized = true; } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget')) return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string') return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); return this.each(function() { typeof options == 'string' ? $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.8.17"; // Workaround for #4055 // Add another global to avoid noConflict issues with inline event handlers window['DP_jQuery_' + dpuuid] = $; })(jQuery);
JavaScript
//Style the file inputs (function($) { $.fn.filestyle = function(options) { /* TODO: This should not override CSS. */ var settings = { width : 210 }; if(options) { $.extend(settings, options); }; return this.each(function() { var self = this; var wrapper = $("<span>") .css({ "width": settings.imagewidth + "px", "height": settings.imageheight + "px", "background": "url(" + settings.image + ") no-repeat " }); var filename = $('<input class="file" value="Der er ikke valgt nogen fil">') .addClass($(self).attr("class")) .css({ "width": settings.width + "px" }); $(self).before(filename); $(self).wrap(wrapper); $(self).css({ "position": "relative", "height": settings.imageheight + "px", "width": settings.width + "px", "display": "inline", "cursor": "pointer", "opacity": "0.0" }); if ($.browser.mozilla) { if (/Win/.test(navigator.platform)) { $(self).css("margin-left", "-260px"); } else { $(self).css("margin-left", "-168px"); }; } else { $(self).css("margin-left", settings.imagewidth - settings.width + "px"); }; $(self).bind("change", function() { filename.val($(self).val()); }); }); }; })(jQuery);
JavaScript
/* Javscript Document */
JavaScript
/*global window, localStorage, fontSizeTitle, bigger, reset, smaller, biggerTitle, resetTitle, smallerTitle, Cookie */ var prefsLoaded = false; var defaultFontSize = 100; var currentFontSize = defaultFontSize; var fontSizeTitle; var bigger; var smaller; var reset; var biggerTitle; var smallerTitle; var resetTitle; Object.append(Browser.Features, { localstorage: (function() { return ('localStorage' in window) && window.localStorage !== null; })() }); function setFontSize(fontSize) { document.body.style.fontSize = fontSize + '%'; } function changeFontSize(sizeDifference) { currentFontSize = parseInt(currentFontSize, 10) + parseInt(sizeDifference * 5, 10); if (currentFontSize > 180) { currentFontSize = 180; } else if (currentFontSize < 60) { currentFontSize = 60; } setFontSize(currentFontSize); } function revertStyles() { currentFontSize = defaultFontSize; changeFontSize(0); } function writeFontSize(value) { if (Browser.Features.localstorage) { localStorage.fontSize = value; } else { Cookie.write("fontSize", value, {duration: 180}); } } function readFontSize() { if (Browser.Features.localstorage) { return localStorage.fontSize; } else { return Cookie.read("fontSize"); } } function setUserOptions() { if (!prefsLoaded) { var size = readFontSize(); currentFontSize = size ? size : defaultFontSize; setFontSize(currentFontSize); prefsLoaded = true; } } function addControls() { var container = document.id('fontsize'); var content = '<h3>'+ fontSizeTitle +'</h3><p><a title="'+ biggerTitle +'" href="#" onclick="changeFontSize(2); return false">'+ bigger +'</a><span class="unseen">.</span><a href="#" title="'+resetTitle+'" onclick="revertStyles(); return false">'+ reset +'</a><span class="unseen">.</span><a href="#" title="'+ smallerTitle +'" onclick="changeFontSize(-2); return false">'+ smaller +'</a></p>'; container.set('html', content); } function saveSettings() { writeFontSize(currentFontSize); } window.addEvent('domready', setUserOptions); window.addEvent('domready', addControls); window.addEvent('unload', saveSettings);
JavaScript
// Angie Radtke 2009 // /*global window, localStorage, Cookie, altopen, altclose, big, small, rightopen, rightclose, bildauf, bildzu */ Object.append(Browser.Features, { localstorage: (function() { return ('localStorage' in window) && window.localStorage !== null; })() }); function saveIt(name) { var x = document.id(name).style.display; if (!x) { alert('No cookie available'); } else { if (Browser.Features.localstorage) { localStorage[name] = x; } else { Cookie.write(name, x, {duration: 7}); } } } function readIt(name) { if (Browser.Features.localstorage) { return localStorage[name]; } else { return Cookie.read(name); } } function wrapperwidth(width) { document.id('wrapper').setStyle('width', width); } // add Wai-Aria landmark-roles window.addEvent('domready', function () { if (document.id('nav')) { document.id('nav').setProperties( { role : 'navigation' }); } if (document.id('mod-search-searchword')) { document.id(document.id('mod-search-searchword').form).set( { role : 'search' }); } if (document.id('main')) { document.id('main').setProperties( { role : 'main' }); } if (document.id('right')) { document.id('right').setProperties( { role : 'contentinfo' }); } }); window.addEvent('domready', function() { // get ankers var myankers = document.id(document.body).getElements('a.opencloselink'); myankers.each(function(element) { element.setProperty('role', 'tab'); var myid = element.getProperty('id'); myid = myid.split('_'); myid = 'module_' + myid[1]; document.id(element).setProperty('aria-controls', myid); }); var list = document.id(document.body).getElements('div.moduletable_js'); list.each(function(element) { if (element.getElement('div.module_content')) { var el = element.getElement('div.module_content'); el.setProperty('role', 'tabpanel'); var myid = el.getProperty('id'); myid = myid.split('_'); myid = 'link_' + myid[1]; el.setProperty('aria-labelledby', myid); var myclass = el.get('class'); var one = myclass.split(' '); // search for active menu-item var listelement = el.getElement('a.active'); var unique = el.id; var nocookieset = readIt(unique); if ((listelement) || ((one[1] == 'open') && (nocookieset == null))) { el.setStyle('display', 'block'); var eltern = el.getParent(); var elternh = eltern.getElement('h3'); var elternbild = eltern.getElement('img'); elternbild.setProperties( { alt : altopen, src : bildzu }); elternbild.focus(); } else { el.setStyle('display', 'none'); el.setProperty('aria-expanded', 'false'); } unique = el.id; var cookieset = readIt(unique); if (cookieset == 'block') { el.setStyle('display', 'block'); el.setProperty('aria-expanded', 'true'); } } }); }); window.addEvent('domready', function() { var what = document.id('right'); // if rightcolumn if (what != null) { var whatid = what.id; var rightcookie = readIt(whatid); if (rightcookie == 'none') { what.setStyle('display', 'none'); document.id('nav').addClass('leftbigger'); wrapperwidth(big); var grafik = document.id('bild'); grafik.innerHTML = rightopen; grafik.focus(); } } }); function auf(key) { var el = document.id(key); if (el.style.display == 'none') { el.setStyle('display', 'block'); el.setProperty('aria-expanded', 'true'); if (key != 'right') { el.slide('hide').slide('in'); el.getParent().setProperty('class', 'slide'); eltern = el.getParent().getParent(); elternh = eltern.getElement('h3'); elternh.addClass('high'); elternbild = eltern.getElement('img'); // elternbild.focus(); el.focus(); elternbild.setProperties( { alt : altopen, src : bildzu }); } if (key == 'right') { document.id('right').setStyle('display', 'block'); wrapperwidth(small); document.id('nav').removeClass('leftbigger'); grafik = document.id('bild'); document.id('bild').innerHTML = rightclose; grafik.focus(); } } else { el.setStyle('display', 'none'); el.setProperty('aria-expanded', 'false'); el.removeClass('open'); if (key != 'right') { eltern = el.getParent().getParent(); elternh = eltern.getElement('h3'); elternh.removeClass('high'); elternbild = eltern.getElement('img'); // alert(bildauf); elternbild.setProperties( { alt : altclose, src : bildauf }); elternbild.focus(); } if (key == 'right') { document.id('right').setStyle('display', 'none'); wrapperwidth(big); document.id('nav').addClass('leftbigger'); grafik = document.id('bild'); grafik.innerHTML = rightopen; grafik.focus(); } } // write cookie saveIt(key); } // ########### Tabfunctions #################### window.addEvent('domready', function() { var alldivs = document.id(document.body).getElements('div.tabcontent'); var outerdivs = document.id(document.body).getElements('div.tabouter'); outerdivs = outerdivs.getProperty('id'); for (var i = 0; i < outerdivs.length; i++) { alldivs = document.id(outerdivs[i]).getElements('div.tabcontent'); count = 0; alldivs.each(function(element) { count++; var el = document.id(element); el.setProperty('role', 'tabpanel'); el.setProperty('aria-hidden', 'false'); el.setProperty('aria-expanded', 'true'); elid = el.getProperty('id'); elid = elid.split('_'); elid = 'link_' + elid[1]; el.setProperty('aria-labelledby', elid); if (count != 1) { el.addClass('tabclosed').removeClass('tabopen'); el.setProperty('aria-hidden', 'true'); el.setProperty('aria-expanded', 'false'); } }); countankers = 0; allankers = document.id(outerdivs[i]).getElement('ul.tabs').getElements('a'); allankers.each(function(element) { countankers++; var el = document.id(element); el.setProperty('aria-selected', 'true'); el.setProperty('role', 'tab'); linkid = el.getProperty('id'); moduleid = linkid.split('_'); moduleid = 'module_' + moduleid[1]; el.setProperty('aria-controls', moduleid); if (countankers != 1) { el.addClass('linkclosed').removeClass('linkopen'); el.setProperty('aria-selected', 'false'); } }); } }); function tabshow(elid) { var el = document.id(elid); var outerdiv = el.getParent(); outerdiv = outerdiv.getProperty('id'); var alldivs = document.id(outerdiv).getElements('div.tabcontent'); var liste = document.id(outerdiv).getElement('ul.tabs'); liste.getElements('a').setProperty('aria-selected', 'false'); alldivs.each(function(element) { element.addClass('tabclosed').removeClass('tabopen'); element.setProperty('aria-hidden', 'true'); element.setProperty('aria-expanded', 'false'); }); el.addClass('tabopen').removeClass('tabclosed'); el.setProperty('aria-hidden', 'false'); el.setProperty('aria-expanded', 'true'); el.focus(); var getid = elid.split('_'); var activelink = 'link_' + getid[1]; document.id(activelink).setProperty('aria-selected', 'true'); liste.getElements('a').addClass('linkclosed').removeClass('linkopen'); document.id(activelink).addClass('linkopen').removeClass('linkclosed'); } function nexttab(el) { var outerdiv = document.id(el).getParent(); var liste = outerdiv.getElement('ul.tabs'); var getid = el.split('_'); var activelink = 'link_' + getid[1]; var aktiverlink = document.id(activelink).getProperty('aria-selected'); var tablinks = liste.getElements('a').getProperty('id'); for ( var i = 0; i < tablinks.length; i++) { if (tablinks[i] == activelink) { if (document.id(tablinks[i + 1]) != null) { document.id(tablinks[i + 1]).onclick(); break; } } } }
JavaScript
/** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ var plg_quickicon_jupdatecheck_ajax_structure = {}; window.addEvent('domready', function(){ plg_quickicon_jupdatecheck_ajax_structure = { onSuccess: function(msg, responseXML) { try { var updateInfoList = JSON.decode(msg, true); } catch(e) { // An error occured document.id('plg_quickicon_joomlaupdate').getElements('img').setProperty('src',plg_quickicon_joomlaupdate_img.ERROR); document.id('plg_quickicon_joomlaupdate').getElements('span').set('html', plg_quickicon_joomlaupdate_text.ERROR); } if (updateInfoList instanceof Array) { if (updateInfoList.length < 1) { // No updates document.id('plg_quickicon_joomlaupdate').getElements('img').setProperty('src',plg_quickicon_joomlaupdate_img.UPTODATE); document.id('plg_quickicon_joomlaupdate').getElements('span').set('html', plg_quickicon_joomlaupdate_text.UPTODATE); } else { var updateInfo = updateInfoList.shift(); if (updateInfo.version != plg_quickicon_jupdatecheck_jversion) { var updateString = plg_quickicon_joomlaupdate_text.UPDATEFOUND.replace("%s", updateInfo.version+""); document.id('plg_quickicon_joomlaupdate').getElements('img').setProperty('src',plg_quickicon_joomlaupdate_img.UPDATEFOUND); document.id('plg_quickicon_joomlaupdate').getElements('span').set('html', updateString); } else { document.id('plg_quickicon_joomlaupdate').getElements('img').setProperty('src',plg_quickicon_joomlaupdate_img.UPTODATE); document.id('plg_quickicon_joomlaupdate').getElements('span').set('html', plg_quickicon_joomlaupdate_text.UPTODATE); } } } else { // An error occured document.id('plg_quickicon_joomlaupdate').getElements('img').setProperty('src',plg_quickicon_joomlaupdate_img.ERROR); document.id('plg_quickicon_joomlaupdate').getElements('span').set('html', plg_quickicon_joomlaupdate_text.ERROR); } }, onFailure: function(req) { // An error occured document.id('plg_quickicon_joomlaupdate').getElements('img').setProperty('src',plg_quickicon_joomlaupdate_img.ERROR); document.id('plg_quickicon_joomlaupdate').getElements('span').set('html', plg_quickicon_joomlaupdate_text.ERROR); }, url: plg_quickicon_joomlaupdate_ajax_url }; setTimeout("ajax_object = new Request(plg_quickicon_jupdatecheck_ajax_structure); ajax_object.send('eid=700&cache_timeout=3600');", 2000); });
JavaScript
/* Demonstration of embedding CodeMirror in a bigger application. The * interface defined here is a mess of prompts and confirms, and * should probably not be used in a real project. */ function MirrorFrame(place, options) { this.home = document.createElement("div"); if (place.appendChild) place.appendChild(this.home); else place(this.home); var self = this; function makeButton(name, action) { var button = document.createElement("input"); button.type = "button"; button.value = name; self.home.appendChild(button); button.onclick = function(){self[action].call(self);}; } makeButton("Search", "search"); makeButton("Replace", "replace"); makeButton("Current line", "line"); makeButton("Jump to line", "jump"); makeButton("Insert constructor", "macro"); makeButton("Indent all", "reindent"); this.mirror = new CodeMirror(this.home, options); } MirrorFrame.prototype = { search: function() { var text = prompt("Enter search term:", ""); if (!text) return; var first = true; do { var cursor = this.mirror.getSearchCursor(text, first); first = false; while (cursor.findNext()) { cursor.select(); if (!confirm("Search again?")) return; } } while (confirm("End of document reached. Start over?")); }, replace: function() { // This is a replace-all, but it is possible to implement a // prompting replace. var from = prompt("Enter search string:", ""), to; if (from) to = prompt("What should it be replaced with?", ""); if (to == null) return; var cursor = this.mirror.getSearchCursor(from, false); while (cursor.findNext()) cursor.replace(to); }, jump: function() { var line = prompt("Jump to line:", ""); if (line && !isNaN(Number(line))) this.mirror.jumpToLine(Number(line)); }, line: function() { alert("The cursor is currently at line " + this.mirror.currentLine()); this.mirror.focus(); }, macro: function() { var name = prompt("Name your constructor:", ""); if (name) this.mirror.replaceSelection("function " + name + "() {\n \n}\n\n" + name + ".prototype = {\n \n};\n"); }, reindent: function() { this.mirror.reindent(); } };
JavaScript
var HTMLMixedParser = Editor.Parser = (function() { // tags that trigger seperate parsers var triggers = { "script": "JSParser", "style": "CSSParser" }; function checkDependencies() { var parsers = ['XMLParser']; for (var p in triggers) parsers.push(triggers[p]); for (var i in parsers) { if (!window[parsers[i]]) throw new Error(parsers[i] + " parser must be loaded for HTML mixed mode to work."); } XMLParser.configure({useHTMLKludges: true}); } function parseMixed(stream) { checkDependencies(); var htmlParser = XMLParser.make(stream), localParser = null, inTag = false; var iter = {next: top, copy: copy}; function top() { var token = htmlParser.next(); if (token.content == "<") inTag = true; else if (token.style == "xml-tagname" && inTag === true) inTag = token.content.toLowerCase(); else if (token.content == ">") { if (triggers[inTag]) { var parser = window[triggers[inTag]]; iter.next = local(parser, "</" + inTag); } inTag = false; } return token; } function local(parser, tag) { var baseIndent = htmlParser.indentation(); localParser = parser.make(stream, baseIndent + indentUnit); return function() { if (stream.lookAhead(tag, false, false, true)) { localParser = null; iter.next = top; return top(); } var token = localParser.next(); var lt = token.value.lastIndexOf("<"), sz = Math.min(token.value.length - lt, tag.length); if (lt != -1 && token.value.slice(lt, lt + sz).toLowerCase() == tag.slice(0, sz) && stream.lookAhead(tag.slice(sz), false, false, true)) { stream.push(token.value.slice(lt)); token.value = token.value.slice(0, lt); } if (token.indentation) { var oldIndent = token.indentation; token.indentation = function(chars) { if (chars == "</") return baseIndent; else return oldIndent(chars); }; } return token; }; } function copy() { var _html = htmlParser.copy(), _local = localParser && localParser.copy(), _next = iter.next, _inTag = inTag; return function(_stream) { stream = _stream; htmlParser = _html(_stream); localParser = _local && _local(_stream); iter.next = _next; inTag = _inTag; return iter; }; } return iter; } return { make: parseMixed, electricChars: "{}/:", configure: function(obj) { if (obj.triggers) triggers = obj.triggers; } }; })();
JavaScript
/* Simple parser for CSS */ var CSSParser = Editor.Parser = (function() { var tokenizeCSS = (function() { function normal(source, setState) { var ch = source.next(); if (ch == "@") { source.nextWhileMatches(/\w/); return "css-at"; } else if (ch == "/" && source.equals("*")) { setState(inCComment); return null; } else if (ch == "<" && source.equals("!")) { setState(inSGMLComment); return null; } else if (ch == "=") { return "css-compare"; } else if (source.equals("=") && (ch == "~" || ch == "|")) { source.next(); return "css-compare"; } else if (ch == "\"" || ch == "'") { setState(inString(ch)); return null; } else if (ch == "#") { source.nextWhileMatches(/\w/); return "css-hash"; } else if (ch == "!") { source.nextWhileMatches(/[ \t]/); source.nextWhileMatches(/\w/); return "css-important"; } else if (/\d/.test(ch)) { source.nextWhileMatches(/[\w.%]/); return "css-unit"; } else if (/[,.+>*\/]/.test(ch)) { return "css-select-op"; } else if (/[;{}:\[\]]/.test(ch)) { return "css-punctuation"; } else { source.nextWhileMatches(/[\w\\\-_]/); return "css-identifier"; } } function inCComment(source, setState) { var maybeEnd = false; while (!source.endOfLine()) { var ch = source.next(); if (maybeEnd && ch == "/") { setState(normal); break; } maybeEnd = (ch == "*"); } return "css-comment"; } function inSGMLComment(source, setState) { var dashes = 0; while (!source.endOfLine()) { var ch = source.next(); if (dashes >= 2 && ch == ">") { setState(normal); break; } dashes = (ch == "-") ? dashes + 1 : 0; } return "css-comment"; } function inString(quote) { return function(source, setState) { var escaped = false; while (!source.endOfLine()) { var ch = source.next(); if (ch == quote && !escaped) break; escaped = !escaped && ch == "\\"; } if (!escaped) setState(normal); return "css-string"; }; } return function(source, startState) { return tokenizer(source, startState || normal); }; })(); function indentCSS(inBraces, inRule, base) { return function(nextChars) { if (!inBraces || /^\}/.test(nextChars)) return base; else if (inRule) return base + indentUnit * 2; else return base + indentUnit; }; } // This is a very simplistic parser -- since CSS does not really // nest, it works acceptably well, but some nicer colouroing could // be provided with a more complicated parser. function parseCSS(source, basecolumn) { basecolumn = basecolumn || 0; var tokens = tokenizeCSS(source); var inBraces = false, inRule = false, inDecl = false;; var iter = { next: function() { var token = tokens.next(), style = token.style, content = token.content; if (style == "css-hash") style = token.style = inRule ? "css-colorcode" : "css-identifier"; if (style == "css-identifier") { if (inRule) token.style = "css-value"; else if (!inBraces && !inDecl) token.style = "css-selector"; } if (content == "\n") token.indentation = indentCSS(inBraces, inRule, basecolumn); if (content == "{" && inDecl == "@media") inDecl = false; else if (content == "{") inBraces = true; else if (content == "}") inBraces = inRule = inDecl = false; else if (content == ";") inRule = inDecl = false; else if (inBraces && style != "css-comment" && style != "whitespace") inRule = true; else if (!inBraces && style == "css-at") inDecl = content; return token; }, copy: function() { var _inBraces = inBraces, _inRule = inRule, _tokenState = tokens.state; return function(source) { tokens = tokenizeCSS(source, _tokenState); inBraces = _inBraces; inRule = _inRule; return iter; }; } }; return iter; } return {make: parseCSS, electricChars: "}"}; })();
JavaScript
/* Functionality for finding, storing, and restoring selections * * This does not provide a generic API, just the minimal functionality * required by the CodeMirror system. */ // Namespace object. var select = {}; (function() { select.ie_selection = document.selection && document.selection.createRangeCollection; // Find the 'top-level' (defined as 'a direct child of the node // passed as the top argument') node that the given node is // contained in. Return null if the given node is not inside the top // node. function topLevelNodeAt(node, top) { while (node && node.parentNode != top) node = node.parentNode; return node; } // Find the top-level node that contains the node before this one. function topLevelNodeBefore(node, top) { while (!node.previousSibling && node.parentNode != top) node = node.parentNode; return topLevelNodeAt(node.previousSibling, top); } var fourSpaces = "\u00a0\u00a0\u00a0\u00a0"; select.scrollToNode = function(node, cursor) { if (!node) return; var element = node, body = document.body, html = document.documentElement, atEnd = !element.nextSibling || !element.nextSibling.nextSibling || !element.nextSibling.nextSibling.nextSibling; // In Opera (and recent Webkit versions), BR elements *always* // have a offsetTop property of zero. var compensateHack = 0; while (element && !element.offsetTop) { compensateHack++; element = element.previousSibling; } // atEnd is another kludge for these browsers -- if the cursor is // at the end of the document, and the node doesn't have an // offset, just scroll to the end. if (compensateHack == 0) atEnd = false; // WebKit has a bad habit of (sometimes) happily returning bogus // offsets when the document has just been changed. This seems to // always be 5/5, so we don't use those. if (webkit && element && element.offsetTop == 5 && element.offsetLeft == 5) return; var y = compensateHack * (element ? element.offsetHeight : 0), x = 0, width = (node ? node.offsetWidth : 0), pos = element; while (pos && pos.offsetParent) { y += pos.offsetTop; // Don't count X offset for <br> nodes if (!isBR(pos)) x += pos.offsetLeft; pos = pos.offsetParent; } var scroll_x = body.scrollLeft || html.scrollLeft || 0, scroll_y = body.scrollTop || html.scrollTop || 0, scroll = false, screen_width = window.innerWidth || html.clientWidth || 0; if (cursor || width < screen_width) { if (cursor) { var off = select.offsetInNode(node), size = nodeText(node).length; if (size) x += width * (off / size); } var screen_x = x - scroll_x; if (screen_x < 0 || screen_x > screen_width) { scroll_x = x; scroll = true; } } var screen_y = y - scroll_y; if (screen_y < 0 || atEnd || screen_y > (window.innerHeight || html.clientHeight || 0) - 50) { scroll_y = atEnd ? 1e6 : y; scroll = true; } if (scroll) window.scrollTo(scroll_x, scroll_y); }; select.scrollToCursor = function(container) { select.scrollToNode(select.selectionTopNode(container, true) || container.firstChild, true); }; // Used to prevent restoring a selection when we do not need to. var currentSelection = null; select.snapshotChanged = function() { if (currentSelection) currentSelection.changed = true; }; // Find the 'leaf' node (BR or text) after the given one. function baseNodeAfter(node) { var next = node.nextSibling; if (next) { while (next.firstChild) next = next.firstChild; if (next.nodeType == 3 || isBR(next)) return next; else return baseNodeAfter(next); } else { var parent = node.parentNode; while (parent && !parent.nextSibling) parent = parent.parentNode; return parent && baseNodeAfter(parent); } } // This is called by the code in editor.js whenever it is replacing // a text node. The function sees whether the given oldNode is part // of the current selection, and updates this selection if it is. // Because nodes are often only partially replaced, the length of // the part that gets replaced has to be taken into account -- the // selection might stay in the oldNode if the newNode is smaller // than the selection's offset. The offset argument is needed in // case the selection does move to the new object, and the given // length is not the whole length of the new node (part of it might // have been used to replace another node). select.snapshotReplaceNode = function(from, to, length, offset) { if (!currentSelection) return; function replace(point) { if (from == point.node) { currentSelection.changed = true; if (length && point.offset > length) { point.offset -= length; } else { point.node = to; point.offset += (offset || 0); } } else if (select.ie_selection && point.offset == 0 && point.node == baseNodeAfter(from)) { currentSelection.changed = true; } } replace(currentSelection.start); replace(currentSelection.end); }; select.snapshotMove = function(from, to, distance, relative, ifAtStart) { if (!currentSelection) return; function move(point) { if (from == point.node && (!ifAtStart || point.offset == 0)) { currentSelection.changed = true; point.node = to; if (relative) point.offset = Math.max(0, point.offset + distance); else point.offset = distance; } } move(currentSelection.start); move(currentSelection.end); }; // Most functions are defined in two ways, one for the IE selection // model, one for the W3C one. if (select.ie_selection) { function selRange() { var sel = document.selection; if (!sel) return null; if (sel.createRange) return sel.createRange(); else return sel.createTextRange(); } function selectionNode(start) { var range = selRange(); range.collapse(start); function nodeAfter(node) { var found = null; while (!found && node) { found = node.nextSibling; node = node.parentNode; } return nodeAtStartOf(found); } function nodeAtStartOf(node) { while (node && node.firstChild) node = node.firstChild; return {node: node, offset: 0}; } var containing = range.parentElement(); if (!isAncestor(document.body, containing)) return null; if (!containing.firstChild) return nodeAtStartOf(containing); var working = range.duplicate(); working.moveToElementText(containing); working.collapse(true); for (var cur = containing.firstChild; cur; cur = cur.nextSibling) { if (cur.nodeType == 3) { var size = cur.nodeValue.length; working.move("character", size); } else { working.moveToElementText(cur); working.collapse(false); } var dir = range.compareEndPoints("StartToStart", working); if (dir == 0) return nodeAfter(cur); if (dir == 1) continue; if (cur.nodeType != 3) return nodeAtStartOf(cur); working.setEndPoint("StartToEnd", range); return {node: cur, offset: size - working.text.length}; } return nodeAfter(containing); } select.markSelection = function() { currentSelection = null; var sel = document.selection; if (!sel) return; var start = selectionNode(true), end = selectionNode(false); if (!start || !end) return; currentSelection = {start: start, end: end, changed: false}; }; select.selectMarked = function() { if (!currentSelection || !currentSelection.changed) return; function makeRange(point) { var range = document.body.createTextRange(), node = point.node; if (!node) { range.moveToElementText(document.body); range.collapse(false); } else if (node.nodeType == 3) { range.moveToElementText(node.parentNode); var offset = point.offset; while (node.previousSibling) { node = node.previousSibling; offset += (node.innerText || "").length; } range.move("character", offset); } else { range.moveToElementText(node); range.collapse(true); } return range; } var start = makeRange(currentSelection.start), end = makeRange(currentSelection.end); start.setEndPoint("StartToEnd", end); start.select(); }; select.offsetInNode = function(node) { var range = selRange(); if (!range) return 0; var range2 = range.duplicate(); try {range2.moveToElementText(node);} catch(e){return 0;} range.setEndPoint("StartToStart", range2); return range.text.length; }; // Get the top-level node that one end of the cursor is inside or // after. Note that this returns false for 'no cursor', and null // for 'start of document'. select.selectionTopNode = function(container, start) { var range = selRange(); if (!range) return false; var range2 = range.duplicate(); range.collapse(start); var around = range.parentElement(); if (around && isAncestor(container, around)) { // Only use this node if the selection is not at its start. range2.moveToElementText(around); if (range.compareEndPoints("StartToStart", range2) == 1) return topLevelNodeAt(around, container); } // Move the start of a range to the start of a node, // compensating for the fact that you can't call // moveToElementText with text nodes. function moveToNodeStart(range, node) { if (node.nodeType == 3) { var count = 0, cur = node.previousSibling; while (cur && cur.nodeType == 3) { count += cur.nodeValue.length; cur = cur.previousSibling; } if (cur) { try{range.moveToElementText(cur);} catch(e){return false;} range.collapse(false); } else range.moveToElementText(node.parentNode); if (count) range.move("character", count); } else { try{range.moveToElementText(node);} catch(e){return false;} } return true; } // Do a binary search through the container object, comparing // the start of each node to the selection var start = 0, end = container.childNodes.length - 1; while (start < end) { var middle = Math.ceil((end + start) / 2), node = container.childNodes[middle]; if (!node) return false; // Don't ask. IE6 manages this sometimes. if (!moveToNodeStart(range2, node)) return false; if (range.compareEndPoints("StartToStart", range2) == 1) start = middle; else end = middle - 1; } if (start == 0) { var test1 = selRange(), test2 = test1.duplicate(); try { test2.moveToElementText(container); } catch(exception) { return null; } if (test1.compareEndPoints("StartToStart", test2) == 0) return null; } return container.childNodes[start] || null; }; // Place the cursor after this.start. This is only useful when // manually moving the cursor instead of restoring it to its old // position. select.focusAfterNode = function(node, container) { var range = document.body.createTextRange(); range.moveToElementText(node || container); range.collapse(!node); range.select(); }; select.somethingSelected = function() { var range = selRange(); return range && (range.text != ""); }; function insertAtCursor(html) { var range = selRange(); if (range) { range.pasteHTML(html); range.collapse(false); range.select(); } } // Used to normalize the effect of the enter key, since browsers // do widely different things when pressing enter in designMode. select.insertNewlineAtCursor = function() { insertAtCursor("<br>"); }; select.insertTabAtCursor = function() { insertAtCursor(fourSpaces); }; // Get the BR node at the start of the line on which the cursor // currently is, and the offset into the line. Returns null as // node if cursor is on first line. select.cursorPos = function(container, start) { var range = selRange(); if (!range) return null; var topNode = select.selectionTopNode(container, start); while (topNode && !isBR(topNode)) topNode = topNode.previousSibling; var range2 = range.duplicate(); range.collapse(start); if (topNode) { range2.moveToElementText(topNode); range2.collapse(false); } else { // When nothing is selected, we can get all kinds of funky errors here. try { range2.moveToElementText(container); } catch (e) { return null; } range2.collapse(true); } range.setEndPoint("StartToStart", range2); return {node: topNode, offset: range.text.length}; }; select.setCursorPos = function(container, from, to) { function rangeAt(pos) { var range = document.body.createTextRange(); if (!pos.node) { range.moveToElementText(container); range.collapse(true); } else { range.moveToElementText(pos.node); range.collapse(false); } range.move("character", pos.offset); return range; } var range = rangeAt(from); if (to && to != from) range.setEndPoint("EndToEnd", rangeAt(to)); range.select(); } // Some hacks for storing and re-storing the selection when the editor loses and regains focus. select.getBookmark = function (container) { var from = select.cursorPos(container, true), to = select.cursorPos(container, false); if (from && to) return {from: from, to: to}; }; // Restore a stored selection. select.setBookmark = function(container, mark) { if (!mark) return; select.setCursorPos(container, mark.from, mark.to); }; } // W3C model else { // Find the node right at the cursor, not one of its // ancestors with a suitable offset. This goes down the DOM tree // until a 'leaf' is reached (or is it *up* the DOM tree?). function innerNode(node, offset) { while (node.nodeType != 3 && !isBR(node)) { var newNode = node.childNodes[offset] || node.nextSibling; offset = 0; while (!newNode && node.parentNode) { node = node.parentNode; newNode = node.nextSibling; } node = newNode; if (!newNode) break; } return {node: node, offset: offset}; } // Store start and end nodes, and offsets within these, and refer // back to the selection object from those nodes, so that this // object can be updated when the nodes are replaced before the // selection is restored. select.markSelection = function () { var selection = window.getSelection(); if (!selection || selection.rangeCount == 0) return (currentSelection = null); var range = selection.getRangeAt(0); currentSelection = { start: innerNode(range.startContainer, range.startOffset), end: innerNode(range.endContainer, range.endOffset), changed: false }; }; select.selectMarked = function () { var cs = currentSelection; // on webkit-based browsers, it is apparently possible that the // selection gets reset even when a node that is not one of the // endpoints get messed with. the most common situation where // this occurs is when a selection is deleted or overwitten. we // check for that here. function focusIssue() { if (cs.start.node == cs.end.node && cs.start.offset == cs.end.offset) { var selection = window.getSelection(); if (!selection || selection.rangeCount == 0) return true; var range = selection.getRangeAt(0), point = innerNode(range.startContainer, range.startOffset); return cs.start.node != point.node || cs.start.offset != point.offset; } } if (!cs || !(cs.changed || (webkit && focusIssue()))) return; var range = document.createRange(); function setPoint(point, which) { if (point.node) { // Some magic to generalize the setting of the start and end // of a range. if (point.offset == 0) range["set" + which + "Before"](point.node); else range["set" + which](point.node, point.offset); } else { range.setStartAfter(document.body.lastChild || document.body); } } setPoint(cs.end, "End"); setPoint(cs.start, "Start"); selectRange(range); }; // Helper for selecting a range object. function selectRange(range) { var selection = window.getSelection(); if (!selection) return; selection.removeAllRanges(); selection.addRange(range); } function selectionRange() { var selection = window.getSelection(); if (!selection || selection.rangeCount == 0) return false; else return selection.getRangeAt(0); } // Finding the top-level node at the cursor in the W3C is, as you // can see, quite an involved process. select.selectionTopNode = function(container, start) { var range = selectionRange(); if (!range) return false; var node = start ? range.startContainer : range.endContainer; var offset = start ? range.startOffset : range.endOffset; // Work around (yet another) bug in Opera's selection model. if (window.opera && !start && range.endContainer == container && range.endOffset == range.startOffset + 1 && container.childNodes[range.startOffset] && isBR(container.childNodes[range.startOffset])) offset--; // For text nodes, we look at the node itself if the cursor is // inside, or at the node before it if the cursor is at the // start. if (node.nodeType == 3){ if (offset > 0) return topLevelNodeAt(node, container); else return topLevelNodeBefore(node, container); } // Occasionally, browsers will return the HTML node as // selection. If the offset is 0, we take the start of the frame // ('after null'), otherwise, we take the last node. else if (node.nodeName.toUpperCase() == "HTML") { return (offset == 1 ? null : container.lastChild); } // If the given node is our 'container', we just look up the // correct node by using the offset. else if (node == container) { return (offset == 0) ? null : node.childNodes[offset - 1]; } // In any other case, we have a regular node. If the cursor is // at the end of the node, we use the node itself, if it is at // the start, we use the node before it, and in any other // case, we look up the child before the cursor and use that. else { if (offset == node.childNodes.length) return topLevelNodeAt(node, container); else if (offset == 0) return topLevelNodeBefore(node, container); else return topLevelNodeAt(node.childNodes[offset - 1], container); } }; select.focusAfterNode = function(node, container) { var range = document.createRange(); range.setStartBefore(container.firstChild || container); // In Opera, setting the end of a range at the end of a line // (before a BR) will cause the cursor to appear on the next // line, so we set the end inside of the start node when // possible. if (node && !node.firstChild) range.setEndAfter(node); else if (node) range.setEnd(node, node.childNodes.length); else range.setEndBefore(container.firstChild || container); range.collapse(false); selectRange(range); }; select.somethingSelected = function() { var range = selectionRange(); return range && !range.collapsed; }; select.offsetInNode = function(node) { var range = selectionRange(); if (!range) return 0; range = range.cloneRange(); range.setStartBefore(node); return range.toString().length; }; select.insertNodeAtCursor = function(node) { var range = selectionRange(); if (!range) return; range.deleteContents(); range.insertNode(node); webkitLastLineHack(document.body); // work around weirdness where Opera will magically insert a new // BR node when a BR node inside a span is moved around. makes // sure the BR ends up outside of spans. if (window.opera && isBR(node) && isSpan(node.parentNode)) { var next = node.nextSibling, p = node.parentNode, outer = p.parentNode; outer.insertBefore(node, p.nextSibling); var textAfter = ""; for (; next && next.nodeType == 3; next = next.nextSibling) { textAfter += next.nodeValue; removeElement(next); } outer.insertBefore(makePartSpan(textAfter, document), node.nextSibling); } range = document.createRange(); range.selectNode(node); range.collapse(false); selectRange(range); } select.insertNewlineAtCursor = function() { select.insertNodeAtCursor(document.createElement("BR")); }; select.insertTabAtCursor = function() { select.insertNodeAtCursor(document.createTextNode(fourSpaces)); }; select.cursorPos = function(container, start) { var range = selectionRange(); if (!range) return; var topNode = select.selectionTopNode(container, start); while (topNode && !isBR(topNode)) topNode = topNode.previousSibling; range = range.cloneRange(); range.collapse(start); if (topNode) range.setStartAfter(topNode); else range.setStartBefore(container); var text = range.toString(); return {node: topNode, offset: text.length}; }; select.setCursorPos = function(container, from, to) { var range = document.createRange(); function setPoint(node, offset, side) { if (offset == 0 && node && !node.nextSibling) { range["set" + side + "After"](node); return true; } if (!node) node = container.firstChild; else node = node.nextSibling; if (!node) return; if (offset == 0) { range["set" + side + "Before"](node); return true; } var backlog = [] function decompose(node) { if (node.nodeType == 3) backlog.push(node); else forEach(node.childNodes, decompose); } while (true) { while (node && !backlog.length) { decompose(node); node = node.nextSibling; } var cur = backlog.shift(); if (!cur) return false; var length = cur.nodeValue.length; if (length >= offset) { range["set" + side](cur, offset); return true; } offset -= length; } } to = to || from; if (setPoint(to.node, to.offset, "End") && setPoint(from.node, from.offset, "Start")) selectRange(range); }; } })();
JavaScript
/* A few useful utility functions. */ // Capture a method on an object. function method(obj, name) { return function() {obj[name].apply(obj, arguments);}; } // The value used to signal the end of a sequence in iterators. var StopIteration = {toString: function() {return "StopIteration"}}; // Apply a function to each element in a sequence. function forEach(iter, f) { if (iter.next) { try {while (true) f(iter.next());} catch (e) {if (e != StopIteration) throw e;} } else { for (var i = 0; i < iter.length; i++) f(iter[i]); } } // Map a function over a sequence, producing an array of results. function map(iter, f) { var accum = []; forEach(iter, function(val) {accum.push(f(val));}); return accum; } // Create a predicate function that tests a string againsts a given // regular expression. No longer used but might be used by 3rd party // parsers. function matcher(regexp){ return function(value){return regexp.test(value);}; } // Test whether a DOM node has a certain CSS class. function hasClass(element, className) { var classes = element.className; return classes && new RegExp("(^| )" + className + "($| )").test(classes); } function removeClass(element, className) { element.className = element.className.replace(new RegExp(" " + className + "\\b", "g"), ""); return element; } // Insert a DOM node after another node. function insertAfter(newNode, oldNode) { var parent = oldNode.parentNode; parent.insertBefore(newNode, oldNode.nextSibling); return newNode; } function removeElement(node) { if (node.parentNode) node.parentNode.removeChild(node); } function clearElement(node) { while (node.firstChild) node.removeChild(node.firstChild); } // Check whether a node is contained in another one. function isAncestor(node, child) { while (child = child.parentNode) { if (node == child) return true; } return false; } // The non-breaking space character. var nbsp = "\u00a0"; var matching = {"{": "}", "[": "]", "(": ")", "}": "{", "]": "[", ")": "("}; // Standardize a few unportable event properties. function normalizeEvent(event) { if (!event.stopPropagation) { event.stopPropagation = function() {this.cancelBubble = true;}; event.preventDefault = function() {this.returnValue = false;}; } if (!event.stop) { event.stop = function() { this.stopPropagation(); this.preventDefault(); }; } if (event.type == "keypress") { event.code = (event.charCode == null) ? event.keyCode : event.charCode; event.character = String.fromCharCode(event.code); } return event; } // Portably register event handlers. function addEventHandler(node, type, handler, removeFunc) { function wrapHandler(event) { handler(normalizeEvent(event || window.event)); } if (typeof node.addEventListener == "function") { node.addEventListener(type, wrapHandler, false); if (removeFunc) return function() {node.removeEventListener(type, wrapHandler, false);}; } else { node.attachEvent("on" + type, wrapHandler); if (removeFunc) return function() {node.detachEvent("on" + type, wrapHandler);}; } } function nodeText(node) { return node.textContent || node.innerText || node.nodeValue || ""; } function nodeTop(node) { var top = 0; while (node.offsetParent) { top += node.offsetTop; node = node.offsetParent; } return top; } function isBR(node) { var nn = node.nodeName; return nn == "BR" || nn == "br"; } function isSpan(node) { var nn = node.nodeName; return nn == "SPAN" || nn == "span"; }
JavaScript
var SparqlParser = Editor.Parser = (function() { function wordRegexp(words) { return new RegExp("^(?:" + words.join("|") + ")$", "i"); } var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri", "isblank", "isliteral", "union", "a"]); var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe", "ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional", "graph", "by", "asc", "desc"]); var operatorChars = /[*+\-<>=&|]/; var tokenizeSparql = (function() { function normal(source, setState) { var ch = source.next(); if (ch == "$" || ch == "?") { source.nextWhileMatches(/[\w\d]/); return "sp-var"; } else if (ch == "<" && !source.matches(/[\s\u00a0=]/)) { source.nextWhileMatches(/[^\s\u00a0>]/); if (source.equals(">")) source.next(); return "sp-uri"; } else if (ch == "\"" || ch == "'") { setState(inLiteral(ch)); return null; } else if (/[{}\(\),\.;\[\]]/.test(ch)) { return "sp-punc"; } else if (ch == "#") { while (!source.endOfLine()) source.next(); return "sp-comment"; } else if (operatorChars.test(ch)) { source.nextWhileMatches(operatorChars); return "sp-operator"; } else if (ch == ":") { source.nextWhileMatches(/[\w\d\._\-]/); return "sp-prefixed"; } else { source.nextWhileMatches(/[_\w\d]/); if (source.equals(":")) { source.next(); source.nextWhileMatches(/[\w\d_\-]/); return "sp-prefixed"; } var word = source.get(), type; if (ops.test(word)) type = "sp-operator"; else if (keywords.test(word)) type = "sp-keyword"; else type = "sp-word"; return {style: type, content: word}; } } function inLiteral(quote) { return function(source, setState) { var escaped = false; while (!source.endOfLine()) { var ch = source.next(); if (ch == quote && !escaped) { setState(normal); break; } escaped = !escaped && ch == "\\"; } return "sp-literal"; }; } return function(source, startState) { return tokenizer(source, startState || normal); }; })(); function indentSparql(context) { return function(nextChars) { var firstChar = nextChars && nextChars.charAt(0); if (/[\]\}]/.test(firstChar)) while (context && context.type == "pattern") context = context.prev; var closing = context && firstChar == matching[context.type]; if (!context) return 0; else if (context.type == "pattern") return context.col; else if (context.align) return context.col - (closing ? context.width : 0); else return context.indent + (closing ? 0 : indentUnit); } } function parseSparql(source) { var tokens = tokenizeSparql(source); var context = null, indent = 0, col = 0; function pushContext(type, width) { context = {prev: context, indent: indent, col: col, type: type, width: width}; } function popContext() { context = context.prev; } var iter = { next: function() { var token = tokens.next(), type = token.style, content = token.content, width = token.value.length; if (content == "\n") { token.indentation = indentSparql(context); indent = col = 0; if (context && context.align == null) context.align = false; } else if (type == "whitespace" && col == 0) { indent = width; } else if (type != "sp-comment" && context && context.align == null) { context.align = true; } if (content != "\n") col += width; if (/[\[\{\(]/.test(content)) { pushContext(content, width); } else if (/[\]\}\)]/.test(content)) { while (context && context.type == "pattern") popContext(); if (context && content == matching[context.type]) popContext(); } else if (content == "." && context && context.type == "pattern") { popContext(); } else if ((type == "sp-word" || type == "sp-prefixed" || type == "sp-uri" || type == "sp-var" || type == "sp-literal") && context && /[\{\[]/.test(context.type)) { pushContext("pattern", width); } return token; }, copy: function() { var _context = context, _indent = indent, _col = col, _tokenState = tokens.state; return function(source) { tokens = tokenizeSparql(source, _tokenState); context = _context; indent = _indent; col = _col; return iter; }; } }; return iter; } return {make: parseSparql, electricChars: "}]"}; })();
JavaScript
/* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed by Yahoo! Inc. under the BSD (revised) open source license @author Dan Vlad Dascalescu <dandv@yahoo-inc.com> Parse function for PHP. Makes use of the tokenizer from tokenizephp.js. Based on parsejavascript.js by Marijn Haverbeke. Features: + special "deprecated" style for PHP4 keywords like 'var' + support for PHP 5.3 keywords: 'namespace', 'use' + 911 predefined constants, 1301 predefined functions, 105 predeclared classes from a typical PHP installation in a LAMP environment + new feature: syntax error flagging, thus enabling strict parsing of: + function definitions with explicitly or implicitly typed arguments and default values + modifiers (public, static etc.) applied to method and member definitions + foreach(array_expression as $key [=> $value]) loops + differentiation between single-quoted strings and double-quoted interpolating strings */ // add the Array.indexOf method for JS engines that don't support it (e.g. IE) // code from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array/IndexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; } var PHPParser = Editor.Parser = (function() { // Token types that can be considered to be atoms, part of operator expressions var atomicTypes = { "atom": true, "number": true, "variable": true, "string": true }; // Constructor for the lexical context objects. function PHPLexical(indented, column, type, align, prev, info) { // indentation at start of this line this.indented = indented; // column at which this scope was opened this.column = column; // type of scope ('stat' (statement), 'form' (special form), '[', '{', or '(') this.type = type; // '[', '{', or '(' blocks that have any text after their opening // character are said to be 'aligned' -- any lines below are // indented all the way to the opening character. if (align != null) this.align = align; // Parent scope, if any. this.prev = prev; this.info = info; } // PHP indentation rules function indentPHP(lexical) { return function(firstChars) { var firstChar = firstChars && firstChars.charAt(0), type = lexical.type; var closing = firstChar == type; if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "stat" || type == "form") return lexical.indented + indentUnit; else if (lexical.info == "switch" && !closing) return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column - (closing ? 1 : 0); else return lexical.indented + (closing ? 0 : indentUnit); }; } // The parser-iterator-producing function itself. function parsePHP(input, basecolumn) { // Wrap the input in a token stream var tokens = tokenizePHP(input); // The parser state. cc is a stack of actions that have to be // performed to finish the current statement. For example we might // know that we still need to find a closing parenthesis and a // semicolon. Actions at the end of the stack go first. It is // initialized with an infinitely looping action that consumes // whole statements. var cc = [statements]; // The lexical scope, used mostly for indentation. var lexical = new PHPLexical((basecolumn || 0) - indentUnit, 0, "block", false); // Current column, and the indentation at the start of the current // line. Used to create lexical scope objects. var column = 0; var indented = 0; // Variables which are used by the mark, cont, and pass functions // below to communicate with the driver loop in the 'next' function. var consume, marked; // The iterator object. var parser = {next: next, copy: copy}; // parsing is accomplished by calling next() repeatedly function next(){ // Start by performing any 'lexical' actions (adjusting the // lexical variable), or the operations below will be working // with the wrong lexical state. while(cc[cc.length - 1].lex) cc.pop()(); // Fetch the next token. var token = tokens.next(); // Adjust column and indented. if (token.type == "whitespace" && column == 0) indented = token.value.length; column += token.value.length; if (token.content == "\n"){ indented = column = 0; // If the lexical scope's align property is still undefined at // the end of the line, it is an un-aligned scope. if (!("align" in lexical)) lexical.align = false; // Newline tokens get an indentation function associated with // them. token.indentation = indentPHP(lexical); } // No more processing for meaningless tokens. if (token.type == "whitespace" || token.type == "comment" || token.type == "string_not_terminated" ) return token; // When a meaningful token is found and the lexical scope's // align is undefined, it is an aligned scope. if (!("align" in lexical)) lexical.align = true; // Execute actions until one 'consumes' the token and we can // return it. 'marked' is used to change the style of the current token. while(true) { consume = marked = false; // Take and execute the topmost action. var action = cc.pop(); action(token); if (consume){ if (marked) token.style = marked; // Here we differentiate between local and global variables. return token; } } return 1; // Firebug workaround for http://code.google.com/p/fbug/issues/detail?id=1239#c1 } // This makes a copy of the parser state. It stores all the // stateful variables in a closure, and returns a function that // will restore them when called with a new input stream. Note // that the cc array has to be copied, because it is contantly // being modified. Lexical objects are not mutated, so they can // be shared between runs of the parser. function copy(){ var _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state; return function copyParser(input){ lexical = _lexical; cc = _cc.concat([]); // copies the array column = indented = 0; tokens = tokenizePHP(input, _tokenState); return parser; }; } // Helper function for pushing a number of actions onto the cc // stack in reverse order. function push(fs){ for (var i = fs.length - 1; i >= 0; i--) cc.push(fs[i]); } // cont and pass are used by the action functions to add other // actions to the stack. cont will cause the current token to be // consumed, pass will leave it for the next action. function cont(){ push(arguments); consume = true; } function pass(){ push(arguments); consume = false; } // Used to change the style of the current token. function mark(style){ marked = style; } // Add a lyer of style to the current token, for example syntax-error function mark_add(style){ marked = marked + ' ' + style; } // Push a new lexical context of the given type. function pushlex(type, info) { var result = function pushlexing() { lexical = new PHPLexical(indented, column, type, null, lexical, info) }; result.lex = true; return result; } // Pop off the current lexical context. function poplex(){ if (lexical.prev) lexical = lexical.prev; } poplex.lex = true; // The 'lex' flag on these actions is used by the 'next' function // to know they can (and have to) be ran before moving on to the // next token. // Creates an action that discards tokens until it finds one of // the given type. This will ignore (and recover from) syntax errors. function expect(wanted){ return function expecting(token){ if (token.type == wanted) cont(); // consume the token else { cont(arguments.callee); // continue expecting() - call itself } }; } // Require a specific token type, or one of the tokens passed in the 'wanted' array // Used to detect blatant syntax errors. 'execute' is used to pass extra code // to be executed if the token is matched. For example, a '(' match could // 'execute' a cont( compasep(funcarg), require(")") ) function require(wanted, execute){ return function requiring(token){ var ok; var type = token.type; if (typeof(wanted) == "string") ok = (type == wanted) -1; else ok = wanted.indexOf(type); if (ok >= 0) { if (execute && typeof(execute[ok]) == "function") pass(execute[ok]); else cont(); } else { if (!marked) mark(token.style); mark_add("syntax-error"); cont(arguments.callee); } }; } // Looks for a statement, and then calls itself. function statements(token){ return pass(statement, statements); } // Dispatches various types of statements based on the type of the current token. function statement(token){ var type = token.type; if (type == "keyword a") cont(pushlex("form"), expression, altsyntax, statement, poplex); else if (type == "keyword b") cont(pushlex("form"), altsyntax, statement, poplex); else if (type == "{") cont(pushlex("}"), block, poplex); else if (type == "function") funcdef(); // technically, "class implode {...}" is correct, but we'll flag that as an error because it overrides a predefined function else if (type == "class") classdef(); else if (type == "foreach") cont(pushlex("form"), require("("), pushlex(")"), expression, require("as"), require("variable"), /* => $value */ expect(")"), altsyntax, poplex, statement, poplex); else if (type == "for") cont(pushlex("form"), require("("), pushlex(")"), expression, require(";"), expression, require(";"), expression, require(")"), altsyntax, poplex, statement, poplex); // public final function foo(), protected static $bar; else if (type == "modifier") cont(require(["modifier", "variable", "function", "abstract"], [null, commasep(require("variable")), funcdef, absfun])); else if (type == "abstract") abs(); else if (type == "switch") cont(pushlex("form"), require("("), expression, require(")"), pushlex("}", "switch"), require([":", "{"]), block, poplex, poplex); else if (type == "case") cont(expression, require(":")); else if (type == "default") cont(require(":")); else if (type == "catch") cont(pushlex("form"), require("("), require("t_string"), require("variable"), require(")"), statement, poplex); else if (type == "const") cont(require("t_string")); // 'const static x=5' is a syntax error // technically, "namespace implode {...}" is correct, but we'll flag that as an error because it overrides a predefined function else if (type == "namespace") cont(namespacedef, require(";")); // $variables may be followed by operators, () for variable function calls, or [] subscripts else pass(pushlex("stat"), expression, require(";"), poplex); } // Dispatch expression types. function expression(token){ var type = token.type; if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator); else if (type == "<<<") cont(require("string"), maybeoperator); // heredoc/nowdoc else if (type == "t_string") cont(maybe_double_colon, maybeoperator); else if (type == "keyword c" || type == "operator") cont(expression); // lambda else if (type == "function") lambdadef(); // function call or parenthesized expression: $a = ($b + 1) * 2; else if (type == "(") cont(pushlex(")"), commasep(expression), require(")"), poplex, maybeoperator); } // Called for places where operators, function calls, or subscripts are // valid. Will skip on to the next action if none is found. function maybeoperator(token){ var type = token.type; if (type == "operator") { if (token.content == "?") cont(expression, require(":"), expression); // ternary operator else cont(expression); } else if (type == "(") cont(pushlex(")"), expression, commasep(expression), require(")"), poplex, maybeoperator /* $varfunc() + 3 */); else if (type == "[") cont(pushlex("]"), expression, require("]"), maybeoperator /* for multidimensional arrays, or $func[$i]() */, poplex); } // A regular use of the double colon to specify a class, as in self::func() or myclass::$var; // Differs from `namespace` or `use` in that only one class can be the parent; chains (A::B::$var) are a syntax error. function maybe_double_colon(token) { if (token.type == "t_double_colon") // A::$var, A::func(), A::const cont(require(["t_string", "variable"]), maybeoperator); else { // a t_string wasn't followed by ::, such as in a function call: foo() pass(expression) } } // the declaration or definition of a function function funcdef() { cont(require("t_string"), require("("), pushlex(")"), commasep(funcarg), require(")"), poplex, block); } // the declaration or definition of a lambda function lambdadef() { cont(require("("), pushlex(")"), commasep(funcarg), require(")"), maybe_lambda_use, poplex, require("{"), pushlex("}"), block, poplex); } // optional lambda 'use' statement function maybe_lambda_use(token) { if(token.type == "namespace") { cont(require('('), commasep(funcarg), require(')')); } else { pass(expression); } } // the definition of a class function classdef() { cont(require("t_string"), expect("{"), pushlex("}"), block, poplex); } // either funcdef if the current token is "function", or the keyword "function" + funcdef function absfun(token) { if(token.type == "function") funcdef(); else cont(require(["function"], [funcdef])); } // the abstract class or function (with optional modifier) function abs(token) { cont(require(["modifier", "function", "class"], [absfun, funcdef, classdef])); } // Parses a comma-separated list of the things that are recognized // by the 'what' argument. function commasep(what){ function proceed(token) { if (token.type == ",") cont(what, proceed); } return function commaSeparated() { pass(what, proceed); }; } // Look for statements until a closing brace is found. function block(token) { if (token.type == "}") cont(); else pass(statement, block); } function empty_parens_if_array(token) { if(token.content == "array") cont(require("("), require(")")); } function maybedefaultparameter(token){ if (token.content == "=") cont(require(["t_string", "string", "number", "atom"], [empty_parens_if_array, null, null])); } function var_or_reference(token) { if(token.type == "variable") cont(maybedefaultparameter); else if(token.content == "&") cont(require("variable"), maybedefaultparameter); } // support for default arguments: http://us.php.net/manual/en/functions.arguments.php#functions.arguments.default function funcarg(token){ // function foo(myclass $obj) {...} or function foo(myclass &objref) {...} if (token.type == "t_string") cont(var_or_reference); // function foo($var) {...} or function foo(&$ref) {...} else var_or_reference(token); } // A namespace definition or use function maybe_double_colon_def(token) { if (token.type == "t_double_colon") cont(namespacedef); } function namespacedef(token) { pass(require("t_string"), maybe_double_colon_def); } function altsyntax(token){ if(token.content==':') cont(altsyntaxBlock,poplex); } function altsyntaxBlock(token){ if (token.type == "altsyntaxend") cont(require(';')); else pass(statement, altsyntaxBlock); } return parser; } return {make: parsePHP, electricChars: "{}:"}; })();
JavaScript
/* This file defines an XML parser, with a few kludges to make it * useable for HTML. autoSelfClosers defines a set of tag names that * are expected to not have a closing tag, and doNotIndent specifies * the tags inside of which no indentation should happen (see Config * object). These can be disabled by passing the editor an object like * {useHTMLKludges: false} as parserConfig option. */ var XMLParser = Editor.Parser = (function() { var Kludges = { autoSelfClosers: {"br": true, "img": true, "hr": true, "link": true, "input": true, "meta": true, "col": true, "frame": true, "base": true, "area": true}, doNotIndent: {"pre": true, "!cdata": true} }; var NoKludges = {autoSelfClosers: {}, doNotIndent: {"!cdata": true}}; var UseKludges = Kludges; var alignCDATA = false; // Simple stateful tokenizer for XML documents. Returns a // MochiKit-style iterator, with a state property that contains a // function encapsulating the current state. See tokenize.js. var tokenizeXML = (function() { function inText(source, setState) { var ch = source.next(); if (ch == "<") { if (source.equals("!")) { source.next(); if (source.equals("[")) { if (source.lookAhead("[CDATA[", true)) { setState(inBlock("xml-cdata", "]]>")); return null; } else { return "xml-text"; } } else if (source.lookAhead("--", true)) { setState(inBlock("xml-comment", "-->")); return null; } else if (source.lookAhead("DOCTYPE", true)) { source.nextWhileMatches(/[\w\._\-]/); setState(inBlock("xml-doctype", ">")); return "xml-doctype"; } else { return "xml-text"; } } else if (source.equals("?")) { source.next(); source.nextWhileMatches(/[\w\._\-]/); setState(inBlock("xml-processing", "?>")); return "xml-processing"; } else { if (source.equals("/")) source.next(); setState(inTag); return "xml-punctuation"; } } else if (ch == "&") { while (!source.endOfLine()) { if (source.next() == ";") break; } return "xml-entity"; } else { source.nextWhileMatches(/[^&<\n]/); return "xml-text"; } } function inTag(source, setState) { var ch = source.next(); if (ch == ">") { setState(inText); return "xml-punctuation"; } else if (/[?\/]/.test(ch) && source.equals(">")) { source.next(); setState(inText); return "xml-punctuation"; } else if (ch == "=") { return "xml-punctuation"; } else if (/[\'\"]/.test(ch)) { setState(inAttribute(ch)); return null; } else { source.nextWhileMatches(/[^\s\u00a0=<>\"\'\/?]/); return "xml-name"; } } function inAttribute(quote) { return function(source, setState) { while (!source.endOfLine()) { if (source.next() == quote) { setState(inTag); break; } } return "xml-attribute"; }; } function inBlock(style, terminator) { return function(source, setState) { while (!source.endOfLine()) { if (source.lookAhead(terminator, true)) { setState(inText); break; } source.next(); } return style; }; } return function(source, startState) { return tokenizer(source, startState || inText); }; })(); // The parser. The structure of this function largely follows that of // parseJavaScript in parsejavascript.js (there is actually a bit more // shared code than I'd like), but it is quite a bit simpler. function parseXML(source) { var tokens = tokenizeXML(source), token; var cc = [base]; var tokenNr = 0, indented = 0; var currentTag = null, context = null; var consume; function push(fs) { for (var i = fs.length - 1; i >= 0; i--) cc.push(fs[i]); } function cont() { push(arguments); consume = true; } function pass() { push(arguments); consume = false; } function markErr() { token.style += " xml-error"; } function expect(text) { return function(style, content) { if (content == text) cont(); else {markErr(); cont(arguments.callee);} }; } function pushContext(tagname, startOfLine) { var noIndent = UseKludges.doNotIndent.hasOwnProperty(tagname) || (context && context.noIndent); context = {prev: context, name: tagname, indent: indented, startOfLine: startOfLine, noIndent: noIndent}; } function popContext() { context = context.prev; } function computeIndentation(baseContext) { return function(nextChars, current) { var context = baseContext; if (context && context.noIndent) return current; if (alignCDATA && /<!\[CDATA\[/.test(nextChars)) return 0; if (context && /^<\//.test(nextChars)) context = context.prev; while (context && !context.startOfLine) context = context.prev; if (context) return context.indent + indentUnit; else return 0; }; } function base() { return pass(element, base); } var harmlessTokens = {"xml-text": true, "xml-entity": true, "xml-comment": true, "xml-processing": true, "xml-doctype": true}; function element(style, content) { if (content == "<") cont(tagname, attributes, endtag(tokenNr == 1)); else if (content == "</") cont(closetagname, expect(">")); else if (style == "xml-cdata") { if (!context || context.name != "!cdata") pushContext("!cdata"); if (/\]\]>$/.test(content)) popContext(); cont(); } else if (harmlessTokens.hasOwnProperty(style)) cont(); else {markErr(); cont();} } function tagname(style, content) { if (style == "xml-name") { currentTag = content.toLowerCase(); token.style = "xml-tagname"; cont(); } else { currentTag = null; pass(); } } function closetagname(style, content) { if (style == "xml-name") { token.style = "xml-tagname"; if (context && content.toLowerCase() == context.name) popContext(); else markErr(); } cont(); } function endtag(startOfLine) { return function(style, content) { if (content == "/>" || (content == ">" && UseKludges.autoSelfClosers.hasOwnProperty(currentTag))) cont(); else if (content == ">") {pushContext(currentTag, startOfLine); cont();} else {markErr(); cont(arguments.callee);} }; } function attributes(style) { if (style == "xml-name") {token.style = "xml-attname"; cont(attribute, attributes);} else pass(); } function attribute(style, content) { if (content == "=") cont(value); else if (content == ">" || content == "/>") pass(endtag); else pass(); } function value(style) { if (style == "xml-attribute") cont(value); else pass(); } return { indentation: function() {return indented;}, next: function(){ token = tokens.next(); if (token.style == "whitespace" && tokenNr == 0) indented = token.value.length; else tokenNr++; if (token.content == "\n") { indented = tokenNr = 0; token.indentation = computeIndentation(context); } if (token.style == "whitespace" || token.type == "xml-comment") return token; while(true){ consume = false; cc.pop()(token.style, token.content); if (consume) return token; } }, copy: function(){ var _cc = cc.concat([]), _tokenState = tokens.state, _context = context; var parser = this; return function(input){ cc = _cc.concat([]); tokenNr = indented = 0; context = _context; tokens = tokenizeXML(input, _tokenState); return parser; }; } }; } return { make: parseXML, electricChars: "/", configure: function(config) { if (config.useHTMLKludges != null) UseKludges = config.useHTMLKludges ? Kludges : NoKludges; if (config.alignCDATA) alignCDATA = config.alignCDATA; } }; })();
JavaScript
/* Tokenizer for JavaScript code */ var tokenizeJavaScript = (function() { // Advance the stream until the given character (not preceded by a // backslash) is encountered, or the end of the line is reached. function nextUntilUnescaped(source, end) { var escaped = false; while (!source.endOfLine()) { var next = source.next(); if (next == end && !escaped) return false; escaped = !escaped && next == "\\"; } return escaped; } // A map of JavaScript's keywords. The a/b/c keyword distinction is // very rough, but it gives the parser enough information to parse // correct code correctly (we don't care that much how we parse // incorrect code). The style information included in these objects // is used by the highlighter to pick the correct CSS style for a // token. var keywords = function(){ function result(type, style){ return {type: type, style: "js-" + style}; } // keywords that take a parenthised expression, and then a // statement (if) var keywordA = result("keyword a", "keyword"); // keywords that take just a statement (else) var keywordB = result("keyword b", "keyword"); // keywords that optionally take an expression, and form a // statement (return) var keywordC = result("keyword c", "keyword"); var operator = result("operator", "keyword"); var atom = result("atom", "atom"); return { "if": keywordA, "while": keywordA, "with": keywordA, "else": keywordB, "do": keywordB, "try": keywordB, "finally": keywordB, "return": keywordC, "break": keywordC, "continue": keywordC, "new": keywordC, "delete": keywordC, "throw": keywordC, "in": operator, "typeof": operator, "instanceof": operator, "var": result("var", "keyword"), "function": result("function", "keyword"), "catch": result("catch", "keyword"), "for": result("for", "keyword"), "switch": result("switch", "keyword"), "case": result("case", "keyword"), "default": result("default", "keyword"), "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom }; }(); // Some helper regexps var isOperatorChar = /[+\-*&%=<>!?|]/; var isHexDigit = /[0-9A-Fa-f]/; var isWordChar = /[\w\$_]/; // Wrapper around jsToken that helps maintain parser state (whether // we are inside of a multi-line comment and whether the next token // could be a regular expression). function jsTokenState(inside, regexp) { return function(source, setState) { var newInside = inside; var type = jsToken(inside, regexp, source, function(c) {newInside = c;}); var newRegexp = type.type == "operator" || type.type == "keyword c" || type.type.match(/^[\[{}\(,;:]$/); if (newRegexp != regexp || newInside != inside) setState(jsTokenState(newInside, newRegexp)); return type; }; } // The token reader, intended to be used by the tokenizer from // tokenize.js (through jsTokenState). Advances the source stream // over a token, and returns an object containing the type and style // of that token. function jsToken(inside, regexp, source, setInside) { function readHexNumber(){ source.next(); // skip the 'x' source.nextWhileMatches(isHexDigit); return {type: "number", style: "js-atom"}; } function readNumber() { source.nextWhileMatches(/[0-9]/); if (source.equals(".")){ source.next(); source.nextWhileMatches(/[0-9]/); } if (source.equals("e") || source.equals("E")){ source.next(); if (source.equals("-")) source.next(); source.nextWhileMatches(/[0-9]/); } return {type: "number", style: "js-atom"}; } // Read a word, look it up in keywords. If not found, it is a // variable, otherwise it is a keyword of the type found. function readWord() { source.nextWhileMatches(isWordChar); var word = source.get(); var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word]; return known ? {type: known.type, style: known.style, content: word} : {type: "variable", style: "js-variable", content: word}; } function readRegexp() { nextUntilUnescaped(source, "/"); source.nextWhileMatches(/[gimy]/); // 'y' is "sticky" option in Mozilla return {type: "regexp", style: "js-string"}; } // Mutli-line comments are tricky. We want to return the newlines // embedded in them as regular newline tokens, and then continue // returning a comment token for every line of the comment. So // some state has to be saved (inside) to indicate whether we are // inside a /* */ sequence. function readMultilineComment(start){ var newInside = "/*"; var maybeEnd = (start == "*"); while (true) { if (source.endOfLine()) break; var next = source.next(); if (next == "/" && maybeEnd){ newInside = null; break; } maybeEnd = (next == "*"); } setInside(newInside); return {type: "comment", style: "js-comment"}; } function readOperator() { source.nextWhileMatches(isOperatorChar); return {type: "operator", style: "js-operator"}; } function readString(quote) { var endBackSlash = nextUntilUnescaped(source, quote); setInside(endBackSlash ? quote : null); return {type: "string", style: "js-string"}; } // Fetch the next token. Dispatches on first character in the // stream, or first two characters when the first is a slash. if (inside == "\"" || inside == "'") return readString(inside); var ch = source.next(); if (inside == "/*") return readMultilineComment(ch); else if (ch == "\"" || ch == "'") return readString(ch); // with punctuation, the type of the token is the symbol itself else if (/[\[\]{}\(\),;\:\.]/.test(ch)) return {type: ch, style: "js-punctuation"}; else if (ch == "0" && (source.equals("x") || source.equals("X"))) return readHexNumber(); else if (/[0-9]/.test(ch)) return readNumber(); else if (ch == "/"){ if (source.equals("*")) { source.next(); return readMultilineComment(ch); } else if (source.equals("/")) { nextUntilUnescaped(source, null); return {type: "comment", style: "js-comment"};} else if (regexp) return readRegexp(); else return readOperator(); } else if (isOperatorChar.test(ch)) return readOperator(); else return readWord(); } // The external interface to the tokenizer. return function(source, startState) { return tokenizer(source, startState || jsTokenState(false, true)); }; })();
JavaScript
// A framework for simple tokenizers. Takes care of newlines and // white-space, and of getting the text from the source stream into // the token object. A state is a function of two arguments -- a // string stream and a setState function. The second can be used to // change the tokenizer's state, and can be ignored for stateless // tokenizers. This function should advance the stream over a token // and return a string or object containing information about the next // token, or null to pass and have the (new) state be called to finish // the token. When a string is given, it is wrapped in a {style, type} // object. In the resulting object, the characters consumed are stored // under the content property. Any whitespace following them is also // automatically consumed, and added to the value property. (Thus, // content is the actual meaningful part of the token, while value // contains all the text it spans.) function tokenizer(source, state) { // Newlines are always a separate token. function isWhiteSpace(ch) { // The messy regexp is because IE's regexp matcher is of the // opinion that non-breaking spaces are no whitespace. return ch != "\n" && /^[\s\u00a0]*$/.test(ch); } var tokenizer = { state: state, take: function(type) { if (typeof(type) == "string") type = {style: type, type: type}; type.content = (type.content || "") + source.get(); if (!/\n$/.test(type.content)) source.nextWhile(isWhiteSpace); type.value = type.content + source.get(); return type; }, next: function () { if (!source.more()) throw StopIteration; var type; if (source.equals("\n")) { source.next(); return this.take("whitespace"); } if (source.applies(isWhiteSpace)) type = "whitespace"; else while (!type) type = this.state(source, function(s) {tokenizer.state = s;}); return this.take(type); } }; return tokenizer; }
JavaScript
/* The Editor object manages the content of the editable frame. It * catches events, colours nodes, and indents lines. This file also * holds some functions for transforming arbitrary DOM structures into * plain sequences of <span> and <br> elements */ var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent); var webkit = /AppleWebKit/.test(navigator.userAgent); var safari = /Apple Computer, Inc/.test(navigator.vendor); var gecko = navigator.userAgent.match(/gecko\/(\d{8})/i); if (gecko) gecko = Number(gecko[1]); var mac = /Mac/.test(navigator.platform); // TODO this is related to the backspace-at-end-of-line bug. Remove // this if Opera gets their act together, make the version check more // broad if they don't. var brokenOpera = window.opera && /Version\/10.[56]/.test(navigator.userAgent); // TODO remove this once WebKit 533 becomes less common. var slowWebkit = /AppleWebKit\/533/.test(navigator.userAgent); // Make sure a string does not contain two consecutive 'collapseable' // whitespace characters. function makeWhiteSpace(n) { var buffer = [], nb = true; for (; n > 0; n--) { buffer.push((nb || n == 1) ? nbsp : " "); nb ^= true; } return buffer.join(""); } // Create a set of white-space characters that will not be collapsed // by the browser, but will not break text-wrapping either. function fixSpaces(string) { if (string.charAt(0) == " ") string = nbsp + string.slice(1); return string.replace(/\t/g, function() {return makeWhiteSpace(indentUnit);}) .replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);}); } function cleanText(text) { return text.replace(/\u00a0/g, " ").replace(/\u200b/g, ""); } // Create a SPAN node with the expected properties for document part // spans. function makePartSpan(value) { var text = value; if (value.nodeType == 3) text = value.nodeValue; else value = document.createTextNode(text); var span = document.createElement("span"); span.isPart = true; span.appendChild(value); span.currentText = text; return span; } function alwaysZero() {return 0;} // On webkit, when the last BR of the document does not have text // behind it, the cursor can not be put on the line after it. This // makes pressing enter at the end of the document occasionally do // nothing (or at least seem to do nothing). To work around it, this // function makes sure the document ends with a span containing a // zero-width space character. The traverseDOM iterator filters such // character out again, so that the parsers won't see them. This // function is called from a few strategic places to make sure the // zwsp is restored after the highlighting process eats it. var webkitLastLineHack = webkit ? function(container) { var last = container.lastChild; if (!last || !last.hackBR) { var br = document.createElement("br"); br.hackBR = true; container.appendChild(br); } } : function() {}; function asEditorLines(string) { var tab = makeWhiteSpace(indentUnit); return map(string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").split("\n"), fixSpaces); } var Editor = (function(){ // The HTML elements whose content should be suffixed by a newline // when converting them to flat text. var newlineElements = {"P": true, "DIV": true, "LI": true}; // Helper function for traverseDOM. Flattens an arbitrary DOM node // into an array of textnodes and <br> tags. function simplifyDOM(root, atEnd) { var result = []; var leaving = true; function simplifyNode(node, top) { if (node.nodeType == 3) { var text = node.nodeValue = fixSpaces(node.nodeValue.replace(/[\r\u200b]/g, "").replace(/\n/g, " ")); if (text.length) leaving = false; result.push(node); } else if (isBR(node) && node.childNodes.length == 0) { leaving = true; result.push(node); } else { for (var n = node.firstChild; n; n = n.nextSibling) simplifyNode(n); if (!leaving && newlineElements.hasOwnProperty(node.nodeName.toUpperCase())) { leaving = true; if (!atEnd || !top) result.push(document.createElement("br")); } } } simplifyNode(root, true); return result; } // Creates a MochiKit-style iterator that goes over a series of DOM // nodes. The values it yields are strings, the textual content of // the nodes. It makes sure that all nodes up to and including the // one whose text is being yielded have been 'normalized' to be just // <span> and <br> elements. function traverseDOM(start){ var nodeQueue = []; // Create a function that can be used to insert nodes after the // one given as argument. function pointAt(node){ var parent = node.parentNode; var next = node.nextSibling; return function(newnode) { parent.insertBefore(newnode, next); }; } var point = null; // This an Opera-specific hack -- always insert an empty span // between two BRs, because Opera's cursor code gets terribly // confused when the cursor is between two BRs. var afterBR = true; // Insert a normalized node at the current point. If it is a text // node, wrap it in a <span>, and give that span a currentText // property -- this is used to cache the nodeValue, because // directly accessing nodeValue is horribly slow on some browsers. // The dirty property is used by the highlighter to determine // which parts of the document have to be re-highlighted. function insertPart(part){ var text = "\n"; if (part.nodeType == 3) { select.snapshotChanged(); part = makePartSpan(part); text = part.currentText; afterBR = false; } else { if (afterBR && window.opera) point(makePartSpan("")); afterBR = true; } part.dirty = true; nodeQueue.push(part); point(part); return text; } // Extract the text and newlines from a DOM node, insert them into // the document, and return the textual content. Used to replace // non-normalized nodes. function writeNode(node, end) { var simplified = simplifyDOM(node, end); for (var i = 0; i < simplified.length; i++) simplified[i] = insertPart(simplified[i]); return simplified.join(""); } // Check whether a node is a normalized <span> element. function partNode(node){ if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { var text = node.firstChild.nodeValue; node.dirty = node.dirty || text != node.currentText; node.currentText = text; return !/[\n\t\r]/.test(node.currentText); } return false; } // Advance to next node, return string for current node. function next() { if (!start) throw StopIteration; var node = start; start = node.nextSibling; if (partNode(node)){ nodeQueue.push(node); afterBR = false; return node.currentText; } else if (isBR(node)) { if (afterBR && window.opera) node.parentNode.insertBefore(makePartSpan(""), node); nodeQueue.push(node); afterBR = true; return "\n"; } else { var end = !node.nextSibling; point = pointAt(node); removeElement(node); return writeNode(node, end); } } // MochiKit iterators are objects with a next function that // returns the next value or throws StopIteration when there are // no more values. return {next: next, nodes: nodeQueue}; } // Determine the text size of a processed node. function nodeSize(node) { return isBR(node) ? 1 : node.currentText.length; } // Search backwards through the top-level nodes until the next BR or // the start of the frame. function startOfLine(node) { while (node && !isBR(node)) node = node.previousSibling; return node; } function endOfLine(node, container) { if (!node) node = container.firstChild; else if (isBR(node)) node = node.nextSibling; while (node && !isBR(node)) node = node.nextSibling; return node; } function time() {return new Date().getTime();} // Client interface for searching the content of the editor. Create // these by calling CodeMirror.getSearchCursor. To use, call // findNext on the resulting object -- this returns a boolean // indicating whether anything was found, and can be called again to // skip to the next find. Use the select and replace methods to // actually do something with the found locations. function SearchCursor(editor, pattern, from, caseFold) { this.editor = editor; this.history = editor.history; this.history.commit(); this.valid = !!pattern; this.atOccurrence = false; if (caseFold == undefined) caseFold = typeof pattern == "string" && pattern == pattern.toLowerCase(); function getText(node){ var line = cleanText(editor.history.textAfter(node)); return (caseFold ? line.toLowerCase() : line); } var topPos = {node: null, offset: 0}, self = this; if (from && typeof from == "object" && typeof from.character == "number") { editor.checkLine(from.line); var pos = {node: from.line, offset: from.character}; this.pos = {from: pos, to: pos}; } else if (from) { this.pos = {from: select.cursorPos(editor.container, true) || topPos, to: select.cursorPos(editor.container, false) || topPos}; } else { this.pos = {from: topPos, to: topPos}; } if (typeof pattern != "string") { // Regexp match this.matches = function(reverse, node, offset) { if (reverse) { var line = getText(node).slice(0, offset), match = line.match(pattern), start = 0; while (match) { var ind = line.indexOf(match[0]); start += ind; line = line.slice(ind + 1); var newmatch = line.match(pattern); if (newmatch) match = newmatch; else break; } } else { var line = getText(node).slice(offset), match = line.match(pattern), start = match && offset + line.indexOf(match[0]); } if (match) { self.currentMatch = match; return {from: {node: node, offset: start}, to: {node: node, offset: start + match[0].length}}; } }; return; } if (caseFold) pattern = pattern.toLowerCase(); // Create a matcher function based on the kind of string we have. var target = pattern.split("\n"); this.matches = (target.length == 1) ? // For one-line strings, searching can be done simply by calling // indexOf or lastIndexOf on the current line. function(reverse, node, offset) { var line = getText(node), len = pattern.length, match; if (reverse ? (offset >= len && (match = line.lastIndexOf(pattern, offset - len)) != -1) : (match = line.indexOf(pattern, offset)) != -1) return {from: {node: node, offset: match}, to: {node: node, offset: match + len}}; } : // Multi-line strings require internal iteration over lines, and // some clunky checks to make sure the first match ends at the // end of the line and the last match starts at the start. function(reverse, node, offset) { var idx = (reverse ? target.length - 1 : 0), match = target[idx], line = getText(node); var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match)); if (reverse ? offsetA >= offset || offsetA != match.length : offsetA <= offset || offsetA != line.length - match.length) return; var pos = node; while (true) { if (reverse && !pos) return; pos = (reverse ? this.history.nodeBefore(pos) : this.history.nodeAfter(pos) ); if (!reverse && !pos) return; line = getText(pos); match = target[reverse ? --idx : ++idx]; if (idx > 0 && idx < target.length - 1) { if (line != match) return; else continue; } var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length); if (reverse ? offsetB != line.length - match.length : offsetB != match.length) return; return {from: {node: reverse ? pos : node, offset: reverse ? offsetB : offsetA}, to: {node: reverse ? node : pos, offset: reverse ? offsetA : offsetB}}; } }; } SearchCursor.prototype = { findNext: function() {return this.find(false);}, findPrevious: function() {return this.find(true);}, find: function(reverse) { if (!this.valid) return false; var self = this, pos = reverse ? this.pos.from : this.pos.to, node = pos.node, offset = pos.offset; // Reset the cursor if the current line is no longer in the DOM tree. if (node && !node.parentNode) { node = null; offset = 0; } function savePosAndFail() { var pos = {node: node, offset: offset}; self.pos = {from: pos, to: pos}; self.atOccurrence = false; return false; } while (true) { if (this.pos = this.matches(reverse, node, offset)) { this.atOccurrence = true; return true; } if (reverse) { if (!node) return savePosAndFail(); node = this.history.nodeBefore(node); offset = this.history.textAfter(node).length; } else { var next = this.history.nodeAfter(node); if (!next) { offset = this.history.textAfter(node).length; return savePosAndFail(); } node = next; offset = 0; } } }, select: function() { if (this.atOccurrence) { select.setCursorPos(this.editor.container, this.pos.from, this.pos.to); select.scrollToCursor(this.editor.container); } }, replace: function(string) { if (this.atOccurrence) { var fragments = this.currentMatch; if (fragments) string = string.replace(/\\(\d)/, function(m, i){return fragments[i];}); var end = this.editor.replaceRange(this.pos.from, this.pos.to, string); this.pos.to = end; this.atOccurrence = false; } }, position: function() { if (this.atOccurrence) return {line: this.pos.from.node, character: this.pos.from.offset}; } }; // The Editor object is the main inside-the-iframe interface. function Editor(options) { this.options = options; window.indentUnit = options.indentUnit; var container = this.container = document.body; this.history = new UndoHistory(container, options.undoDepth, options.undoDelay, this); var self = this; if (!Editor.Parser) throw "No parser loaded."; if (options.parserConfig && Editor.Parser.configure) Editor.Parser.configure(options.parserConfig); if (!options.readOnly && !internetExplorer) select.setCursorPos(container, {node: null, offset: 0}); this.dirty = []; this.importCode(options.content || ""); this.history.onChange = options.onChange; if (!options.readOnly) { if (options.continuousScanning !== false) { this.scanner = this.documentScanner(options.passTime); this.delayScanning(); } function setEditable() { // Use contentEditable instead of designMode on IE, since designMode frames // can not run any scripts. It would be nice if we could use contentEditable // everywhere, but it is significantly flakier than designMode on every // single non-IE browser. if (document.body.contentEditable != undefined && internetExplorer) document.body.contentEditable = "true"; else document.designMode = "on"; // Work around issue where you have to click on the actual // body of the document to focus it in IE, making focusing // hard when the document is small. if (internetExplorer && options.height != "dynamic") document.body.style.minHeight = ( window.frameElement.clientHeight - 2 * document.body.offsetTop - 5) + "px"; document.documentElement.style.borderWidth = "0"; if (!options.textWrapping) container.style.whiteSpace = "nowrap"; } // If setting the frame editable fails, try again when the user // focus it (happens when the frame is not visible on // initialisation, in Firefox). try { setEditable(); } catch(e) { var focusEvent = addEventHandler(document, "focus", function() { focusEvent(); setEditable(); }, true); } addEventHandler(document, "keydown", method(this, "keyDown")); addEventHandler(document, "keypress", method(this, "keyPress")); addEventHandler(document, "keyup", method(this, "keyUp")); function cursorActivity() {self.cursorActivity(false);} addEventHandler(internetExplorer ? document.body : window, "mouseup", cursorActivity); addEventHandler(document.body, "cut", cursorActivity); // workaround for a gecko bug [?] where going forward and then // back again breaks designmode (no more cursor) if (gecko) addEventHandler(window, "pagehide", function(){self.unloaded = true;}); addEventHandler(document.body, "paste", function(event) { cursorActivity(); var text = null; try { var clipboardData = event.clipboardData || window.clipboardData; if (clipboardData) text = clipboardData.getData('Text'); } catch(e) {} if (text !== null) { event.stop(); self.replaceSelection(text); select.scrollToCursor(self.container); } }); if (this.options.autoMatchParens) addEventHandler(document.body, "click", method(this, "scheduleParenHighlight")); } else if (!options.textWrapping) { container.style.whiteSpace = "nowrap"; } } function isSafeKey(code) { return (code >= 16 && code <= 18) || // shift, control, alt (code >= 33 && code <= 40); // arrows, home, end } Editor.prototype = { // Import a piece of code into the editor. importCode: function(code) { var lines = asEditorLines(code), chunk = 1000; if (!this.options.incrementalLoading || lines.length < chunk) { this.history.push(null, null, lines); this.history.reset(); } else { var cur = 0, self = this; function addChunk() { var chunklines = lines.slice(cur, cur + chunk); chunklines.push(""); self.history.push(self.history.nodeBefore(null), null, chunklines); self.history.reset(); cur += chunk; if (cur < lines.length) parent.setTimeout(addChunk, 1000); } addChunk(); } }, // Extract the code from the editor. getCode: function() { if (!this.container.firstChild) return ""; var accum = []; select.markSelection(); forEach(traverseDOM(this.container.firstChild), method(accum, "push")); select.selectMarked(); // On webkit, don't count last (empty) line if the webkitLastLineHack BR is present if (webkit && this.container.lastChild.hackBR) accum.pop(); webkitLastLineHack(this.container); return cleanText(accum.join("")); }, checkLine: function(node) { if (node === false || !(node == null || node.parentNode == this.container || node.hackBR)) throw parent.CodeMirror.InvalidLineHandle; }, cursorPosition: function(start) { if (start == null) start = true; var pos = select.cursorPos(this.container, start); if (pos) return {line: pos.node, character: pos.offset}; else return {line: null, character: 0}; }, firstLine: function() { return null; }, lastLine: function() { var last = this.container.lastChild; if (last) last = startOfLine(last); if (last && last.hackBR) last = startOfLine(last.previousSibling); return last; }, nextLine: function(line) { this.checkLine(line); var end = endOfLine(line, this.container); if (!end || end.hackBR) return false; else return end; }, prevLine: function(line) { this.checkLine(line); if (line == null) return false; return startOfLine(line.previousSibling); }, visibleLineCount: function() { var line = this.container.firstChild; while (line && isBR(line)) line = line.nextSibling; // BR heights are unreliable if (!line) return false; var innerHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight); return Math.floor(innerHeight / line.offsetHeight); }, selectLines: function(startLine, startOffset, endLine, endOffset) { this.checkLine(startLine); var start = {node: startLine, offset: startOffset}, end = null; if (endOffset !== undefined) { this.checkLine(endLine); end = {node: endLine, offset: endOffset}; } select.setCursorPos(this.container, start, end); select.scrollToCursor(this.container); }, lineContent: function(line) { var accum = []; for (line = line ? line.nextSibling : this.container.firstChild; line && !isBR(line); line = line.nextSibling) accum.push(nodeText(line)); return cleanText(accum.join("")); }, setLineContent: function(line, content) { this.history.commit(); this.replaceRange({node: line, offset: 0}, {node: line, offset: this.history.textAfter(line).length}, content); this.addDirtyNode(line); this.scheduleHighlight(); }, removeLine: function(line) { var node = line ? line.nextSibling : this.container.firstChild; while (node) { var next = node.nextSibling; removeElement(node); if (isBR(node)) break; node = next; } this.addDirtyNode(line); this.scheduleHighlight(); }, insertIntoLine: function(line, position, content) { var before = null; if (position == "end") { before = endOfLine(line, this.container); } else { for (var cur = line ? line.nextSibling : this.container.firstChild; cur; cur = cur.nextSibling) { if (position == 0) { before = cur; break; } var text = nodeText(cur); if (text.length > position) { before = cur.nextSibling; content = text.slice(0, position) + content + text.slice(position); removeElement(cur); break; } position -= text.length; } } var lines = asEditorLines(content); for (var i = 0; i < lines.length; i++) { if (i > 0) this.container.insertBefore(document.createElement("BR"), before); this.container.insertBefore(makePartSpan(lines[i]), before); } this.addDirtyNode(line); this.scheduleHighlight(); }, // Retrieve the selected text. selectedText: function() { var h = this.history; h.commit(); var start = select.cursorPos(this.container, true), end = select.cursorPos(this.container, false); if (!start || !end) return ""; if (start.node == end.node) return h.textAfter(start.node).slice(start.offset, end.offset); var text = [h.textAfter(start.node).slice(start.offset)]; for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos)) text.push(h.textAfter(pos)); text.push(h.textAfter(end.node).slice(0, end.offset)); return cleanText(text.join("\n")); }, // Replace the selection with another piece of text. replaceSelection: function(text) { this.history.commit(); var start = select.cursorPos(this.container, true), end = select.cursorPos(this.container, false); if (!start || !end) return; end = this.replaceRange(start, end, text); select.setCursorPos(this.container, end); webkitLastLineHack(this.container); }, cursorCoords: function(start, internal) { var sel = select.cursorPos(this.container, start); if (!sel) return null; var off = sel.offset, node = sel.node, self = this; function measureFromNode(node, xOffset) { var y = -(document.body.scrollTop || document.documentElement.scrollTop || 0), x = -(document.body.scrollLeft || document.documentElement.scrollLeft || 0) + xOffset; forEach([node, internal ? null : window.frameElement], function(n) { while (n) {x += n.offsetLeft; y += n.offsetTop;n = n.offsetParent;} }); return {x: x, y: y, yBot: y + node.offsetHeight}; } function withTempNode(text, f) { var node = document.createElement("SPAN"); node.appendChild(document.createTextNode(text)); try {return f(node);} finally {if (node.parentNode) node.parentNode.removeChild(node);} } while (off) { node = node ? node.nextSibling : this.container.firstChild; var txt = nodeText(node); if (off < txt.length) return withTempNode(txt.substr(0, off), function(tmp) { tmp.style.position = "absolute"; tmp.style.visibility = "hidden"; tmp.className = node.className; self.container.appendChild(tmp); return measureFromNode(node, tmp.offsetWidth); }); off -= txt.length; } if (node && isSpan(node)) return measureFromNode(node, node.offsetWidth); else if (node && node.nextSibling && isSpan(node.nextSibling)) return measureFromNode(node.nextSibling, 0); else return withTempNode("\u200b", function(tmp) { if (node) node.parentNode.insertBefore(tmp, node.nextSibling); else self.container.insertBefore(tmp, self.container.firstChild); return measureFromNode(tmp, 0); }); }, reroutePasteEvent: function() { if (this.capturingPaste || window.opera || (gecko && gecko >= 20101026)) return; this.capturingPaste = true; var te = window.frameElement.CodeMirror.textareaHack; var coords = this.cursorCoords(true, true); te.style.top = coords.y + "px"; if (internetExplorer) { var snapshot = select.getBookmark(this.container); if (snapshot) this.selectionSnapshot = snapshot; } parent.focus(); te.value = ""; te.focus(); var self = this; parent.setTimeout(function() { self.capturingPaste = false; window.focus(); if (self.selectionSnapshot) // IE hack window.select.setBookmark(self.container, self.selectionSnapshot); var text = te.value; if (text) { self.replaceSelection(text); select.scrollToCursor(self.container); } }, 10); }, replaceRange: function(from, to, text) { var lines = asEditorLines(text); lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0]; var lastLine = lines[lines.length - 1]; lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset); var end = this.history.nodeAfter(to.node); this.history.push(from.node, end, lines); return {node: this.history.nodeBefore(end), offset: lastLine.length}; }, getSearchCursor: function(string, fromCursor, caseFold) { return new SearchCursor(this, string, fromCursor, caseFold); }, // Re-indent the whole buffer reindent: function() { if (this.container.firstChild) this.indentRegion(null, this.container.lastChild); }, reindentSelection: function(direction) { if (!select.somethingSelected()) { this.indentAtCursor(direction); } else { var start = select.selectionTopNode(this.container, true), end = select.selectionTopNode(this.container, false); if (start === false || end === false) return; this.indentRegion(start, end, direction, true); } }, grabKeys: function(eventHandler, filter) { this.frozen = eventHandler; this.keyFilter = filter; }, ungrabKeys: function() { this.frozen = "leave"; }, setParser: function(name, parserConfig) { Editor.Parser = window[name]; parserConfig = parserConfig || this.options.parserConfig; if (parserConfig && Editor.Parser.configure) Editor.Parser.configure(parserConfig); if (this.container.firstChild) { forEach(this.container.childNodes, function(n) { if (n.nodeType != 3) n.dirty = true; }); this.addDirtyNode(this.firstChild); this.scheduleHighlight(); } }, // Intercept enter and tab, and assign their new functions. keyDown: function(event) { if (this.frozen == "leave") {this.frozen = null; this.keyFilter = null;} if (this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode, event))) { event.stop(); this.frozen(event); return; } var code = event.keyCode; // Don't scan when the user is typing. this.delayScanning(); // Schedule a paren-highlight event, if configured. if (this.options.autoMatchParens) this.scheduleParenHighlight(); // The various checks for !altKey are there because AltGr sets both // ctrlKey and altKey to true, and should not be recognised as // Control. if (code == 13) { // enter if (event.ctrlKey && !event.altKey) { this.reparseBuffer(); } else { select.insertNewlineAtCursor(); var mode = this.options.enterMode; if (mode != "flat") this.indentAtCursor(mode == "keep" ? "keep" : undefined); select.scrollToCursor(this.container); } event.stop(); } else if (code == 9 && this.options.tabMode != "default" && !event.ctrlKey) { // tab this.handleTab(!event.shiftKey); event.stop(); } else if (code == 32 && event.shiftKey && this.options.tabMode == "default") { // space this.handleTab(true); event.stop(); } else if (code == 36 && !event.shiftKey && !event.ctrlKey) { // home if (this.home()) event.stop(); } else if (code == 35 && !event.shiftKey && !event.ctrlKey) { // end if (this.end()) event.stop(); } // Only in Firefox is the default behavior for PgUp/PgDn correct. else if (code == 33 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgUp if (this.pageUp()) event.stop(); } else if (code == 34 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgDn if (this.pageDown()) event.stop(); } else if ((code == 219 || code == 221) && event.ctrlKey && !event.altKey) { // [, ] this.highlightParens(event.shiftKey, true); event.stop(); } else if (event.metaKey && !event.shiftKey && (code == 37 || code == 39)) { // Meta-left/right var cursor = select.selectionTopNode(this.container); if (cursor === false || !this.container.firstChild) return; if (code == 37) select.focusAfterNode(startOfLine(cursor), this.container); else { var end = endOfLine(cursor, this.container); select.focusAfterNode(end ? end.previousSibling : this.container.lastChild, this.container); } event.stop(); } else if ((event.ctrlKey || event.metaKey) && !event.altKey) { if ((event.shiftKey && code == 90) || code == 89) { // shift-Z, Y select.scrollToNode(this.history.redo()); event.stop(); } else if (code == 90 || (safari && code == 8)) { // Z, backspace select.scrollToNode(this.history.undo()); event.stop(); } else if (code == 83 && this.options.saveFunction) { // S this.options.saveFunction(); event.stop(); } else if (code == 86 && !mac) { // V this.reroutePasteEvent(); } } }, // Check for characters that should re-indent the current line, // and prevent Opera from handling enter and tab anyway. keyPress: function(event) { var electric = this.options.electricChars && Editor.Parser.electricChars, self = this; // Hack for Opera, and Firefox on OS X, in which stopping a // keydown event does not prevent the associated keypress event // from happening, so we have to cancel enter and tab again // here. if ((this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode || event.code, event))) || event.code == 13 || (event.code == 9 && this.options.tabMode != "default") || (event.code == 32 && event.shiftKey && this.options.tabMode == "default")) event.stop(); else if (mac && (event.ctrlKey || event.metaKey) && event.character == "v") { this.reroutePasteEvent(); } else if (electric && electric.indexOf(event.character) != -1) parent.setTimeout(function(){self.indentAtCursor(null);}, 0); // Work around a bug where pressing backspace at the end of a // line, or delete at the start, often causes the cursor to jump // to the start of the line in Opera 10.60. else if (brokenOpera) { if (event.code == 8) { // backspace var sel = select.selectionTopNode(this.container), self = this, next = sel ? sel.nextSibling : this.container.firstChild; if (sel !== false && next && isBR(next)) parent.setTimeout(function(){ if (select.selectionTopNode(self.container) == next) select.focusAfterNode(next.previousSibling, self.container); }, 20); } else if (event.code == 46) { // delete var sel = select.selectionTopNode(this.container), self = this; if (sel && isBR(sel)) { parent.setTimeout(function(){ if (select.selectionTopNode(self.container) != sel) select.focusAfterNode(sel, self.container); }, 20); } } } // In 533.* WebKit versions, when the document is big, typing // something at the end of a line causes the browser to do some // kind of stupid heavy operation, creating delays of several // seconds before the typed characters appear. This very crude // hack inserts a temporary zero-width space after the cursor to // make it not be at the end of the line. else if (slowWebkit) { var sel = select.selectionTopNode(this.container), next = sel ? sel.nextSibling : this.container.firstChild; // Doesn't work on empty lines, for some reason those always // trigger the delay. if (sel && next && isBR(next) && !isBR(sel)) { var cheat = document.createTextNode("\u200b"); this.container.insertBefore(cheat, next); parent.setTimeout(function() { if (cheat.nodeValue == "\u200b") removeElement(cheat); else cheat.nodeValue = cheat.nodeValue.replace("\u200b", ""); }, 20); } } // Magic incantation that works abound a webkit bug when you // can't type on a blank line following a line that's wider than // the window. if (webkit && !this.options.textWrapping) setTimeout(function () { var node = select.selectionTopNode(self.container, true); if (node && node.nodeType == 3 && node.previousSibling && isBR(node.previousSibling) && node.nextSibling && isBR(node.nextSibling)) node.parentNode.replaceChild(document.createElement("BR"), node.previousSibling); }, 50); }, // Mark the node at the cursor dirty when a non-safe key is // released. keyUp: function(event) { this.cursorActivity(isSafeKey(event.keyCode)); }, // Indent the line following a given <br>, or null for the first // line. If given a <br> element, this must have been highlighted // so that it has an indentation method. Returns the whitespace // element that has been modified or created (if any). indentLineAfter: function(start, direction) { function whiteSpaceAfter(node) { var ws = node ? node.nextSibling : self.container.firstChild; if (!ws || !hasClass(ws, "whitespace")) return null; return ws; } // whiteSpace is the whitespace span at the start of the line, // or null if there is no such node. var self = this, whiteSpace = whiteSpaceAfter(start); var newIndent = 0, curIndent = whiteSpace ? whiteSpace.currentText.length : 0; var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild); if (direction == "keep") { if (start) { var prevWS = whiteSpaceAfter(startOfLine(start.previousSibling)) if (prevWS) newIndent = prevWS.currentText.length; } } else { // Sometimes the start of the line can influence the correct // indentation, so we retrieve it. var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : ""; // Ask the lexical context for the correct indentation, and // compute how much this differs from the current indentation. if (direction != null && this.options.tabMode != "indent") newIndent = direction ? curIndent + indentUnit : Math.max(0, curIndent - indentUnit) else if (start) newIndent = start.indentation(nextChars, curIndent, direction, firstText); else if (Editor.Parser.firstIndentation) newIndent = Editor.Parser.firstIndentation(nextChars, curIndent, direction, firstText); } var indentDiff = newIndent - curIndent; // If there is too much, this is just a matter of shrinking a span. if (indentDiff < 0) { if (newIndent == 0) { if (firstText) select.snapshotMove(whiteSpace.firstChild, firstText.firstChild || firstText, 0); removeElement(whiteSpace); whiteSpace = null; } else { select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true); whiteSpace.currentText = makeWhiteSpace(newIndent); whiteSpace.firstChild.nodeValue = whiteSpace.currentText; } } // Not enough... else if (indentDiff > 0) { // If there is whitespace, we grow it. if (whiteSpace) { whiteSpace.currentText = makeWhiteSpace(newIndent); whiteSpace.firstChild.nodeValue = whiteSpace.currentText; select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true); } // Otherwise, we have to add a new whitespace node. else { whiteSpace = makePartSpan(makeWhiteSpace(newIndent)); whiteSpace.className = "whitespace"; if (start) insertAfter(whiteSpace, start); else this.container.insertBefore(whiteSpace, this.container.firstChild); select.snapshotMove(firstText && (firstText.firstChild || firstText), whiteSpace.firstChild, newIndent, false, true); } } // Make sure cursor ends up after the whitespace else if (whiteSpace) { select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, newIndent, false); } if (indentDiff != 0) this.addDirtyNode(start); }, // Re-highlight the selected part of the document. highlightAtCursor: function() { var pos = select.selectionTopNode(this.container, true); var to = select.selectionTopNode(this.container, false); if (pos === false || to === false) return false; select.markSelection(); if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false) return false; select.selectMarked(); return true; }, // When tab is pressed with text selected, the whole selection is // re-indented, when nothing is selected, the line with the cursor // is re-indented. handleTab: function(direction) { if (this.options.tabMode == "spaces" && !select.somethingSelected()) select.insertTabAtCursor(); else this.reindentSelection(direction); }, // Custom home behaviour that doesn't land the cursor in front of // leading whitespace unless pressed twice. home: function() { var cur = select.selectionTopNode(this.container, true), start = cur; if (cur === false || !(!cur || cur.isPart || isBR(cur)) || !this.container.firstChild) return false; while (cur && !isBR(cur)) cur = cur.previousSibling; var next = cur ? cur.nextSibling : this.container.firstChild; if (next && next != start && next.isPart && hasClass(next, "whitespace")) select.focusAfterNode(next, this.container); else select.focusAfterNode(cur, this.container); select.scrollToCursor(this.container); return true; }, // Some browsers (Opera) don't manage to handle the end key // properly in the face of vertical scrolling. end: function() { var cur = select.selectionTopNode(this.container, true); if (cur === false) return false; cur = endOfLine(cur, this.container); if (!cur) return false; select.focusAfterNode(cur.previousSibling, this.container); select.scrollToCursor(this.container); return true; }, pageUp: function() { var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount(); if (line === false || scrollAmount === false) return false; // Try to keep one line on the screen. scrollAmount -= 2; for (var i = 0; i < scrollAmount; i++) { line = this.prevLine(line); if (line === false) break; } if (i == 0) return false; // Already at first line select.setCursorPos(this.container, {node: line, offset: 0}); select.scrollToCursor(this.container); return true; }, pageDown: function() { var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount(); if (line === false || scrollAmount === false) return false; // Try to move to the last line of the current page. scrollAmount -= 2; for (var i = 0; i < scrollAmount; i++) { var nextLine = this.nextLine(line); if (nextLine === false) break; line = nextLine; } if (i == 0) return false; // Already at last line select.setCursorPos(this.container, {node: line, offset: 0}); select.scrollToCursor(this.container); return true; }, // Delay (or initiate) the next paren highlight event. scheduleParenHighlight: function() { if (this.parenEvent) parent.clearTimeout(this.parenEvent); var self = this; this.parenEvent = parent.setTimeout(function(){self.highlightParens();}, 300); }, // Take the token before the cursor. If it contains a character in // '()[]{}', search for the matching paren/brace/bracket, and // highlight them in green for a moment, or red if no proper match // was found. highlightParens: function(jump, fromKey) { var self = this, mark = this.options.markParen; if (typeof mark == "string") mark = [mark, mark]; // give the relevant nodes a colour. function highlight(node, ok) { if (!node) return; if (!mark) { node.style.fontWeight = "bold"; node.style.color = ok ? "#8F8" : "#F88"; } else if (mark.call) mark(node, ok); else node.className += " " + mark[ok ? 0 : 1]; } function unhighlight(node) { if (!node) return; if (mark && !mark.call) removeClass(removeClass(node, mark[0]), mark[1]); else if (self.options.unmarkParen) self.options.unmarkParen(node); else { node.style.fontWeight = ""; node.style.color = ""; } } if (!fromKey && self.highlighted) { unhighlight(self.highlighted[0]); unhighlight(self.highlighted[1]); } if (!window || !window.parent || !window.select) return; // Clear the event property. if (this.parenEvent) parent.clearTimeout(this.parenEvent); this.parenEvent = null; // Extract a 'paren' from a piece of text. function paren(node) { if (node.currentText) { var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/); return match && match[1]; } } // Determine the direction a paren is facing. function forward(ch) { return /[\(\[\{]/.test(ch); } var ch, cursor = select.selectionTopNode(this.container, true); if (!cursor || !this.highlightAtCursor()) return; cursor = select.selectionTopNode(this.container, true); if (!(cursor && ((ch = paren(cursor)) || (cursor = cursor.nextSibling) && (ch = paren(cursor))))) return; // We only look for tokens with the same className. var className = cursor.className, dir = forward(ch), match = matching[ch]; // Since parts of the document might not have been properly // highlighted, and it is hard to know in advance which part we // have to scan, we just try, and when we find dirty nodes we // abort, parse them, and re-try. function tryFindMatch() { var stack = [], ch, ok = true; for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) { if (runner.className == className && isSpan(runner) && (ch = paren(runner))) { if (forward(ch) == dir) stack.push(ch); else if (!stack.length) ok = false; else if (stack.pop() != matching[ch]) ok = false; if (!stack.length) break; } else if (runner.dirty || !isSpan(runner) && !isBR(runner)) { return {node: runner, status: "dirty"}; } } return {node: runner, status: runner && ok}; } while (true) { var found = tryFindMatch(); if (found.status == "dirty") { this.highlight(found.node, endOfLine(found.node)); // Needed because in some corner cases a highlight does not // reach a node. found.node.dirty = false; continue; } else { highlight(cursor, found.status); highlight(found.node, found.status); if (fromKey) parent.setTimeout(function() {unhighlight(cursor); unhighlight(found.node);}, 500); else self.highlighted = [cursor, found.node]; if (jump && found.node) select.focusAfterNode(found.node.previousSibling, this.container); break; } } }, // Adjust the amount of whitespace at the start of the line that // the cursor is on so that it is indented properly. indentAtCursor: function(direction) { if (!this.container.firstChild) return; // The line has to have up-to-date lexical information, so we // highlight it first. if (!this.highlightAtCursor()) return; var cursor = select.selectionTopNode(this.container, false); // If we couldn't determine the place of the cursor, // there's nothing to indent. if (cursor === false) return; select.markSelection(); this.indentLineAfter(startOfLine(cursor), direction); select.selectMarked(); }, // Indent all lines whose start falls inside of the current // selection. indentRegion: function(start, end, direction, selectAfter) { var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling); if (!isBR(end)) end = endOfLine(end, this.container); this.addDirtyNode(start); do { var next = endOfLine(current, this.container); if (current) this.highlight(before, next, true); this.indentLineAfter(current, direction); before = current; current = next; } while (current != end); if (selectAfter) select.setCursorPos(this.container, {node: start, offset: 0}, {node: end, offset: 0}); }, // Find the node that the cursor is in, mark it as dirty, and make // sure a highlight pass is scheduled. cursorActivity: function(safe) { // pagehide event hack above if (this.unloaded) { window.document.designMode = "off"; window.document.designMode = "on"; this.unloaded = false; } if (internetExplorer) { this.container.createTextRange().execCommand("unlink"); clearTimeout(this.saveSelectionSnapshot); var self = this; this.saveSelectionSnapshot = setTimeout(function() { var snapshot = select.getBookmark(self.container); if (snapshot) self.selectionSnapshot = snapshot; }, 200); } var activity = this.options.onCursorActivity; if (!safe || activity) { var cursor = select.selectionTopNode(this.container, false); if (cursor === false || !this.container.firstChild) return; cursor = cursor || this.container.firstChild; if (activity) activity(cursor); if (!safe) { this.scheduleHighlight(); this.addDirtyNode(cursor); } } }, reparseBuffer: function() { forEach(this.container.childNodes, function(node) {node.dirty = true;}); if (this.container.firstChild) this.addDirtyNode(this.container.firstChild); }, // Add a node to the set of dirty nodes, if it isn't already in // there. addDirtyNode: function(node) { node = node || this.container.firstChild; if (!node) return; for (var i = 0; i < this.dirty.length; i++) if (this.dirty[i] == node) return; if (node.nodeType != 3) node.dirty = true; this.dirty.push(node); }, allClean: function() { return !this.dirty.length; }, // Cause a highlight pass to happen in options.passDelay // milliseconds. Clear the existing timeout, if one exists. This // way, the passes do not happen while the user is typing, and // should as unobtrusive as possible. scheduleHighlight: function() { // Timeouts are routed through the parent window, because on // some browsers designMode windows do not fire timeouts. var self = this; parent.clearTimeout(this.highlightTimeout); this.highlightTimeout = parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay); }, // Fetch one dirty node, and remove it from the dirty set. getDirtyNode: function() { while (this.dirty.length > 0) { var found = this.dirty.pop(); // IE8 sometimes throws an unexplainable 'invalid argument' // exception for found.parentNode try { // If the node has been coloured in the meantime, or is no // longer in the document, it should not be returned. while (found && found.parentNode != this.container) found = found.parentNode; if (found && (found.dirty || found.nodeType == 3)) return found; } catch (e) {} } return null; }, // Pick dirty nodes, and highlight them, until options.passTime // milliseconds have gone by. The highlight method will continue // to next lines as long as it finds dirty nodes. It returns // information about the place where it stopped. If there are // dirty nodes left after this function has spent all its lines, // it shedules another highlight to finish the job. highlightDirty: function(force) { // Prevent FF from raising an error when it is firing timeouts // on a page that's no longer loaded. if (!window || !window.parent || !window.select) return false; if (!this.options.readOnly) select.markSelection(); var start, endTime = force ? null : time() + this.options.passTime; while ((time() < endTime || force) && (start = this.getDirtyNode())) { var result = this.highlight(start, endTime); if (result && result.node && result.dirty) this.addDirtyNode(result.node.nextSibling); } if (!this.options.readOnly) select.selectMarked(); if (start) this.scheduleHighlight(); return this.dirty.length == 0; }, // Creates a function that, when called through a timeout, will // continuously re-parse the document. documentScanner: function(passTime) { var self = this, pos = null; return function() { // FF timeout weirdness workaround. if (!window || !window.parent || !window.select) return; // If the current node is no longer in the document... oh // well, we start over. if (pos && pos.parentNode != self.container) pos = null; select.markSelection(); var result = self.highlight(pos, time() + passTime, true); select.selectMarked(); var newPos = result ? (result.node && result.node.nextSibling) : null; pos = (pos == newPos) ? null : newPos; self.delayScanning(); }; }, // Starts the continuous scanning process for this document after // a given interval. delayScanning: function() { if (this.scanner) { parent.clearTimeout(this.documentScan); this.documentScan = parent.setTimeout(this.scanner, this.options.continuousScanning); } }, // The function that does the actual highlighting/colouring (with // help from the parser and the DOM normalizer). Its interface is // rather overcomplicated, because it is used in different // situations: ensuring that a certain line is highlighted, or // highlighting up to X milliseconds starting from a certain // point. The 'from' argument gives the node at which it should // start. If this is null, it will start at the beginning of the // document. When a timestamp is given with the 'target' argument, // it will stop highlighting at that time. If this argument holds // a DOM node, it will highlight until it reaches that node. If at // any time it comes across two 'clean' lines (no dirty nodes), it // will stop, except when 'cleanLines' is true. maxBacktrack is // the maximum number of lines to backtrack to find an existing // parser instance. This is used to give up in situations where a // highlight would take too long and freeze the browser interface. highlight: function(from, target, cleanLines, maxBacktrack){ var container = this.container, self = this, active = this.options.activeTokens; var endTime = (typeof target == "number" ? target : null); if (!container.firstChild) return false; // Backtrack to the first node before from that has a partial // parse stored. while (from && (!from.parserFromHere || from.dirty)) { if (maxBacktrack != null && isBR(from) && (--maxBacktrack) < 0) return false; from = from.previousSibling; } // If we are at the end of the document, do nothing. if (from && !from.nextSibling) return false; // Check whether a part (<span> node) and the corresponding token // match. function correctPart(token, part){ return !part.reduced && part.currentText == token.value && part.className == token.style; } // Shorten the text associated with a part by chopping off // characters from the front. Note that only the currentText // property gets changed. For efficiency reasons, we leave the // nodeValue alone -- we set the reduced flag to indicate that // this part must be replaced. function shortenPart(part, minus){ part.currentText = part.currentText.substring(minus); part.reduced = true; } // Create a part corresponding to a given token. function tokenPart(token){ var part = makePartSpan(token.value); part.className = token.style; return part; } function maybeTouch(node) { if (node) { var old = node.oldNextSibling; if (lineDirty || old === undefined || node.nextSibling != old) self.history.touch(node); node.oldNextSibling = node.nextSibling; } else { var old = self.container.oldFirstChild; if (lineDirty || old === undefined || self.container.firstChild != old) self.history.touch(null); self.container.oldFirstChild = self.container.firstChild; } } // Get the token stream. If from is null, we start with a new // parser from the start of the frame, otherwise a partial parse // is resumed. var traversal = traverseDOM(from ? from.nextSibling : container.firstChild), stream = stringStream(traversal), parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream); function surroundedByBRs(node) { return (node.previousSibling == null || isBR(node.previousSibling)) && (node.nextSibling == null || isBR(node.nextSibling)); } // parts is an interface to make it possible to 'delay' fetching // the next DOM node until we are completely done with the one // before it. This is necessary because often the next node is // not yet available when we want to proceed past the current // one. var parts = { current: null, // Fetch current node. get: function(){ if (!this.current) this.current = traversal.nodes.shift(); return this.current; }, // Advance to the next part (do not fetch it yet). next: function(){ this.current = null; }, // Remove the current part from the DOM tree, and move to the // next. remove: function(){ container.removeChild(this.get()); this.current = null; }, // Advance to the next part that is not empty, discarding empty // parts. getNonEmpty: function(){ var part = this.get(); // Allow empty nodes when they are alone on a line, needed // for the FF cursor bug workaround (see select.js, // insertNewlineAtCursor). while (part && isSpan(part) && part.currentText == "") { // Leave empty nodes that are alone on a line alone in // Opera, since that browsers doesn't deal well with // having 2 BRs in a row. if (window.opera && surroundedByBRs(part)) { this.next(); part = this.get(); } else { var old = part; this.remove(); part = this.get(); // Adjust selection information, if any. See select.js for details. select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0); } } return part; } }; var lineDirty = false, prevLineDirty = true, lineNodes = 0; // This forEach loops over the tokens from the parsed stream, and // at the same time uses the parts object to proceed through the // corresponding DOM nodes. forEach(parsed, function(token){ var part = parts.getNonEmpty(); if (token.value == "\n"){ // The idea of the two streams actually staying synchronized // is such a long shot that we explicitly check. if (!isBR(part)) throw "Parser out of sync. Expected BR."; if (part.dirty || !part.indentation) lineDirty = true; maybeTouch(from); from = part; // Every <br> gets a copy of the parser state and a lexical // context assigned to it. The first is used to be able to // later resume parsing from this point, the second is used // for indentation. part.parserFromHere = parsed.copy(); part.indentation = token.indentation || alwaysZero; part.dirty = false; // If the target argument wasn't an integer, go at least // until that node. if (endTime == null && part == target) throw StopIteration; // A clean line with more than one node means we are done. // Throwing a StopIteration is the way to break out of a // MochiKit forEach loop. if ((endTime != null && time() >= endTime) || (!lineDirty && !prevLineDirty && lineNodes > 1 && !cleanLines)) throw StopIteration; prevLineDirty = lineDirty; lineDirty = false; lineNodes = 0; parts.next(); } else { if (!isSpan(part)) throw "Parser out of sync. Expected SPAN."; if (part.dirty) lineDirty = true; lineNodes++; // If the part matches the token, we can leave it alone. if (correctPart(token, part)){ if (active && part.dirty) active(part, token, self); part.dirty = false; parts.next(); } // Otherwise, we have to fix it. else { lineDirty = true; // Insert the correct part. var newPart = tokenPart(token); container.insertBefore(newPart, part); if (active) active(newPart, token, self); var tokensize = token.value.length; var offset = 0; // Eat up parts until the text for this token has been // removed, adjusting the stored selection info (see // select.js) in the process. while (tokensize > 0) { part = parts.get(); var partsize = part.currentText.length; select.snapshotReplaceNode(part.firstChild, newPart.firstChild, tokensize, offset); if (partsize > tokensize){ shortenPart(part, tokensize); tokensize = 0; } else { tokensize -= partsize; offset += partsize; parts.remove(); } } } } }); maybeTouch(from); webkitLastLineHack(this.container); // The function returns some status information that is used by // hightlightDirty to determine whether and where it has to // continue. return {node: parts.getNonEmpty(), dirty: lineDirty}; } }; return Editor; })(); addEventHandler(window, "load", function() { var CodeMirror = window.frameElement.CodeMirror; var e = CodeMirror.editor = new Editor(CodeMirror.options); parent.setTimeout(method(CodeMirror, "init"), 0); }); /* Functionality for finding, storing, and restoring selections * * This does not provide a generic API, just the minimal functionality * required by the CodeMirror system. */ // Namespace object. var select = {}; (function() { select.ie_selection = document.selection && document.selection.createRangeCollection; // Find the 'top-level' (defined as 'a direct child of the node // passed as the top argument') node that the given node is // contained in. Return null if the given node is not inside the top // node. function topLevelNodeAt(node, top) { while (node && node.parentNode != top) node = node.parentNode; return node; } // Find the top-level node that contains the node before this one. function topLevelNodeBefore(node, top) { while (!node.previousSibling && node.parentNode != top) node = node.parentNode; return topLevelNodeAt(node.previousSibling, top); } var fourSpaces = "\u00a0\u00a0\u00a0\u00a0"; select.scrollToNode = function(node, cursor) { if (!node) return; var element = node, body = document.body, html = document.documentElement, atEnd = !element.nextSibling || !element.nextSibling.nextSibling || !element.nextSibling.nextSibling.nextSibling; // In Opera (and recent Webkit versions), BR elements *always* // have a offsetTop property of zero. var compensateHack = 0; while (element && !element.offsetTop) { compensateHack++; element = element.previousSibling; } // atEnd is another kludge for these browsers -- if the cursor is // at the end of the document, and the node doesn't have an // offset, just scroll to the end. if (compensateHack == 0) atEnd = false; // WebKit has a bad habit of (sometimes) happily returning bogus // offsets when the document has just been changed. This seems to // always be 5/5, so we don't use those. if (webkit && element && element.offsetTop == 5 && element.offsetLeft == 5) return; var y = compensateHack * (element ? element.offsetHeight : 0), x = 0, width = (node ? node.offsetWidth : 0), pos = element; while (pos && pos.offsetParent) { y += pos.offsetTop; // Don't count X offset for <br> nodes if (!isBR(pos)) x += pos.offsetLeft; pos = pos.offsetParent; } var scroll_x = body.scrollLeft || html.scrollLeft || 0, scroll_y = body.scrollTop || html.scrollTop || 0, scroll = false, screen_width = window.innerWidth || html.clientWidth || 0; if (cursor || width < screen_width) { if (cursor) { var off = select.offsetInNode(node), size = nodeText(node).length; if (size) x += width * (off / size); } var screen_x = x - scroll_x; if (screen_x < 0 || screen_x > screen_width) { scroll_x = x; scroll = true; } } var screen_y = y - scroll_y; if (screen_y < 0 || atEnd || screen_y > (window.innerHeight || html.clientHeight || 0) - 50) { scroll_y = atEnd ? 1e6 : y; scroll = true; } if (scroll) window.scrollTo(scroll_x, scroll_y); }; select.scrollToCursor = function(container) { select.scrollToNode(select.selectionTopNode(container, true) || container.firstChild, true); }; // Used to prevent restoring a selection when we do not need to. var currentSelection = null; select.snapshotChanged = function() { if (currentSelection) currentSelection.changed = true; }; // Find the 'leaf' node (BR or text) after the given one. function baseNodeAfter(node) { var next = node.nextSibling; if (next) { while (next.firstChild) next = next.firstChild; if (next.nodeType == 3 || isBR(next)) return next; else return baseNodeAfter(next); } else { var parent = node.parentNode; while (parent && !parent.nextSibling) parent = parent.parentNode; return parent && baseNodeAfter(parent); } } // This is called by the code in editor.js whenever it is replacing // a text node. The function sees whether the given oldNode is part // of the current selection, and updates this selection if it is. // Because nodes are often only partially replaced, the length of // the part that gets replaced has to be taken into account -- the // selection might stay in the oldNode if the newNode is smaller // than the selection's offset. The offset argument is needed in // case the selection does move to the new object, and the given // length is not the whole length of the new node (part of it might // have been used to replace another node). select.snapshotReplaceNode = function(from, to, length, offset) { if (!currentSelection) return; function replace(point) { if (from == point.node) { currentSelection.changed = true; if (length && point.offset > length) { point.offset -= length; } else { point.node = to; point.offset += (offset || 0); } } else if (select.ie_selection && point.offset == 0 && point.node == baseNodeAfter(from)) { currentSelection.changed = true; } } replace(currentSelection.start); replace(currentSelection.end); }; select.snapshotMove = function(from, to, distance, relative, ifAtStart) { if (!currentSelection) return; function move(point) { if (from == point.node && (!ifAtStart || point.offset == 0)) { currentSelection.changed = true; point.node = to; if (relative) point.offset = Math.max(0, point.offset + distance); else point.offset = distance; } } move(currentSelection.start); move(currentSelection.end); }; // Most functions are defined in two ways, one for the IE selection // model, one for the W3C one. if (select.ie_selection) { function selRange() { var sel = document.selection; if (!sel) return null; if (sel.createRange) return sel.createRange(); else return sel.createTextRange(); } function selectionNode(start) { var range = selRange(); range.collapse(start); function nodeAfter(node) { var found = null; while (!found && node) { found = node.nextSibling; node = node.parentNode; } return nodeAtStartOf(found); } function nodeAtStartOf(node) { while (node && node.firstChild) node = node.firstChild; return {node: node, offset: 0}; } var containing = range.parentElement(); if (!isAncestor(document.body, containing)) return null; if (!containing.firstChild) return nodeAtStartOf(containing); var working = range.duplicate(); working.moveToElementText(containing); working.collapse(true); for (var cur = containing.firstChild; cur; cur = cur.nextSibling) { if (cur.nodeType == 3) { var size = cur.nodeValue.length; working.move("character", size); } else { working.moveToElementText(cur); working.collapse(false); } var dir = range.compareEndPoints("StartToStart", working); if (dir == 0) return nodeAfter(cur); if (dir == 1) continue; if (cur.nodeType != 3) return nodeAtStartOf(cur); working.setEndPoint("StartToEnd", range); return {node: cur, offset: size - working.text.length}; } return nodeAfter(containing); } select.markSelection = function() { currentSelection = null; var sel = document.selection; if (!sel) return; var start = selectionNode(true), end = selectionNode(false); if (!start || !end) return; currentSelection = {start: start, end: end, changed: false}; }; select.selectMarked = function() { if (!currentSelection || !currentSelection.changed) return; function makeRange(point) { var range = document.body.createTextRange(), node = point.node; if (!node) { range.moveToElementText(document.body); range.collapse(false); } else if (node.nodeType == 3) { range.moveToElementText(node.parentNode); var offset = point.offset; while (node.previousSibling) { node = node.previousSibling; offset += (node.innerText || "").length; } range.move("character", offset); } else { range.moveToElementText(node); range.collapse(true); } return range; } var start = makeRange(currentSelection.start), end = makeRange(currentSelection.end); start.setEndPoint("StartToEnd", end); start.select(); }; select.offsetInNode = function(node) { var range = selRange(); if (!range) return 0; var range2 = range.duplicate(); try {range2.moveToElementText(node);} catch(e){return 0;} range.setEndPoint("StartToStart", range2); return range.text.length; }; // Get the top-level node that one end of the cursor is inside or // after. Note that this returns false for 'no cursor', and null // for 'start of document'. select.selectionTopNode = function(container, start) { var range = selRange(); if (!range) return false; var range2 = range.duplicate(); range.collapse(start); var around = range.parentElement(); if (around && isAncestor(container, around)) { // Only use this node if the selection is not at its start. range2.moveToElementText(around); if (range.compareEndPoints("StartToStart", range2) == 1) return topLevelNodeAt(around, container); } // Move the start of a range to the start of a node, // compensating for the fact that you can't call // moveToElementText with text nodes. function moveToNodeStart(range, node) { if (node.nodeType == 3) { var count = 0, cur = node.previousSibling; while (cur && cur.nodeType == 3) { count += cur.nodeValue.length; cur = cur.previousSibling; } if (cur) { try{range.moveToElementText(cur);} catch(e){return false;} range.collapse(false); } else range.moveToElementText(node.parentNode); if (count) range.move("character", count); } else { try{range.moveToElementText(node);} catch(e){return false;} } return true; } // Do a binary search through the container object, comparing // the start of each node to the selection var start = 0, end = container.childNodes.length - 1; while (start < end) { var middle = Math.ceil((end + start) / 2), node = container.childNodes[middle]; if (!node) return false; // Don't ask. IE6 manages this sometimes. if (!moveToNodeStart(range2, node)) return false; if (range.compareEndPoints("StartToStart", range2) == 1) start = middle; else end = middle - 1; } if (start == 0) { var test1 = selRange(), test2 = test1.duplicate(); try { test2.moveToElementText(container); } catch(exception) { return null; } if (test1.compareEndPoints("StartToStart", test2) == 0) return null; } return container.childNodes[start] || null; }; // Place the cursor after this.start. This is only useful when // manually moving the cursor instead of restoring it to its old // position. select.focusAfterNode = function(node, container) { var range = document.body.createTextRange(); range.moveToElementText(node || container); range.collapse(!node); range.select(); }; select.somethingSelected = function() { var range = selRange(); return range && (range.text != ""); }; function insertAtCursor(html) { var range = selRange(); if (range) { range.pasteHTML(html); range.collapse(false); range.select(); } } // Used to normalize the effect of the enter key, since browsers // do widely different things when pressing enter in designMode. select.insertNewlineAtCursor = function() { insertAtCursor("<br>"); }; select.insertTabAtCursor = function() { insertAtCursor(fourSpaces); }; // Get the BR node at the start of the line on which the cursor // currently is, and the offset into the line. Returns null as // node if cursor is on first line. select.cursorPos = function(container, start) { var range = selRange(); if (!range) return null; var topNode = select.selectionTopNode(container, start); while (topNode && !isBR(topNode)) topNode = topNode.previousSibling; var range2 = range.duplicate(); range.collapse(start); if (topNode) { range2.moveToElementText(topNode); range2.collapse(false); } else { // When nothing is selected, we can get all kinds of funky errors here. try { range2.moveToElementText(container); } catch (e) { return null; } range2.collapse(true); } range.setEndPoint("StartToStart", range2); return {node: topNode, offset: range.text.length}; }; select.setCursorPos = function(container, from, to) { function rangeAt(pos) { var range = document.body.createTextRange(); if (!pos.node) { range.moveToElementText(container); range.collapse(true); } else { range.moveToElementText(pos.node); range.collapse(false); } range.move("character", pos.offset); return range; } var range = rangeAt(from); if (to && to != from) range.setEndPoint("EndToEnd", rangeAt(to)); range.select(); } // Some hacks for storing and re-storing the selection when the editor loses and regains focus. select.getBookmark = function (container) { var from = select.cursorPos(container, true), to = select.cursorPos(container, false); if (from && to) return {from: from, to: to}; }; // Restore a stored selection. select.setBookmark = function(container, mark) { if (!mark) return; select.setCursorPos(container, mark.from, mark.to); }; } // W3C model else { // Find the node right at the cursor, not one of its // ancestors with a suitable offset. This goes down the DOM tree // until a 'leaf' is reached (or is it *up* the DOM tree?). function innerNode(node, offset) { while (node.nodeType != 3 && !isBR(node)) { var newNode = node.childNodes[offset] || node.nextSibling; offset = 0; while (!newNode && node.parentNode) { node = node.parentNode; newNode = node.nextSibling; } node = newNode; if (!newNode) break; } return {node: node, offset: offset}; } // Store start and end nodes, and offsets within these, and refer // back to the selection object from those nodes, so that this // object can be updated when the nodes are replaced before the // selection is restored. select.markSelection = function () { var selection = window.getSelection(); if (!selection || selection.rangeCount == 0) return (currentSelection = null); var range = selection.getRangeAt(0); currentSelection = { start: innerNode(range.startContainer, range.startOffset), end: innerNode(range.endContainer, range.endOffset), changed: false }; }; select.selectMarked = function () { var cs = currentSelection; // on webkit-based browsers, it is apparently possible that the // selection gets reset even when a node that is not one of the // endpoints get messed with. the most common situation where // this occurs is when a selection is deleted or overwitten. we // check for that here. function focusIssue() { if (cs.start.node == cs.end.node && cs.start.offset == cs.end.offset) { var selection = window.getSelection(); if (!selection || selection.rangeCount == 0) return true; var range = selection.getRangeAt(0), point = innerNode(range.startContainer, range.startOffset); return cs.start.node != point.node || cs.start.offset != point.offset; } } if (!cs || !(cs.changed || (webkit && focusIssue()))) return; var range = document.createRange(); function setPoint(point, which) { if (point.node) { // Some magic to generalize the setting of the start and end // of a range. if (point.offset == 0) range["set" + which + "Before"](point.node); else range["set" + which](point.node, point.offset); } else { range.setStartAfter(document.body.lastChild || document.body); } } setPoint(cs.end, "End"); setPoint(cs.start, "Start"); selectRange(range); }; // Helper for selecting a range object. function selectRange(range) { var selection = window.getSelection(); if (!selection) return; selection.removeAllRanges(); selection.addRange(range); } function selectionRange() { var selection = window.getSelection(); if (!selection || selection.rangeCount == 0) return false; else return selection.getRangeAt(0); } // Finding the top-level node at the cursor in the W3C is, as you // can see, quite an involved process. select.selectionTopNode = function(container, start) { var range = selectionRange(); if (!range) return false; var node = start ? range.startContainer : range.endContainer; var offset = start ? range.startOffset : range.endOffset; // Work around (yet another) bug in Opera's selection model. if (window.opera && !start && range.endContainer == container && range.endOffset == range.startOffset + 1 && container.childNodes[range.startOffset] && isBR(container.childNodes[range.startOffset])) offset--; // For text nodes, we look at the node itself if the cursor is // inside, or at the node before it if the cursor is at the // start. if (node.nodeType == 3){ if (offset > 0) return topLevelNodeAt(node, container); else return topLevelNodeBefore(node, container); } // Occasionally, browsers will return the HTML node as // selection. If the offset is 0, we take the start of the frame // ('after null'), otherwise, we take the last node. else if (node.nodeName.toUpperCase() == "HTML") { return (offset == 1 ? null : container.lastChild); } // If the given node is our 'container', we just look up the // correct node by using the offset. else if (node == container) { return (offset == 0) ? null : node.childNodes[offset - 1]; } // In any other case, we have a regular node. If the cursor is // at the end of the node, we use the node itself, if it is at // the start, we use the node before it, and in any other // case, we look up the child before the cursor and use that. else { if (offset == node.childNodes.length) return topLevelNodeAt(node, container); else if (offset == 0) return topLevelNodeBefore(node, container); else return topLevelNodeAt(node.childNodes[offset - 1], container); } }; select.focusAfterNode = function(node, container) { var range = document.createRange(); range.setStartBefore(container.firstChild || container); // In Opera, setting the end of a range at the end of a line // (before a BR) will cause the cursor to appear on the next // line, so we set the end inside of the start node when // possible. if (node && !node.firstChild) range.setEndAfter(node); else if (node) range.setEnd(node, node.childNodes.length); else range.setEndBefore(container.firstChild || container); range.collapse(false); selectRange(range); }; select.somethingSelected = function() { var range = selectionRange(); return range && !range.collapsed; }; select.offsetInNode = function(node) { var range = selectionRange(); if (!range) return 0; range = range.cloneRange(); range.setStartBefore(node); return range.toString().length; }; select.insertNodeAtCursor = function(node) { var range = selectionRange(); if (!range) return; range.deleteContents(); range.insertNode(node); webkitLastLineHack(document.body); // work around weirdness where Opera will magically insert a new // BR node when a BR node inside a span is moved around. makes // sure the BR ends up outside of spans. if (window.opera && isBR(node) && isSpan(node.parentNode)) { var next = node.nextSibling, p = node.parentNode, outer = p.parentNode; outer.insertBefore(node, p.nextSibling); var textAfter = ""; for (; next && next.nodeType == 3; next = next.nextSibling) { textAfter += next.nodeValue; removeElement(next); } outer.insertBefore(makePartSpan(textAfter, document), node.nextSibling); } range = document.createRange(); range.selectNode(node); range.collapse(false); selectRange(range); } select.insertNewlineAtCursor = function() { select.insertNodeAtCursor(document.createElement("BR")); }; select.insertTabAtCursor = function() { select.insertNodeAtCursor(document.createTextNode(fourSpaces)); }; select.cursorPos = function(container, start) { var range = selectionRange(); if (!range) return; var topNode = select.selectionTopNode(container, start); while (topNode && !isBR(topNode)) topNode = topNode.previousSibling; range = range.cloneRange(); range.collapse(start); if (topNode) range.setStartAfter(topNode); else range.setStartBefore(container); var text = range.toString(); return {node: topNode, offset: text.length}; }; select.setCursorPos = function(container, from, to) { var range = document.createRange(); function setPoint(node, offset, side) { if (offset == 0 && node && !node.nextSibling) { range["set" + side + "After"](node); return true; } if (!node) node = container.firstChild; else node = node.nextSibling; if (!node) return; if (offset == 0) { range["set" + side + "Before"](node); return true; } var backlog = [] function decompose(node) { if (node.nodeType == 3) backlog.push(node); else forEach(node.childNodes, decompose); } while (true) { while (node && !backlog.length) { decompose(node); node = node.nextSibling; } var cur = backlog.shift(); if (!cur) return false; var length = cur.nodeValue.length; if (length >= offset) { range["set" + side](cur, offset); return true; } offset -= length; } } to = to || from; if (setPoint(to.node, to.offset, "End") && setPoint(from.node, from.offset, "Start")) selectRange(range); }; } })(); /* String streams are the things fed to parsers (which can feed them * to a tokenizer if they want). They provide peek and next methods * for looking at the current character (next 'consumes' this * character, peek does not), and a get method for retrieving all the * text that was consumed since the last time get was called. * * An easy mistake to make is to let a StopIteration exception finish * the token stream while there are still characters pending in the * string stream (hitting the end of the buffer while parsing a * token). To make it easier to detect such errors, the stringstreams * throw an exception when this happens. */ // Make a stringstream stream out of an iterator that returns strings. // This is applied to the result of traverseDOM (see codemirror.js), // and the resulting stream is fed to the parser. var stringStream = function(source){ // String that's currently being iterated over. var current = ""; // Position in that string. var pos = 0; // Accumulator for strings that have been iterated over but not // get()-ed yet. var accum = ""; // Make sure there are more characters ready, or throw // StopIteration. function ensureChars() { while (pos == current.length) { accum += current; current = ""; // In case source.next() throws pos = 0; try {current = source.next();} catch (e) { if (e != StopIteration) throw e; else return false; } } return true; } return { // peek: -> character // Return the next character in the stream. peek: function() { if (!ensureChars()) return null; return current.charAt(pos); }, // next: -> character // Get the next character, throw StopIteration if at end, check // for unused content. next: function() { if (!ensureChars()) { if (accum.length > 0) throw "End of stringstream reached without emptying buffer ('" + accum + "')."; else throw StopIteration; } return current.charAt(pos++); }, // get(): -> string // Return the characters iterated over since the last call to // .get(). get: function() { var temp = accum; accum = ""; if (pos > 0){ temp += current.slice(0, pos); current = current.slice(pos); pos = 0; } return temp; }, // Push a string back into the stream. push: function(str) { current = current.slice(0, pos) + str + current.slice(pos); }, lookAhead: function(str, consume, skipSpaces, caseInsensitive) { function cased(str) {return caseInsensitive ? str.toLowerCase() : str;} str = cased(str); var found = false; var _accum = accum, _pos = pos; if (skipSpaces) this.nextWhileMatches(/[\s\u00a0]/); while (true) { var end = pos + str.length, left = current.length - pos; if (end <= current.length) { found = str == cased(current.slice(pos, end)); pos = end; break; } else if (str.slice(0, left) == cased(current.slice(pos))) { accum += current; current = ""; try {current = source.next();} catch (e) {if (e != StopIteration) throw e; break;} pos = 0; str = str.slice(left); } else { break; } } if (!(found && consume)) { current = accum.slice(_accum.length) + current; pos = _pos; accum = _accum; } return found; }, // Wont't match past end of line. lookAheadRegex: function(regex, consume) { if (regex.source.charAt(0) != "^") throw new Error("Regexps passed to lookAheadRegex must start with ^"); // Fetch the rest of the line while (current.indexOf("\n", pos) == -1) { try {current += source.next();} catch (e) {if (e != StopIteration) throw e; break;} } var matched = current.slice(pos).match(regex); if (matched && consume) pos += matched[0].length; return matched; }, // Utils built on top of the above // more: -> boolean // Produce true if the stream isn't empty. more: function() { return this.peek() !== null; }, applies: function(test) { var next = this.peek(); return (next !== null && test(next)); }, nextWhile: function(test) { var next; while ((next = this.peek()) !== null && test(next)) this.next(); }, matches: function(re) { var next = this.peek(); return (next !== null && re.test(next)); }, nextWhileMatches: function(re) { var next; while ((next = this.peek()) !== null && re.test(next)) this.next(); }, equals: function(ch) { return ch === this.peek(); }, endOfLine: function() { var next = this.peek(); return next == null || next == "\n"; } }; }; // A framework for simple tokenizers. Takes care of newlines and // white-space, and of getting the text from the source stream into // the token object. A state is a function of two arguments -- a // string stream and a setState function. The second can be used to // change the tokenizer's state, and can be ignored for stateless // tokenizers. This function should advance the stream over a token // and return a string or object containing information about the next // token, or null to pass and have the (new) state be called to finish // the token. When a string is given, it is wrapped in a {style, type} // object. In the resulting object, the characters consumed are stored // under the content property. Any whitespace following them is also // automatically consumed, and added to the value property. (Thus, // content is the actual meaningful part of the token, while value // contains all the text it spans.) function tokenizer(source, state) { // Newlines are always a separate token. function isWhiteSpace(ch) { // The messy regexp is because IE's regexp matcher is of the // opinion that non-breaking spaces are no whitespace. return ch != "\n" && /^[\s\u00a0]*$/.test(ch); } var tokenizer = { state: state, take: function(type) { if (typeof(type) == "string") type = {style: type, type: type}; type.content = (type.content || "") + source.get(); if (!/\n$/.test(type.content)) source.nextWhile(isWhiteSpace); type.value = type.content + source.get(); return type; }, next: function () { if (!source.more()) throw StopIteration; var type; if (source.equals("\n")) { source.next(); return this.take("whitespace"); } if (source.applies(isWhiteSpace)) type = "whitespace"; else while (!type) type = this.state(source, function(s) {tokenizer.state = s;}); return this.take(type); } }; return tokenizer; } /** * Storage and control for undo information within a CodeMirror * editor. 'Why on earth is such a complicated mess required for * that?', I hear you ask. The goal, in implementing this, was to make * the complexity of storing and reverting undo information depend * only on the size of the edited or restored content, not on the size * of the whole document. This makes it necessary to use a kind of * 'diff' system, which, when applied to a DOM tree, causes some * complexity and hackery. * * In short, the editor 'touches' BR elements as it parses them, and * the UndoHistory stores these. When nothing is touched in commitDelay * milliseconds, the changes are committed: It goes over all touched * nodes, throws out the ones that did not change since last commit or * are no longer in the document, and assembles the rest into zero or * more 'chains' -- arrays of adjacent lines. Links back to these * chains are added to the BR nodes, while the chain that previously * spanned these nodes is added to the undo history. Undoing a change * means taking such a chain off the undo history, restoring its * content (text is saved per line) and linking it back into the * document. */ // A history object needs to know about the DOM container holding the // document, the maximum amount of undo levels it should store, the // delay (of no input) after which it commits a set of changes, and, // unfortunately, the 'parent' window -- a window that is not in // designMode, and on which setTimeout works in every browser. function UndoHistory(container, maxDepth, commitDelay, editor) { this.container = container; this.maxDepth = maxDepth; this.commitDelay = commitDelay; this.editor = editor; // This line object represents the initial, empty editor. var initial = {text: "", from: null, to: null}; // As the borders between lines are represented by BR elements, the // start of the first line and the end of the last one are // represented by null. Since you can not store any properties // (links to line objects) in null, these properties are used in // those cases. this.first = initial; this.last = initial; // Similarly, a 'historyTouched' property is added to the BR in // front of lines that have already been touched, and 'firstTouched' // is used for the first line. this.firstTouched = false; // History is the set of committed changes, touched is the set of // nodes touched since the last commit. this.history = []; this.redoHistory = []; this.touched = []; this.lostundo = 0; } UndoHistory.prototype = { // Schedule a commit (if no other touches come in for commitDelay // milliseconds). scheduleCommit: function() { var self = this; parent.clearTimeout(this.commitTimeout); this.commitTimeout = parent.setTimeout(function(){self.tryCommit();}, this.commitDelay); }, // Mark a node as touched. Null is a valid argument. touch: function(node) { this.setTouched(node); this.scheduleCommit(); }, // Undo the last change. undo: function() { // Make sure pending changes have been committed. this.commit(); if (this.history.length) { // Take the top diff from the history, apply it, and store its // shadow in the redo history. var item = this.history.pop(); this.redoHistory.push(this.updateTo(item, "applyChain")); this.notifyEnvironment(); return this.chainNode(item); } }, // Redo the last undone change. redo: function() { this.commit(); if (this.redoHistory.length) { // The inverse of undo, basically. var item = this.redoHistory.pop(); this.addUndoLevel(this.updateTo(item, "applyChain")); this.notifyEnvironment(); return this.chainNode(item); } }, clear: function() { this.history = []; this.redoHistory = []; this.lostundo = 0; }, // Ask for the size of the un/redo histories. historySize: function() { return {undo: this.history.length, redo: this.redoHistory.length, lostundo: this.lostundo}; }, // Push a changeset into the document. push: function(from, to, lines) { var chain = []; for (var i = 0; i < lines.length; i++) { var end = (i == lines.length - 1) ? to : document.createElement("br"); chain.push({from: from, to: end, text: cleanText(lines[i])}); from = end; } this.pushChains([chain], from == null && to == null); this.notifyEnvironment(); }, pushChains: function(chains, doNotHighlight) { this.commit(doNotHighlight); this.addUndoLevel(this.updateTo(chains, "applyChain")); this.redoHistory = []; }, // Retrieve a DOM node from a chain (for scrolling to it after undo/redo). chainNode: function(chains) { for (var i = 0; i < chains.length; i++) { var start = chains[i][0], node = start && (start.from || start.to); if (node) return node; } }, // Clear the undo history, make the current document the start // position. reset: function() { this.history = []; this.redoHistory = []; this.lostundo = 0; }, textAfter: function(br) { return this.after(br).text; }, nodeAfter: function(br) { return this.after(br).to; }, nodeBefore: function(br) { return this.before(br).from; }, // Commit unless there are pending dirty nodes. tryCommit: function() { if (!window || !window.parent || !window.UndoHistory) return; // Stop when frame has been unloaded if (this.editor.highlightDirty()) this.commit(true); else this.scheduleCommit(); }, // Check whether the touched nodes hold any changes, if so, commit // them. commit: function(doNotHighlight) { parent.clearTimeout(this.commitTimeout); // Make sure there are no pending dirty nodes. if (!doNotHighlight) this.editor.highlightDirty(true); // Build set of chains. var chains = this.touchedChains(), self = this; if (chains.length) { this.addUndoLevel(this.updateTo(chains, "linkChain")); this.redoHistory = []; this.notifyEnvironment(); } }, // [ end of public interface ] // Update the document with a given set of chains, return its // shadow. updateFunc should be "applyChain" or "linkChain". In the // second case, the chains are taken to correspond the the current // document, and only the state of the line data is updated. In the // first case, the content of the chains is also pushed iinto the // document. updateTo: function(chains, updateFunc) { var shadows = [], dirty = []; for (var i = 0; i < chains.length; i++) { shadows.push(this.shadowChain(chains[i])); dirty.push(this[updateFunc](chains[i])); } if (updateFunc == "applyChain") this.notifyDirty(dirty); return shadows; }, // Notify the editor that some nodes have changed. notifyDirty: function(nodes) { forEach(nodes, method(this.editor, "addDirtyNode")) this.editor.scheduleHighlight(); }, notifyEnvironment: function() { if (this.onChange) this.onChange(this.editor); // Used by the line-wrapping line-numbering code. if (window.frameElement && window.frameElement.CodeMirror.updateNumbers) window.frameElement.CodeMirror.updateNumbers(); }, // Link a chain into the DOM nodes (or the first/last links for null // nodes). linkChain: function(chain) { for (var i = 0; i < chain.length; i++) { var line = chain[i]; if (line.from) line.from.historyAfter = line; else this.first = line; if (line.to) line.to.historyBefore = line; else this.last = line; } }, // Get the line object after/before a given node. after: function(node) { return node ? node.historyAfter : this.first; }, before: function(node) { return node ? node.historyBefore : this.last; }, // Mark a node as touched if it has not already been marked. setTouched: function(node) { if (node) { if (!node.historyTouched) { this.touched.push(node); node.historyTouched = true; } } else { this.firstTouched = true; } }, // Store a new set of undo info, throw away info if there is more of // it than allowed. addUndoLevel: function(diffs) { this.history.push(diffs); if (this.history.length > this.maxDepth) { this.history.shift(); this.lostundo += 1; } }, // Build chains from a set of touched nodes. touchedChains: function() { var self = this; // The temp system is a crummy hack to speed up determining // whether a (currently touched) node has a line object associated // with it. nullTemp is used to store the object for the first // line, other nodes get it stored in their historyTemp property. var nullTemp = null; function temp(node) {return node ? node.historyTemp : nullTemp;} function setTemp(node, line) { if (node) node.historyTemp = line; else nullTemp = line; } function buildLine(node) { var text = []; for (var cur = node ? node.nextSibling : self.container.firstChild; cur && (!isBR(cur) || cur.hackBR); cur = cur.nextSibling) if (!cur.hackBR && cur.currentText) text.push(cur.currentText); return {from: node, to: cur, text: cleanText(text.join(""))}; } // Filter out unchanged lines and nodes that are no longer in the // document. Build up line objects for remaining nodes. var lines = []; if (self.firstTouched) self.touched.push(null); forEach(self.touched, function(node) { if (node && (node.parentNode != self.container || node.hackBR)) return; if (node) node.historyTouched = false; else self.firstTouched = false; var line = buildLine(node), shadow = self.after(node); if (!shadow || shadow.text != line.text || shadow.to != line.to) { lines.push(line); setTemp(node, line); } }); // Get the BR element after/before the given node. function nextBR(node, dir) { var link = dir + "Sibling", search = node[link]; while (search && !isBR(search)) search = search[link]; return search; } // Assemble line objects into chains by scanning the DOM tree // around them. var chains = []; self.touched = []; forEach(lines, function(line) { // Note that this makes the loop skip line objects that have // been pulled into chains by lines before them. if (!temp(line.from)) return; var chain = [], curNode = line.from, safe = true; // Put any line objects (referred to by temp info) before this // one on the front of the array. while (true) { var curLine = temp(curNode); if (!curLine) { if (safe) break; else curLine = buildLine(curNode); } chain.unshift(curLine); setTemp(curNode, null); if (!curNode) break; safe = self.after(curNode); curNode = nextBR(curNode, "previous"); } curNode = line.to; safe = self.before(line.from); // Add lines after this one at end of array. while (true) { if (!curNode) break; var curLine = temp(curNode); if (!curLine) { if (safe) break; else curLine = buildLine(curNode); } chain.push(curLine); setTemp(curNode, null); safe = self.before(curNode); curNode = nextBR(curNode, "next"); } chains.push(chain); }); return chains; }, // Find the 'shadow' of a given chain by following the links in the // DOM nodes at its start and end. shadowChain: function(chain) { var shadows = [], next = this.after(chain[0].from), end = chain[chain.length - 1].to; while (true) { shadows.push(next); var nextNode = next.to; if (!nextNode || nextNode == end) break; else next = nextNode.historyAfter || this.before(end); // (The this.before(end) is a hack -- FF sometimes removes // properties from BR nodes, in which case the best we can hope // for is to not break.) } return shadows; }, // Update the DOM tree to contain the lines specified in a given // chain, link this chain into the DOM nodes. applyChain: function(chain) { // Some attempt is made to prevent the cursor from jumping // randomly when an undo or redo happens. It still behaves a bit // strange sometimes. var cursor = select.cursorPos(this.container, false), self = this; // Remove all nodes in the DOM tree between from and to (null for // start/end of container). function removeRange(from, to) { var pos = from ? from.nextSibling : self.container.firstChild; while (pos != to) { var temp = pos.nextSibling; removeElement(pos); pos = temp; } } var start = chain[0].from, end = chain[chain.length - 1].to; // Clear the space where this change has to be made. removeRange(start, end); // Insert the content specified by the chain into the DOM tree. for (var i = 0; i < chain.length; i++) { var line = chain[i]; // The start and end of the space are already correct, but BR // tags inside it have to be put back. if (i > 0) self.container.insertBefore(line.from, end); // Add the text. var node = makePartSpan(fixSpaces(line.text)); self.container.insertBefore(node, end); // See if the cursor was on this line. Put it back, adjusting // for changed line length, if it was. if (cursor && cursor.node == line.from) { var cursordiff = 0; var prev = this.after(line.from); if (prev && i == chain.length - 1) { // Only adjust if the cursor is after the unchanged part of // the line. for (var match = 0; match < cursor.offset && line.text.charAt(match) == prev.text.charAt(match); match++){} if (cursor.offset > match) cursordiff = line.text.length - prev.text.length; } select.setCursorPos(this.container, {node: line.from, offset: Math.max(0, cursor.offset + cursordiff)}); } // Cursor was in removed line, this is last new line. else if (cursor && (i == chain.length - 1) && cursor.node && cursor.node.parentNode != this.container) { select.setCursorPos(this.container, {node: line.from, offset: line.text.length}); } } // Anchor the chain in the DOM tree. this.linkChain(chain); return start; } }; /* A few useful utility functions. */ // Capture a method on an object. function method(obj, name) { return function() {obj[name].apply(obj, arguments);}; } // The value used to signal the end of a sequence in iterators. var StopIteration = {toString: function() {return "StopIteration"}}; // Apply a function to each element in a sequence. function forEach(iter, f) { if (iter.next) { try {while (true) f(iter.next());} catch (e) {if (e != StopIteration) throw e;} } else { for (var i = 0; i < iter.length; i++) f(iter[i]); } } // Map a function over a sequence, producing an array of results. function map(iter, f) { var accum = []; forEach(iter, function(val) {accum.push(f(val));}); return accum; } // Create a predicate function that tests a string againsts a given // regular expression. No longer used but might be used by 3rd party // parsers. function matcher(regexp){ return function(value){return regexp.test(value);}; } // Test whether a DOM node has a certain CSS class. function hasClass(element, className) { var classes = element.className; return classes && new RegExp("(^| )" + className + "($| )").test(classes); } function removeClass(element, className) { element.className = element.className.replace(new RegExp(" " + className + "\\b", "g"), ""); return element; } // Insert a DOM node after another node. function insertAfter(newNode, oldNode) { var parent = oldNode.parentNode; parent.insertBefore(newNode, oldNode.nextSibling); return newNode; } function removeElement(node) { if (node.parentNode) node.parentNode.removeChild(node); } function clearElement(node) { while (node.firstChild) node.removeChild(node.firstChild); } // Check whether a node is contained in another one. function isAncestor(node, child) { while (child = child.parentNode) { if (node == child) return true; } return false; } // The non-breaking space character. var nbsp = "\u00a0"; var matching = {"{": "}", "[": "]", "(": ")", "}": "{", "]": "[", ")": "("}; // Standardize a few unportable event properties. function normalizeEvent(event) { if (!event.stopPropagation) { event.stopPropagation = function() {this.cancelBubble = true;}; event.preventDefault = function() {this.returnValue = false;}; } if (!event.stop) { event.stop = function() { this.stopPropagation(); this.preventDefault(); }; } if (event.type == "keypress") { event.code = (event.charCode == null) ? event.keyCode : event.charCode; event.character = String.fromCharCode(event.code); } return event; } // Portably register event handlers. function addEventHandler(node, type, handler, removeFunc) { function wrapHandler(event) { handler(normalizeEvent(event || window.event)); } if (typeof node.addEventListener == "function") { node.addEventListener(type, wrapHandler, false); if (removeFunc) return function() {node.removeEventListener(type, wrapHandler, false);}; } else { node.attachEvent("on" + type, wrapHandler); if (removeFunc) return function() {node.detachEvent("on" + type, wrapHandler);}; } } function nodeText(node) { return node.textContent || node.innerText || node.nodeValue || ""; } function nodeTop(node) { var top = 0; while (node.offsetParent) { top += node.offsetTop; node = node.offsetParent; } return top; } function isBR(node) { var nn = node.nodeName; return nn == "BR" || nn == "br"; } function isSpan(node) { var nn = node.nodeName; return nn == "SPAN" || nn == "span"; }
JavaScript
/* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed by Yahoo! Inc. under the BSD (revised) open source license @author Dan Vlad Dascalescu <dandv@yahoo-inc.com> Based on parsehtmlmixed.js by Marijn Haverbeke. */ var PHPHTMLMixedParser = Editor.Parser = (function() { var processingInstructions = ["<?php"]; if (!(PHPParser && CSSParser && JSParser && XMLParser)) throw new Error("PHP, CSS, JS, and XML parsers must be loaded for PHP+HTML mixed mode to work."); XMLParser.configure({useHTMLKludges: true}); function parseMixed(stream) { var htmlParser = XMLParser.make(stream), localParser = null, inTag = false, lastAtt = null, phpParserState = null; var iter = {next: top, copy: copy}; function top() { var token = htmlParser.next(); if (token.content == "<") inTag = true; else if (token.style == "xml-tagname" && inTag === true) inTag = token.content.toLowerCase(); else if (token.style == "xml-attname") lastAtt = token.content; else if (token.type == "xml-processing") { // see if this opens a PHP block for (var i = 0; i < processingInstructions.length; i++) if (processingInstructions[i] == token.content) { iter.next = local(PHPParser, "?>"); break; } } else if (token.style == "xml-attribute" && token.content == "\"php\"" && inTag == "script" && lastAtt == "language") inTag = "script/php"; // "xml-processing" tokens are ignored, because they should be handled by a specific local parser else if (token.content == ">") { if (inTag == "script/php") iter.next = local(PHPParser, "</script>"); else if (inTag == "script") iter.next = local(JSParser, "</script"); else if (inTag == "style") iter.next = local(CSSParser, "</style"); lastAtt = null; inTag = false; } return token; } function local(parser, tag) { var baseIndent = htmlParser.indentation(); if (parser == PHPParser && phpParserState) localParser = phpParserState(stream); else localParser = parser.make(stream, baseIndent + indentUnit); return function() { if (stream.lookAhead(tag, false, false, true)) { if (parser == PHPParser) phpParserState = localParser.copy(); localParser = null; iter.next = top; return top(); // pass the ending tag to the enclosing parser } var token = localParser.next(); var lt = token.value.lastIndexOf("<"), sz = Math.min(token.value.length - lt, tag.length); if (lt != -1 && token.value.slice(lt, lt + sz).toLowerCase() == tag.slice(0, sz) && stream.lookAhead(tag.slice(sz), false, false, true)) { stream.push(token.value.slice(lt)); token.value = token.value.slice(0, lt); } if (token.indentation) { var oldIndent = token.indentation; token.indentation = function(chars) { if (chars == "</") return baseIndent; else return oldIndent(chars); } } return token; }; } function copy() { var _html = htmlParser.copy(), _local = localParser && localParser.copy(), _next = iter.next, _inTag = inTag, _lastAtt = lastAtt, _php = phpParserState; return function(_stream) { stream = _stream; htmlParser = _html(_stream); localParser = _local && _local(_stream); phpParserState = _php; iter.next = _next; inTag = _inTag; lastAtt = _lastAtt; return iter; }; } return iter; } return { make: parseMixed, electricChars: "{}/:", configure: function(conf) { if (conf.opening != null) processingInstructions = conf.opening; } }; })();
JavaScript
/* CodeMirror main module (http://codemirror.net/) * * Implements the CodeMirror constructor and prototype, which take care * of initializing the editor frame, and providing the outside interface. */ // The CodeMirrorConfig object is used to specify a default // configuration. If you specify such an object before loading this // file, the values you put into it will override the defaults given // below. You can also assign to it after loading. var CodeMirrorConfig = window.CodeMirrorConfig || {}; var CodeMirror = (function(){ function setDefaults(object, defaults) { for (var option in defaults) { if (!object.hasOwnProperty(option)) object[option] = defaults[option]; } } function forEach(array, action) { for (var i = 0; i < array.length; i++) action(array[i]); } function createHTMLElement(el) { if (document.createElementNS && document.documentElement.namespaceURI !== null) return document.createElementNS("http://www.w3.org/1999/xhtml", el) else return document.createElement(el) } // These default options can be overridden by passing a set of // options to a specific CodeMirror constructor. See manual.html for // their meaning. setDefaults(CodeMirrorConfig, { stylesheet: [], path: "", parserfile: [], basefiles: ["util.js", "stringstream.js", "select.js", "undo.js", "editor.js", "tokenize.js"], iframeClass: null, passDelay: 200, passTime: 50, lineNumberDelay: 200, lineNumberTime: 50, continuousScanning: false, saveFunction: null, onLoad: null, onChange: null, undoDepth: 50, undoDelay: 800, disableSpellcheck: true, textWrapping: true, readOnly: false, width: "", height: "300px", minHeight: 100, onDynamicHeightChange: null, autoMatchParens: false, markParen: null, unmarkParen: null, parserConfig: null, tabMode: "indent", // or "spaces", "default", "shift" enterMode: "indent", // or "keep", "flat" electricChars: true, reindentOnLoad: false, activeTokens: null, onCursorActivity: null, lineNumbers: false, firstLineNumber: 1, onLineNumberClick: null, indentUnit: 2, domain: null, noScriptCaching: false, incrementalLoading: false }); function addLineNumberDiv(container, firstNum) { var nums = createHTMLElement("div"), scroller = createHTMLElement("div"); nums.style.position = "absolute"; nums.style.height = "100%"; if (nums.style.setExpression) { try {nums.style.setExpression("height", "this.previousSibling.offsetHeight + 'px'");} catch(e) {} // Seems to throw 'Not Implemented' on some IE8 versions } nums.style.top = "0px"; nums.style.left = "0px"; nums.style.overflow = "hidden"; container.appendChild(nums); scroller.className = "CodeMirror-line-numbers"; nums.appendChild(scroller); scroller.innerHTML = "<div>" + firstNum + "</div>"; return nums; } function frameHTML(options) { if (typeof options.parserfile == "string") options.parserfile = [options.parserfile]; if (typeof options.basefiles == "string") options.basefiles = [options.basefiles]; if (typeof options.stylesheet == "string") options.stylesheet = [options.stylesheet]; var sp = " spellcheck=\"" + (options.disableSpellcheck ? "false" : "true") + "\""; var html = ["<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html" + sp + "><head>"]; // Hack to work around a bunch of IE8-specific problems. html.push("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/>"); var queryStr = options.noScriptCaching ? "?nocache=" + new Date().getTime().toString(16) : ""; forEach(options.stylesheet, function(file) { html.push("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + file + queryStr + "\"/>"); }); forEach(options.basefiles.concat(options.parserfile), function(file) { if (!/^https?:/.test(file)) file = options.path + file; html.push("<script type=\"text/javascript\" src=\"" + file + queryStr + "\"><" + "/script>"); }); html.push("</head><body style=\"border-width: 0;\" class=\"editbox\"" + sp + "></body></html>"); return html.join(""); } var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent); function CodeMirror(place, options) { // Use passed options, if any, to override defaults. this.options = options = options || {}; setDefaults(options, CodeMirrorConfig); // Backward compatibility for deprecated options. if (options.dumbTabs) options.tabMode = "spaces"; else if (options.normalTab) options.tabMode = "default"; if (options.cursorActivity) options.onCursorActivity = options.cursorActivity; var frame = this.frame = createHTMLElement("iframe"); if (options.iframeClass) frame.className = options.iframeClass; frame.frameBorder = 0; frame.style.border = "0"; frame.style.width = '100%'; frame.style.height = '100%'; // display: block occasionally suppresses some Firefox bugs, so we // always add it, redundant as it sounds. frame.style.display = "block"; var div = this.wrapping = createHTMLElement("div"); div.style.position = "relative"; div.className = "CodeMirror-wrapping"; div.style.width = options.width; div.style.height = (options.height == "dynamic") ? options.minHeight + "px" : options.height; // This is used by Editor.reroutePasteEvent var teHack = this.textareaHack = createHTMLElement("textarea"); div.appendChild(teHack); teHack.style.position = "absolute"; teHack.style.left = "-10000px"; teHack.style.width = "10px"; teHack.tabIndex = 100000; // Link back to this object, so that the editor can fetch options // and add a reference to itself. frame.CodeMirror = this; if (options.domain && internetExplorer) { this.html = frameHTML(options); frame.src = "javascript:(function(){document.open();" + (options.domain ? "document.domain=\"" + options.domain + "\";" : "") + "document.write(window.frameElement.CodeMirror.html);document.close();})()"; } else { frame.src = "javascript:;"; } if (place.appendChild) place.appendChild(div); else place(div); div.appendChild(frame); if (options.lineNumbers) this.lineNumbers = addLineNumberDiv(div, options.firstLineNumber); this.win = frame.contentWindow; if (!options.domain || !internetExplorer) { this.win.document.open(); this.win.document.write(frameHTML(options)); this.win.document.close(); } } CodeMirror.prototype = { init: function() { // Deprecated, but still supported. if (this.options.initCallback) this.options.initCallback(this); if (this.options.onLoad) this.options.onLoad(this); if (this.options.lineNumbers) this.activateLineNumbers(); if (this.options.reindentOnLoad) this.reindent(); if (this.options.height == "dynamic") this.setDynamicHeight(); }, getCode: function() {return this.editor.getCode();}, setCode: function(code) {this.editor.importCode(code);}, selection: function() {this.focusIfIE(); return this.editor.selectedText();}, reindent: function() {this.editor.reindent();}, reindentSelection: function() {this.focusIfIE(); this.editor.reindentSelection(null);}, focusIfIE: function() { // in IE, a lot of selection-related functionality only works when the frame is focused if (this.win.select.ie_selection && document.activeElement != this.frame) this.focus(); }, focus: function() { this.win.focus(); if (this.editor.selectionSnapshot) // IE hack this.win.select.setBookmark(this.win.document.body, this.editor.selectionSnapshot); }, replaceSelection: function(text) { this.focus(); this.editor.replaceSelection(text); return true; }, replaceChars: function(text, start, end) { this.editor.replaceChars(text, start, end); }, getSearchCursor: function(string, fromCursor, caseFold) { return this.editor.getSearchCursor(string, fromCursor, caseFold); }, undo: function() {this.editor.history.undo();}, redo: function() {this.editor.history.redo();}, historySize: function() {return this.editor.history.historySize();}, clearHistory: function() {this.editor.history.clear();}, grabKeys: function(callback, filter) {this.editor.grabKeys(callback, filter);}, ungrabKeys: function() {this.editor.ungrabKeys();}, setParser: function(name, parserConfig) {this.editor.setParser(name, parserConfig);}, setSpellcheck: function(on) {this.win.document.body.spellcheck = on;}, setStylesheet: function(names) { if (typeof names === "string") names = [names]; var activeStylesheets = {}; var matchedNames = {}; var links = this.win.document.getElementsByTagName("link"); // Create hashes of active stylesheets and matched names. // This is O(n^2) but n is expected to be very small. for (var x = 0, link; link = links[x]; x++) { if (link.rel.indexOf("stylesheet") !== -1) { for (var y = 0; y < names.length; y++) { var name = names[y]; if (link.href.substring(link.href.length - name.length) === name) { activeStylesheets[link.href] = true; matchedNames[name] = true; } } } } // Activate the selected stylesheets and disable the rest. for (var x = 0, link; link = links[x]; x++) { if (link.rel.indexOf("stylesheet") !== -1) { link.disabled = !(link.href in activeStylesheets); } } // Create any new stylesheets. for (var y = 0; y < names.length; y++) { var name = names[y]; if (!(name in matchedNames)) { var link = this.win.document.createElement("link"); link.rel = "stylesheet"; link.type = "text/css"; link.href = name; this.win.document.getElementsByTagName('head')[0].appendChild(link); } } }, setTextWrapping: function(on) { if (on == this.options.textWrapping) return; this.win.document.body.style.whiteSpace = on ? "" : "nowrap"; this.options.textWrapping = on; if (this.lineNumbers) { this.setLineNumbers(false); this.setLineNumbers(true); } }, setIndentUnit: function(unit) {this.win.indentUnit = unit;}, setUndoDepth: function(depth) {this.editor.history.maxDepth = depth;}, setTabMode: function(mode) {this.options.tabMode = mode;}, setEnterMode: function(mode) {this.options.enterMode = mode;}, setLineNumbers: function(on) { if (on && !this.lineNumbers) { this.lineNumbers = addLineNumberDiv(this.wrapping,this.options.firstLineNumber); this.activateLineNumbers(); } else if (!on && this.lineNumbers) { this.wrapping.removeChild(this.lineNumbers); this.wrapping.style.paddingLeft = ""; this.lineNumbers = null; } }, cursorPosition: function(start) {this.focusIfIE(); return this.editor.cursorPosition(start);}, firstLine: function() {return this.editor.firstLine();}, lastLine: function() {return this.editor.lastLine();}, nextLine: function(line) {return this.editor.nextLine(line);}, prevLine: function(line) {return this.editor.prevLine(line);}, lineContent: function(line) {return this.editor.lineContent(line);}, setLineContent: function(line, content) {this.editor.setLineContent(line, content);}, removeLine: function(line){this.editor.removeLine(line);}, insertIntoLine: function(line, position, content) {this.editor.insertIntoLine(line, position, content);}, selectLines: function(startLine, startOffset, endLine, endOffset) { this.win.focus(); this.editor.selectLines(startLine, startOffset, endLine, endOffset); }, nthLine: function(n) { var line = this.firstLine(); for (; n > 1 && line !== false; n--) line = this.nextLine(line); return line; }, lineNumber: function(line) { var num = 0; while (line !== false) { num++; line = this.prevLine(line); } return num; }, jumpToLine: function(line) { if (typeof line == "number") line = this.nthLine(line); this.selectLines(line, 0); this.win.focus(); }, currentLine: function() { // Deprecated, but still there for backward compatibility return this.lineNumber(this.cursorLine()); }, cursorLine: function() { return this.cursorPosition().line; }, cursorCoords: function(start) {return this.editor.cursorCoords(start);}, activateLineNumbers: function() { var frame = this.frame, win = frame.contentWindow, doc = win.document, body = doc.body, nums = this.lineNumbers, scroller = nums.firstChild, self = this; var barWidth = null; nums.onclick = function(e) { var handler = self.options.onLineNumberClick; if (handler) { var div = (e || window.event).target || (e || window.event).srcElement; var num = div == nums ? NaN : Number(div.innerHTML); if (!isNaN(num)) handler(num, div); } }; function sizeBar() { if (frame.offsetWidth == 0) return; for (var root = frame; root.parentNode; root = root.parentNode){} if (!nums.parentNode || root != document || !win.Editor) { // Clear event handlers (their nodes might already be collected, so try/catch) try{clear();}catch(e){} clearInterval(sizeInterval); return; } if (nums.offsetWidth != barWidth) { barWidth = nums.offsetWidth; frame.parentNode.style.paddingLeft = barWidth + "px"; } } function doScroll() { nums.scrollTop = body.scrollTop || doc.documentElement.scrollTop || 0; } // Cleanup function, registered by nonWrapping and wrapping. var clear = function(){}; sizeBar(); var sizeInterval = setInterval(sizeBar, 500); function ensureEnoughLineNumbers(fill) { var lineHeight = scroller.firstChild.offsetHeight; if (lineHeight == 0) return; var targetHeight = 50 + Math.max(body.offsetHeight, Math.max(frame.offsetHeight, body.scrollHeight || 0)), lastNumber = Math.ceil(targetHeight / lineHeight); for (var i = scroller.childNodes.length; i <= lastNumber; i++) { var div = createHTMLElement("div"); div.appendChild(document.createTextNode(fill ? String(i + self.options.firstLineNumber) : "\u00a0")); scroller.appendChild(div); } } function nonWrapping() { function update() { ensureEnoughLineNumbers(true); doScroll(); } self.updateNumbers = update; var onScroll = win.addEventHandler(win, "scroll", doScroll, true), onResize = win.addEventHandler(win, "resize", update, true); clear = function(){ onScroll(); onResize(); if (self.updateNumbers == update) self.updateNumbers = null; }; update(); } function wrapping() { var node, lineNum, next, pos, changes = [], styleNums = self.options.styleNumbers; function setNum(n, node) { // Does not typically happen (but can, if you mess with the // document during the numbering) if (!lineNum) lineNum = scroller.appendChild(createHTMLElement("div")); if (styleNums) styleNums(lineNum, node, n); // Changes are accumulated, so that the document layout // doesn't have to be recomputed during the pass changes.push(lineNum); changes.push(n); pos = lineNum.offsetHeight + lineNum.offsetTop; lineNum = lineNum.nextSibling; } function commitChanges() { for (var i = 0; i < changes.length; i += 2) changes[i].innerHTML = changes[i + 1]; changes = []; } function work() { if (!scroller.parentNode || scroller.parentNode != self.lineNumbers) return; var endTime = new Date().getTime() + self.options.lineNumberTime; while (node) { setNum(next++, node.previousSibling); for (; node && !win.isBR(node); node = node.nextSibling) { var bott = node.offsetTop + node.offsetHeight; while (scroller.offsetHeight && bott - 3 > pos) { var oldPos = pos; setNum("&nbsp;"); if (pos <= oldPos) break; } } if (node) node = node.nextSibling; if (new Date().getTime() > endTime) { commitChanges(); pending = setTimeout(work, self.options.lineNumberDelay); return; } } while (lineNum) setNum(next++); commitChanges(); doScroll(); } function start(firstTime) { doScroll(); ensureEnoughLineNumbers(firstTime); node = body.firstChild; lineNum = scroller.firstChild; pos = 0; next = self.options.firstLineNumber; work(); } start(true); var pending = null; function update() { if (pending) clearTimeout(pending); if (self.editor.allClean()) start(); else pending = setTimeout(update, 200); } self.updateNumbers = update; var onScroll = win.addEventHandler(win, "scroll", doScroll, true), onResize = win.addEventHandler(win, "resize", update, true); clear = function(){ if (pending) clearTimeout(pending); if (self.updateNumbers == update) self.updateNumbers = null; onScroll(); onResize(); }; } (this.options.textWrapping || this.options.styleNumbers ? wrapping : nonWrapping)(); }, setDynamicHeight: function() { var self = this, activity = self.options.onCursorActivity, win = self.win, body = win.document.body, lineHeight = null, timeout = null, vmargin = 2 * self.frame.offsetTop; body.style.overflowY = "hidden"; win.document.documentElement.style.overflowY = "hidden"; this.frame.scrolling = "no"; function updateHeight() { var trailingLines = 0, node = body.lastChild, computedHeight; while (node && win.isBR(node)) { if (!node.hackBR) trailingLines++; node = node.previousSibling; } if (node) { lineHeight = node.offsetHeight; computedHeight = node.offsetTop + (1 + trailingLines) * lineHeight; } else if (lineHeight) { computedHeight = trailingLines * lineHeight; } if (computedHeight) { if (self.options.onDynamicHeightChange) computedHeight = self.options.onDynamicHeightChange(computedHeight); if (computedHeight) self.wrapping.style.height = Math.max(vmargin + computedHeight, self.options.minHeight) + "px"; } } setTimeout(updateHeight, 300); self.options.onCursorActivity = function(x) { if (activity) activity(x); clearTimeout(timeout); timeout = setTimeout(updateHeight, 100); }; } }; CodeMirror.InvalidLineHandle = {toString: function(){return "CodeMirror.InvalidLineHandle";}}; CodeMirror.replace = function(element) { if (typeof element == "string") element = document.getElementById(element); return function(newElement) { element.parentNode.replaceChild(newElement, element); }; }; CodeMirror.fromTextArea = function(area, options) { if (typeof area == "string") area = document.getElementById(area); options = options || {}; if (area.style.width && options.width == null) options.width = area.style.width; if (area.style.height && options.height == null) options.height = area.style.height; if (options.content == null) options.content = area.value; function updateField() { area.value = mirror.getCode(); } if (area.form) { if (typeof area.form.addEventListener == "function") area.form.addEventListener("submit", updateField, false); else area.form.attachEvent("onsubmit", updateField); if (typeof area.form.submit == "function") { var realSubmit = area.form.submit; function wrapSubmit() { updateField(); // Can't use realSubmit.apply because IE6 is too stupid area.form.submit = realSubmit; area.form.submit(); area.form.submit = wrapSubmit; } area.form.submit = wrapSubmit; } } function insert(frame) { if (area.nextSibling) area.parentNode.insertBefore(frame, area.nextSibling); else area.parentNode.appendChild(frame); } area.style.display = "none"; var mirror = new CodeMirror(insert, options); mirror.save = updateField; mirror.toTextArea = function() { updateField(); area.parentNode.removeChild(mirror.wrapping); area.style.display = ""; if (area.form) { if (typeof area.form.submit == "function") area.form.submit = realSubmit; if (typeof area.form.removeEventListener == "function") area.form.removeEventListener("submit", updateField, false); else area.form.detachEvent("onsubmit", updateField); } }; return mirror; }; CodeMirror.isProbablySupported = function() { // This is rather awful, but can be useful. var match; if (window.opera) return Number(window.opera.version()) >= 9.52; else if (/Apple Computer, Inc/.test(navigator.vendor) && (match = navigator.userAgent.match(/Version\/(\d+(?:\.\d+)?)\./))) return Number(match[1]) >= 3; else if (document.selection && window.ActiveXObject && (match = navigator.userAgent.match(/MSIE (\d+(?:\.\d*)?)\b/))) return Number(match[1]) >= 6; else if (match = navigator.userAgent.match(/gecko\/(\d{8})/i)) return Number(match[1]) >= 20050901; else if (match = navigator.userAgent.match(/AppleWebKit\/(\d+)/)) return Number(match[1]) >= 525; else return null; }; return CodeMirror; })();
JavaScript
// Minimal framing needed to use CodeMirror-style parsers to highlight // code. Load this along with tokenize.js, stringstream.js, and your // parser. Then call highlightText, passing a string as the first // argument, and as the second argument either a callback function // that will be called with an array of SPAN nodes for every line in // the code, or a DOM node to which to append these spans, and // optionally (not needed if you only loaded one parser) a parser // object. // Stuff from util.js that the parsers are using. var StopIteration = {toString: function() {return "StopIteration"}}; var Editor = {}; var indentUnit = 2; (function(){ function normaliseString(string) { var tab = ""; for (var i = 0; i < indentUnit; i++) tab += " "; string = string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n"); var pos = 0, parts = [], lines = string.split("\n"); for (var line = 0; line < lines.length; line++) { if (line != 0) parts.push("\n"); parts.push(lines[line]); } return { next: function() { if (pos < parts.length) return parts[pos++]; else throw StopIteration; } }; } window.highlightText = function(string, callback, parser) { parser = (parser || Editor.Parser).make(stringStream(normaliseString(string))); var line = []; if (callback.nodeType == 1) { var node = callback; callback = function(line) { for (var i = 0; i < line.length; i++) node.appendChild(line[i]); node.appendChild(document.createElement("br")); }; } try { while (true) { var token = parser.next(); if (token.value == "\n") { callback(line); line = []; } else { var span = document.createElement("span"); span.className = token.style; span.appendChild(document.createTextNode(token.value)); line.push(span); } } } catch (e) { if (e != StopIteration) throw e; } if (line.length) callback(line); } })();
JavaScript
/* The Editor object manages the content of the editable frame. It * catches events, colours nodes, and indents lines. This file also * holds some functions for transforming arbitrary DOM structures into * plain sequences of <span> and <br> elements */ var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent); var webkit = /AppleWebKit/.test(navigator.userAgent); var safari = /Apple Computer, Inc/.test(navigator.vendor); var gecko = navigator.userAgent.match(/gecko\/(\d{8})/i); if (gecko) gecko = Number(gecko[1]); var mac = /Mac/.test(navigator.platform); // TODO this is related to the backspace-at-end-of-line bug. Remove // this if Opera gets their act together, make the version check more // broad if they don't. var brokenOpera = window.opera && /Version\/10.[56]/.test(navigator.userAgent); // TODO remove this once WebKit 533 becomes less common. var slowWebkit = /AppleWebKit\/533/.test(navigator.userAgent); // Make sure a string does not contain two consecutive 'collapseable' // whitespace characters. function makeWhiteSpace(n) { var buffer = [], nb = true; for (; n > 0; n--) { buffer.push((nb || n == 1) ? nbsp : " "); nb ^= true; } return buffer.join(""); } // Create a set of white-space characters that will not be collapsed // by the browser, but will not break text-wrapping either. function fixSpaces(string) { if (string.charAt(0) == " ") string = nbsp + string.slice(1); return string.replace(/\t/g, function() {return makeWhiteSpace(indentUnit);}) .replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);}); } function cleanText(text) { return text.replace(/\u00a0/g, " ").replace(/\u200b/g, ""); } // Create a SPAN node with the expected properties for document part // spans. function makePartSpan(value) { var text = value; if (value.nodeType == 3) text = value.nodeValue; else value = document.createTextNode(text); var span = document.createElement("span"); span.isPart = true; span.appendChild(value); span.currentText = text; return span; } function alwaysZero() {return 0;} // On webkit, when the last BR of the document does not have text // behind it, the cursor can not be put on the line after it. This // makes pressing enter at the end of the document occasionally do // nothing (or at least seem to do nothing). To work around it, this // function makes sure the document ends with a span containing a // zero-width space character. The traverseDOM iterator filters such // character out again, so that the parsers won't see them. This // function is called from a few strategic places to make sure the // zwsp is restored after the highlighting process eats it. var webkitLastLineHack = webkit ? function(container) { var last = container.lastChild; if (!last || !last.hackBR) { var br = document.createElement("br"); br.hackBR = true; container.appendChild(br); } } : function() {}; function asEditorLines(string) { var tab = makeWhiteSpace(indentUnit); return map(string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").split("\n"), fixSpaces); } var Editor = (function(){ // The HTML elements whose content should be suffixed by a newline // when converting them to flat text. var newlineElements = {"P": true, "DIV": true, "LI": true}; // Helper function for traverseDOM. Flattens an arbitrary DOM node // into an array of textnodes and <br> tags. function simplifyDOM(root, atEnd) { var result = []; var leaving = true; function simplifyNode(node, top) { if (node.nodeType == 3) { var text = node.nodeValue = fixSpaces(node.nodeValue.replace(/[\r\u200b]/g, "").replace(/\n/g, " ")); if (text.length) leaving = false; result.push(node); } else if (isBR(node) && node.childNodes.length == 0) { leaving = true; result.push(node); } else { for (var n = node.firstChild; n; n = n.nextSibling) simplifyNode(n); if (!leaving && newlineElements.hasOwnProperty(node.nodeName.toUpperCase())) { leaving = true; if (!atEnd || !top) result.push(document.createElement("br")); } } } simplifyNode(root, true); return result; } // Creates a MochiKit-style iterator that goes over a series of DOM // nodes. The values it yields are strings, the textual content of // the nodes. It makes sure that all nodes up to and including the // one whose text is being yielded have been 'normalized' to be just // <span> and <br> elements. function traverseDOM(start){ var nodeQueue = []; // Create a function that can be used to insert nodes after the // one given as argument. function pointAt(node){ var parent = node.parentNode; var next = node.nextSibling; return function(newnode) { parent.insertBefore(newnode, next); }; } var point = null; // This an Opera-specific hack -- always insert an empty span // between two BRs, because Opera's cursor code gets terribly // confused when the cursor is between two BRs. var afterBR = true; // Insert a normalized node at the current point. If it is a text // node, wrap it in a <span>, and give that span a currentText // property -- this is used to cache the nodeValue, because // directly accessing nodeValue is horribly slow on some browsers. // The dirty property is used by the highlighter to determine // which parts of the document have to be re-highlighted. function insertPart(part){ var text = "\n"; if (part.nodeType == 3) { select.snapshotChanged(); part = makePartSpan(part); text = part.currentText; afterBR = false; } else { if (afterBR && window.opera) point(makePartSpan("")); afterBR = true; } part.dirty = true; nodeQueue.push(part); point(part); return text; } // Extract the text and newlines from a DOM node, insert them into // the document, and return the textual content. Used to replace // non-normalized nodes. function writeNode(node, end) { var simplified = simplifyDOM(node, end); for (var i = 0; i < simplified.length; i++) simplified[i] = insertPart(simplified[i]); return simplified.join(""); } // Check whether a node is a normalized <span> element. function partNode(node){ if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { var text = node.firstChild.nodeValue; node.dirty = node.dirty || text != node.currentText; node.currentText = text; return !/[\n\t\r]/.test(node.currentText); } return false; } // Advance to next node, return string for current node. function next() { if (!start) throw StopIteration; var node = start; start = node.nextSibling; if (partNode(node)){ nodeQueue.push(node); afterBR = false; return node.currentText; } else if (isBR(node)) { if (afterBR && window.opera) node.parentNode.insertBefore(makePartSpan(""), node); nodeQueue.push(node); afterBR = true; return "\n"; } else { var end = !node.nextSibling; point = pointAt(node); removeElement(node); return writeNode(node, end); } } // MochiKit iterators are objects with a next function that // returns the next value or throws StopIteration when there are // no more values. return {next: next, nodes: nodeQueue}; } // Determine the text size of a processed node. function nodeSize(node) { return isBR(node) ? 1 : node.currentText.length; } // Search backwards through the top-level nodes until the next BR or // the start of the frame. function startOfLine(node) { while (node && !isBR(node)) node = node.previousSibling; return node; } function endOfLine(node, container) { if (!node) node = container.firstChild; else if (isBR(node)) node = node.nextSibling; while (node && !isBR(node)) node = node.nextSibling; return node; } function time() {return new Date().getTime();} // Client interface for searching the content of the editor. Create // these by calling CodeMirror.getSearchCursor. To use, call // findNext on the resulting object -- this returns a boolean // indicating whether anything was found, and can be called again to // skip to the next find. Use the select and replace methods to // actually do something with the found locations. function SearchCursor(editor, pattern, from, caseFold) { this.editor = editor; this.history = editor.history; this.history.commit(); this.valid = !!pattern; this.atOccurrence = false; if (caseFold == undefined) caseFold = typeof pattern == "string" && pattern == pattern.toLowerCase(); function getText(node){ var line = cleanText(editor.history.textAfter(node)); return (caseFold ? line.toLowerCase() : line); } var topPos = {node: null, offset: 0}, self = this; if (from && typeof from == "object" && typeof from.character == "number") { editor.checkLine(from.line); var pos = {node: from.line, offset: from.character}; this.pos = {from: pos, to: pos}; } else if (from) { this.pos = {from: select.cursorPos(editor.container, true) || topPos, to: select.cursorPos(editor.container, false) || topPos}; } else { this.pos = {from: topPos, to: topPos}; } if (typeof pattern != "string") { // Regexp match this.matches = function(reverse, node, offset) { if (reverse) { var line = getText(node).slice(0, offset), match = line.match(pattern), start = 0; while (match) { var ind = line.indexOf(match[0]); start += ind; line = line.slice(ind + 1); var newmatch = line.match(pattern); if (newmatch) match = newmatch; else break; } } else { var line = getText(node).slice(offset), match = line.match(pattern), start = match && offset + line.indexOf(match[0]); } if (match) { self.currentMatch = match; return {from: {node: node, offset: start}, to: {node: node, offset: start + match[0].length}}; } }; return; } if (caseFold) pattern = pattern.toLowerCase(); // Create a matcher function based on the kind of string we have. var target = pattern.split("\n"); this.matches = (target.length == 1) ? // For one-line strings, searching can be done simply by calling // indexOf or lastIndexOf on the current line. function(reverse, node, offset) { var line = getText(node), len = pattern.length, match; if (reverse ? (offset >= len && (match = line.lastIndexOf(pattern, offset - len)) != -1) : (match = line.indexOf(pattern, offset)) != -1) return {from: {node: node, offset: match}, to: {node: node, offset: match + len}}; } : // Multi-line strings require internal iteration over lines, and // some clunky checks to make sure the first match ends at the // end of the line and the last match starts at the start. function(reverse, node, offset) { var idx = (reverse ? target.length - 1 : 0), match = target[idx], line = getText(node); var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match)); if (reverse ? offsetA >= offset || offsetA != match.length : offsetA <= offset || offsetA != line.length - match.length) return; var pos = node; while (true) { if (reverse && !pos) return; pos = (reverse ? this.history.nodeBefore(pos) : this.history.nodeAfter(pos) ); if (!reverse && !pos) return; line = getText(pos); match = target[reverse ? --idx : ++idx]; if (idx > 0 && idx < target.length - 1) { if (line != match) return; else continue; } var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length); if (reverse ? offsetB != line.length - match.length : offsetB != match.length) return; return {from: {node: reverse ? pos : node, offset: reverse ? offsetB : offsetA}, to: {node: reverse ? node : pos, offset: reverse ? offsetA : offsetB}}; } }; } SearchCursor.prototype = { findNext: function() {return this.find(false);}, findPrevious: function() {return this.find(true);}, find: function(reverse) { if (!this.valid) return false; var self = this, pos = reverse ? this.pos.from : this.pos.to, node = pos.node, offset = pos.offset; // Reset the cursor if the current line is no longer in the DOM tree. if (node && !node.parentNode) { node = null; offset = 0; } function savePosAndFail() { var pos = {node: node, offset: offset}; self.pos = {from: pos, to: pos}; self.atOccurrence = false; return false; } while (true) { if (this.pos = this.matches(reverse, node, offset)) { this.atOccurrence = true; return true; } if (reverse) { if (!node) return savePosAndFail(); node = this.history.nodeBefore(node); offset = this.history.textAfter(node).length; } else { var next = this.history.nodeAfter(node); if (!next) { offset = this.history.textAfter(node).length; return savePosAndFail(); } node = next; offset = 0; } } }, select: function() { if (this.atOccurrence) { select.setCursorPos(this.editor.container, this.pos.from, this.pos.to); select.scrollToCursor(this.editor.container); } }, replace: function(string) { if (this.atOccurrence) { var fragments = this.currentMatch; if (fragments) string = string.replace(/\\(\d)/, function(m, i){return fragments[i];}); var end = this.editor.replaceRange(this.pos.from, this.pos.to, string); this.pos.to = end; this.atOccurrence = false; } }, position: function() { if (this.atOccurrence) return {line: this.pos.from.node, character: this.pos.from.offset}; } }; // The Editor object is the main inside-the-iframe interface. function Editor(options) { this.options = options; window.indentUnit = options.indentUnit; var container = this.container = document.body; this.history = new UndoHistory(container, options.undoDepth, options.undoDelay, this); var self = this; if (!Editor.Parser) throw "No parser loaded."; if (options.parserConfig && Editor.Parser.configure) Editor.Parser.configure(options.parserConfig); if (!options.readOnly && !internetExplorer) select.setCursorPos(container, {node: null, offset: 0}); this.dirty = []; this.importCode(options.content || ""); this.history.onChange = options.onChange; if (!options.readOnly) { if (options.continuousScanning !== false) { this.scanner = this.documentScanner(options.passTime); this.delayScanning(); } function setEditable() { // Use contentEditable instead of designMode on IE, since designMode frames // can not run any scripts. It would be nice if we could use contentEditable // everywhere, but it is significantly flakier than designMode on every // single non-IE browser. if (document.body.contentEditable != undefined && internetExplorer) document.body.contentEditable = "true"; else document.designMode = "on"; // Work around issue where you have to click on the actual // body of the document to focus it in IE, making focusing // hard when the document is small. if (internetExplorer && options.height != "dynamic") document.body.style.minHeight = ( window.frameElement.clientHeight - 2 * document.body.offsetTop - 5) + "px"; document.documentElement.style.borderWidth = "0"; if (!options.textWrapping) container.style.whiteSpace = "nowrap"; } // If setting the frame editable fails, try again when the user // focus it (happens when the frame is not visible on // initialisation, in Firefox). try { setEditable(); } catch(e) { var focusEvent = addEventHandler(document, "focus", function() { focusEvent(); setEditable(); }, true); } addEventHandler(document, "keydown", method(this, "keyDown")); addEventHandler(document, "keypress", method(this, "keyPress")); addEventHandler(document, "keyup", method(this, "keyUp")); function cursorActivity() {self.cursorActivity(false);} addEventHandler(internetExplorer ? document.body : window, "mouseup", cursorActivity); addEventHandler(document.body, "cut", cursorActivity); // workaround for a gecko bug [?] where going forward and then // back again breaks designmode (no more cursor) if (gecko) addEventHandler(window, "pagehide", function(){self.unloaded = true;}); addEventHandler(document.body, "paste", function(event) { cursorActivity(); var text = null; try { var clipboardData = event.clipboardData || window.clipboardData; if (clipboardData) text = clipboardData.getData('Text'); } catch(e) {} if (text !== null) { event.stop(); self.replaceSelection(text); select.scrollToCursor(self.container); } }); if (this.options.autoMatchParens) addEventHandler(document.body, "click", method(this, "scheduleParenHighlight")); } else if (!options.textWrapping) { container.style.whiteSpace = "nowrap"; } } function isSafeKey(code) { return (code >= 16 && code <= 18) || // shift, control, alt (code >= 33 && code <= 40); // arrows, home, end } Editor.prototype = { // Import a piece of code into the editor. importCode: function(code) { var lines = asEditorLines(code), chunk = 1000; if (!this.options.incrementalLoading || lines.length < chunk) { this.history.push(null, null, lines); this.history.reset(); } else { var cur = 0, self = this; function addChunk() { var chunklines = lines.slice(cur, cur + chunk); chunklines.push(""); self.history.push(self.history.nodeBefore(null), null, chunklines); self.history.reset(); cur += chunk; if (cur < lines.length) parent.setTimeout(addChunk, 1000); } addChunk(); } }, // Extract the code from the editor. getCode: function() { if (!this.container.firstChild) return ""; var accum = []; select.markSelection(); forEach(traverseDOM(this.container.firstChild), method(accum, "push")); select.selectMarked(); // On webkit, don't count last (empty) line if the webkitLastLineHack BR is present if (webkit && this.container.lastChild.hackBR) accum.pop(); webkitLastLineHack(this.container); return cleanText(accum.join("")); }, checkLine: function(node) { if (node === false || !(node == null || node.parentNode == this.container || node.hackBR)) throw parent.CodeMirror.InvalidLineHandle; }, cursorPosition: function(start) { if (start == null) start = true; var pos = select.cursorPos(this.container, start); if (pos) return {line: pos.node, character: pos.offset}; else return {line: null, character: 0}; }, firstLine: function() { return null; }, lastLine: function() { var last = this.container.lastChild; if (last) last = startOfLine(last); if (last && last.hackBR) last = startOfLine(last.previousSibling); return last; }, nextLine: function(line) { this.checkLine(line); var end = endOfLine(line, this.container); if (!end || end.hackBR) return false; else return end; }, prevLine: function(line) { this.checkLine(line); if (line == null) return false; return startOfLine(line.previousSibling); }, visibleLineCount: function() { var line = this.container.firstChild; while (line && isBR(line)) line = line.nextSibling; // BR heights are unreliable if (!line) return false; var innerHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight); return Math.floor(innerHeight / line.offsetHeight); }, selectLines: function(startLine, startOffset, endLine, endOffset) { this.checkLine(startLine); var start = {node: startLine, offset: startOffset}, end = null; if (endOffset !== undefined) { this.checkLine(endLine); end = {node: endLine, offset: endOffset}; } select.setCursorPos(this.container, start, end); select.scrollToCursor(this.container); }, lineContent: function(line) { var accum = []; for (line = line ? line.nextSibling : this.container.firstChild; line && !isBR(line); line = line.nextSibling) accum.push(nodeText(line)); return cleanText(accum.join("")); }, setLineContent: function(line, content) { this.history.commit(); this.replaceRange({node: line, offset: 0}, {node: line, offset: this.history.textAfter(line).length}, content); this.addDirtyNode(line); this.scheduleHighlight(); }, removeLine: function(line) { var node = line ? line.nextSibling : this.container.firstChild; while (node) { var next = node.nextSibling; removeElement(node); if (isBR(node)) break; node = next; } this.addDirtyNode(line); this.scheduleHighlight(); }, insertIntoLine: function(line, position, content) { var before = null; if (position == "end") { before = endOfLine(line, this.container); } else { for (var cur = line ? line.nextSibling : this.container.firstChild; cur; cur = cur.nextSibling) { if (position == 0) { before = cur; break; } var text = nodeText(cur); if (text.length > position) { before = cur.nextSibling; content = text.slice(0, position) + content + text.slice(position); removeElement(cur); break; } position -= text.length; } } var lines = asEditorLines(content); for (var i = 0; i < lines.length; i++) { if (i > 0) this.container.insertBefore(document.createElement("BR"), before); this.container.insertBefore(makePartSpan(lines[i]), before); } this.addDirtyNode(line); this.scheduleHighlight(); }, // Retrieve the selected text. selectedText: function() { var h = this.history; h.commit(); var start = select.cursorPos(this.container, true), end = select.cursorPos(this.container, false); if (!start || !end) return ""; if (start.node == end.node) return h.textAfter(start.node).slice(start.offset, end.offset); var text = [h.textAfter(start.node).slice(start.offset)]; for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos)) text.push(h.textAfter(pos)); text.push(h.textAfter(end.node).slice(0, end.offset)); return cleanText(text.join("\n")); }, // Replace the selection with another piece of text. replaceSelection: function(text) { this.history.commit(); var start = select.cursorPos(this.container, true), end = select.cursorPos(this.container, false); if (!start || !end) return; end = this.replaceRange(start, end, text); select.setCursorPos(this.container, end); webkitLastLineHack(this.container); }, cursorCoords: function(start, internal) { var sel = select.cursorPos(this.container, start); if (!sel) return null; var off = sel.offset, node = sel.node, self = this; function measureFromNode(node, xOffset) { var y = -(document.body.scrollTop || document.documentElement.scrollTop || 0), x = -(document.body.scrollLeft || document.documentElement.scrollLeft || 0) + xOffset; forEach([node, internal ? null : window.frameElement], function(n) { while (n) {x += n.offsetLeft; y += n.offsetTop;n = n.offsetParent;} }); return {x: x, y: y, yBot: y + node.offsetHeight}; } function withTempNode(text, f) { var node = document.createElement("SPAN"); node.appendChild(document.createTextNode(text)); try {return f(node);} finally {if (node.parentNode) node.parentNode.removeChild(node);} } while (off) { node = node ? node.nextSibling : this.container.firstChild; var txt = nodeText(node); if (off < txt.length) return withTempNode(txt.substr(0, off), function(tmp) { tmp.style.position = "absolute"; tmp.style.visibility = "hidden"; tmp.className = node.className; self.container.appendChild(tmp); return measureFromNode(node, tmp.offsetWidth); }); off -= txt.length; } if (node && isSpan(node)) return measureFromNode(node, node.offsetWidth); else if (node && node.nextSibling && isSpan(node.nextSibling)) return measureFromNode(node.nextSibling, 0); else return withTempNode("\u200b", function(tmp) { if (node) node.parentNode.insertBefore(tmp, node.nextSibling); else self.container.insertBefore(tmp, self.container.firstChild); return measureFromNode(tmp, 0); }); }, reroutePasteEvent: function() { if (this.capturingPaste || window.opera || (gecko && gecko >= 20101026)) return; this.capturingPaste = true; var te = window.frameElement.CodeMirror.textareaHack; var coords = this.cursorCoords(true, true); te.style.top = coords.y + "px"; if (internetExplorer) { var snapshot = select.getBookmark(this.container); if (snapshot) this.selectionSnapshot = snapshot; } parent.focus(); te.value = ""; te.focus(); var self = this; parent.setTimeout(function() { self.capturingPaste = false; window.focus(); if (self.selectionSnapshot) // IE hack window.select.setBookmark(self.container, self.selectionSnapshot); var text = te.value; if (text) { self.replaceSelection(text); select.scrollToCursor(self.container); } }, 10); }, replaceRange: function(from, to, text) { var lines = asEditorLines(text); lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0]; var lastLine = lines[lines.length - 1]; lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset); var end = this.history.nodeAfter(to.node); this.history.push(from.node, end, lines); return {node: this.history.nodeBefore(end), offset: lastLine.length}; }, getSearchCursor: function(string, fromCursor, caseFold) { return new SearchCursor(this, string, fromCursor, caseFold); }, // Re-indent the whole buffer reindent: function() { if (this.container.firstChild) this.indentRegion(null, this.container.lastChild); }, reindentSelection: function(direction) { if (!select.somethingSelected()) { this.indentAtCursor(direction); } else { var start = select.selectionTopNode(this.container, true), end = select.selectionTopNode(this.container, false); if (start === false || end === false) return; this.indentRegion(start, end, direction, true); } }, grabKeys: function(eventHandler, filter) { this.frozen = eventHandler; this.keyFilter = filter; }, ungrabKeys: function() { this.frozen = "leave"; }, setParser: function(name, parserConfig) { Editor.Parser = window[name]; parserConfig = parserConfig || this.options.parserConfig; if (parserConfig && Editor.Parser.configure) Editor.Parser.configure(parserConfig); if (this.container.firstChild) { forEach(this.container.childNodes, function(n) { if (n.nodeType != 3) n.dirty = true; }); this.addDirtyNode(this.firstChild); this.scheduleHighlight(); } }, // Intercept enter and tab, and assign their new functions. keyDown: function(event) { if (this.frozen == "leave") {this.frozen = null; this.keyFilter = null;} if (this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode, event))) { event.stop(); this.frozen(event); return; } var code = event.keyCode; // Don't scan when the user is typing. this.delayScanning(); // Schedule a paren-highlight event, if configured. if (this.options.autoMatchParens) this.scheduleParenHighlight(); // The various checks for !altKey are there because AltGr sets both // ctrlKey and altKey to true, and should not be recognised as // Control. if (code == 13) { // enter if (event.ctrlKey && !event.altKey) { this.reparseBuffer(); } else { select.insertNewlineAtCursor(); var mode = this.options.enterMode; if (mode != "flat") this.indentAtCursor(mode == "keep" ? "keep" : undefined); select.scrollToCursor(this.container); } event.stop(); } else if (code == 9 && this.options.tabMode != "default" && !event.ctrlKey) { // tab this.handleTab(!event.shiftKey); event.stop(); } else if (code == 32 && event.shiftKey && this.options.tabMode == "default") { // space this.handleTab(true); event.stop(); } else if (code == 36 && !event.shiftKey && !event.ctrlKey) { // home if (this.home()) event.stop(); } else if (code == 35 && !event.shiftKey && !event.ctrlKey) { // end if (this.end()) event.stop(); } // Only in Firefox is the default behavior for PgUp/PgDn correct. else if (code == 33 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgUp if (this.pageUp()) event.stop(); } else if (code == 34 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgDn if (this.pageDown()) event.stop(); } else if ((code == 219 || code == 221) && event.ctrlKey && !event.altKey) { // [, ] this.highlightParens(event.shiftKey, true); event.stop(); } else if (event.metaKey && !event.shiftKey && (code == 37 || code == 39)) { // Meta-left/right var cursor = select.selectionTopNode(this.container); if (cursor === false || !this.container.firstChild) return; if (code == 37) select.focusAfterNode(startOfLine(cursor), this.container); else { var end = endOfLine(cursor, this.container); select.focusAfterNode(end ? end.previousSibling : this.container.lastChild, this.container); } event.stop(); } else if ((event.ctrlKey || event.metaKey) && !event.altKey) { if ((event.shiftKey && code == 90) || code == 89) { // shift-Z, Y select.scrollToNode(this.history.redo()); event.stop(); } else if (code == 90 || (safari && code == 8)) { // Z, backspace select.scrollToNode(this.history.undo()); event.stop(); } else if (code == 83 && this.options.saveFunction) { // S this.options.saveFunction(); event.stop(); } else if (code == 86 && !mac) { // V this.reroutePasteEvent(); } } }, // Check for characters that should re-indent the current line, // and prevent Opera from handling enter and tab anyway. keyPress: function(event) { var electric = this.options.electricChars && Editor.Parser.electricChars, self = this; // Hack for Opera, and Firefox on OS X, in which stopping a // keydown event does not prevent the associated keypress event // from happening, so we have to cancel enter and tab again // here. if ((this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode || event.code, event))) || event.code == 13 || (event.code == 9 && this.options.tabMode != "default") || (event.code == 32 && event.shiftKey && this.options.tabMode == "default")) event.stop(); else if (mac && (event.ctrlKey || event.metaKey) && event.character == "v") { this.reroutePasteEvent(); } else if (electric && electric.indexOf(event.character) != -1) parent.setTimeout(function(){self.indentAtCursor(null);}, 0); // Work around a bug where pressing backspace at the end of a // line, or delete at the start, often causes the cursor to jump // to the start of the line in Opera 10.60. else if (brokenOpera) { if (event.code == 8) { // backspace var sel = select.selectionTopNode(this.container), self = this, next = sel ? sel.nextSibling : this.container.firstChild; if (sel !== false && next && isBR(next)) parent.setTimeout(function(){ if (select.selectionTopNode(self.container) == next) select.focusAfterNode(next.previousSibling, self.container); }, 20); } else if (event.code == 46) { // delete var sel = select.selectionTopNode(this.container), self = this; if (sel && isBR(sel)) { parent.setTimeout(function(){ if (select.selectionTopNode(self.container) != sel) select.focusAfterNode(sel, self.container); }, 20); } } } // In 533.* WebKit versions, when the document is big, typing // something at the end of a line causes the browser to do some // kind of stupid heavy operation, creating delays of several // seconds before the typed characters appear. This very crude // hack inserts a temporary zero-width space after the cursor to // make it not be at the end of the line. else if (slowWebkit) { var sel = select.selectionTopNode(this.container), next = sel ? sel.nextSibling : this.container.firstChild; // Doesn't work on empty lines, for some reason those always // trigger the delay. if (sel && next && isBR(next) && !isBR(sel)) { var cheat = document.createTextNode("\u200b"); this.container.insertBefore(cheat, next); parent.setTimeout(function() { if (cheat.nodeValue == "\u200b") removeElement(cheat); else cheat.nodeValue = cheat.nodeValue.replace("\u200b", ""); }, 20); } } // Magic incantation that works abound a webkit bug when you // can't type on a blank line following a line that's wider than // the window. if (webkit && !this.options.textWrapping) setTimeout(function () { var node = select.selectionTopNode(self.container, true); if (node && node.nodeType == 3 && node.previousSibling && isBR(node.previousSibling) && node.nextSibling && isBR(node.nextSibling)) node.parentNode.replaceChild(document.createElement("BR"), node.previousSibling); }, 50); }, // Mark the node at the cursor dirty when a non-safe key is // released. keyUp: function(event) { this.cursorActivity(isSafeKey(event.keyCode)); }, // Indent the line following a given <br>, or null for the first // line. If given a <br> element, this must have been highlighted // so that it has an indentation method. Returns the whitespace // element that has been modified or created (if any). indentLineAfter: function(start, direction) { function whiteSpaceAfter(node) { var ws = node ? node.nextSibling : self.container.firstChild; if (!ws || !hasClass(ws, "whitespace")) return null; return ws; } // whiteSpace is the whitespace span at the start of the line, // or null if there is no such node. var self = this, whiteSpace = whiteSpaceAfter(start); var newIndent = 0, curIndent = whiteSpace ? whiteSpace.currentText.length : 0; var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild); if (direction == "keep") { if (start) { var prevWS = whiteSpaceAfter(startOfLine(start.previousSibling)) if (prevWS) newIndent = prevWS.currentText.length; } } else { // Sometimes the start of the line can influence the correct // indentation, so we retrieve it. var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : ""; // Ask the lexical context for the correct indentation, and // compute how much this differs from the current indentation. if (direction != null && this.options.tabMode != "indent") newIndent = direction ? curIndent + indentUnit : Math.max(0, curIndent - indentUnit) else if (start) newIndent = start.indentation(nextChars, curIndent, direction, firstText); else if (Editor.Parser.firstIndentation) newIndent = Editor.Parser.firstIndentation(nextChars, curIndent, direction, firstText); } var indentDiff = newIndent - curIndent; // If there is too much, this is just a matter of shrinking a span. if (indentDiff < 0) { if (newIndent == 0) { if (firstText) select.snapshotMove(whiteSpace.firstChild, firstText.firstChild || firstText, 0); removeElement(whiteSpace); whiteSpace = null; } else { select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true); whiteSpace.currentText = makeWhiteSpace(newIndent); whiteSpace.firstChild.nodeValue = whiteSpace.currentText; } } // Not enough... else if (indentDiff > 0) { // If there is whitespace, we grow it. if (whiteSpace) { whiteSpace.currentText = makeWhiteSpace(newIndent); whiteSpace.firstChild.nodeValue = whiteSpace.currentText; select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true); } // Otherwise, we have to add a new whitespace node. else { whiteSpace = makePartSpan(makeWhiteSpace(newIndent)); whiteSpace.className = "whitespace"; if (start) insertAfter(whiteSpace, start); else this.container.insertBefore(whiteSpace, this.container.firstChild); select.snapshotMove(firstText && (firstText.firstChild || firstText), whiteSpace.firstChild, newIndent, false, true); } } // Make sure cursor ends up after the whitespace else if (whiteSpace) { select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, newIndent, false); } if (indentDiff != 0) this.addDirtyNode(start); }, // Re-highlight the selected part of the document. highlightAtCursor: function() { var pos = select.selectionTopNode(this.container, true); var to = select.selectionTopNode(this.container, false); if (pos === false || to === false) return false; select.markSelection(); if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false) return false; select.selectMarked(); return true; }, // When tab is pressed with text selected, the whole selection is // re-indented, when nothing is selected, the line with the cursor // is re-indented. handleTab: function(direction) { if (this.options.tabMode == "spaces" && !select.somethingSelected()) select.insertTabAtCursor(); else this.reindentSelection(direction); }, // Custom home behaviour that doesn't land the cursor in front of // leading whitespace unless pressed twice. home: function() { var cur = select.selectionTopNode(this.container, true), start = cur; if (cur === false || !(!cur || cur.isPart || isBR(cur)) || !this.container.firstChild) return false; while (cur && !isBR(cur)) cur = cur.previousSibling; var next = cur ? cur.nextSibling : this.container.firstChild; if (next && next != start && next.isPart && hasClass(next, "whitespace")) select.focusAfterNode(next, this.container); else select.focusAfterNode(cur, this.container); select.scrollToCursor(this.container); return true; }, // Some browsers (Opera) don't manage to handle the end key // properly in the face of vertical scrolling. end: function() { var cur = select.selectionTopNode(this.container, true); if (cur === false) return false; cur = endOfLine(cur, this.container); if (!cur) return false; select.focusAfterNode(cur.previousSibling, this.container); select.scrollToCursor(this.container); return true; }, pageUp: function() { var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount(); if (line === false || scrollAmount === false) return false; // Try to keep one line on the screen. scrollAmount -= 2; for (var i = 0; i < scrollAmount; i++) { line = this.prevLine(line); if (line === false) break; } if (i == 0) return false; // Already at first line select.setCursorPos(this.container, {node: line, offset: 0}); select.scrollToCursor(this.container); return true; }, pageDown: function() { var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount(); if (line === false || scrollAmount === false) return false; // Try to move to the last line of the current page. scrollAmount -= 2; for (var i = 0; i < scrollAmount; i++) { var nextLine = this.nextLine(line); if (nextLine === false) break; line = nextLine; } if (i == 0) return false; // Already at last line select.setCursorPos(this.container, {node: line, offset: 0}); select.scrollToCursor(this.container); return true; }, // Delay (or initiate) the next paren highlight event. scheduleParenHighlight: function() { if (this.parenEvent) parent.clearTimeout(this.parenEvent); var self = this; this.parenEvent = parent.setTimeout(function(){self.highlightParens();}, 300); }, // Take the token before the cursor. If it contains a character in // '()[]{}', search for the matching paren/brace/bracket, and // highlight them in green for a moment, or red if no proper match // was found. highlightParens: function(jump, fromKey) { var self = this, mark = this.options.markParen; if (typeof mark == "string") mark = [mark, mark]; // give the relevant nodes a colour. function highlight(node, ok) { if (!node) return; if (!mark) { node.style.fontWeight = "bold"; node.style.color = ok ? "#8F8" : "#F88"; } else if (mark.call) mark(node, ok); else node.className += " " + mark[ok ? 0 : 1]; } function unhighlight(node) { if (!node) return; if (mark && !mark.call) removeClass(removeClass(node, mark[0]), mark[1]); else if (self.options.unmarkParen) self.options.unmarkParen(node); else { node.style.fontWeight = ""; node.style.color = ""; } } if (!fromKey && self.highlighted) { unhighlight(self.highlighted[0]); unhighlight(self.highlighted[1]); } if (!window || !window.parent || !window.select) return; // Clear the event property. if (this.parenEvent) parent.clearTimeout(this.parenEvent); this.parenEvent = null; // Extract a 'paren' from a piece of text. function paren(node) { if (node.currentText) { var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/); return match && match[1]; } } // Determine the direction a paren is facing. function forward(ch) { return /[\(\[\{]/.test(ch); } var ch, cursor = select.selectionTopNode(this.container, true); if (!cursor || !this.highlightAtCursor()) return; cursor = select.selectionTopNode(this.container, true); if (!(cursor && ((ch = paren(cursor)) || (cursor = cursor.nextSibling) && (ch = paren(cursor))))) return; // We only look for tokens with the same className. var className = cursor.className, dir = forward(ch), match = matching[ch]; // Since parts of the document might not have been properly // highlighted, and it is hard to know in advance which part we // have to scan, we just try, and when we find dirty nodes we // abort, parse them, and re-try. function tryFindMatch() { var stack = [], ch, ok = true; for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) { if (runner.className == className && isSpan(runner) && (ch = paren(runner))) { if (forward(ch) == dir) stack.push(ch); else if (!stack.length) ok = false; else if (stack.pop() != matching[ch]) ok = false; if (!stack.length) break; } else if (runner.dirty || !isSpan(runner) && !isBR(runner)) { return {node: runner, status: "dirty"}; } } return {node: runner, status: runner && ok}; } while (true) { var found = tryFindMatch(); if (found.status == "dirty") { this.highlight(found.node, endOfLine(found.node)); // Needed because in some corner cases a highlight does not // reach a node. found.node.dirty = false; continue; } else { highlight(cursor, found.status); highlight(found.node, found.status); if (fromKey) parent.setTimeout(function() {unhighlight(cursor); unhighlight(found.node);}, 500); else self.highlighted = [cursor, found.node]; if (jump && found.node) select.focusAfterNode(found.node.previousSibling, this.container); break; } } }, // Adjust the amount of whitespace at the start of the line that // the cursor is on so that it is indented properly. indentAtCursor: function(direction) { if (!this.container.firstChild) return; // The line has to have up-to-date lexical information, so we // highlight it first. if (!this.highlightAtCursor()) return; var cursor = select.selectionTopNode(this.container, false); // If we couldn't determine the place of the cursor, // there's nothing to indent. if (cursor === false) return; select.markSelection(); this.indentLineAfter(startOfLine(cursor), direction); select.selectMarked(); }, // Indent all lines whose start falls inside of the current // selection. indentRegion: function(start, end, direction, selectAfter) { var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling); if (!isBR(end)) end = endOfLine(end, this.container); this.addDirtyNode(start); do { var next = endOfLine(current, this.container); if (current) this.highlight(before, next, true); this.indentLineAfter(current, direction); before = current; current = next; } while (current != end); if (selectAfter) select.setCursorPos(this.container, {node: start, offset: 0}, {node: end, offset: 0}); }, // Find the node that the cursor is in, mark it as dirty, and make // sure a highlight pass is scheduled. cursorActivity: function(safe) { // pagehide event hack above if (this.unloaded) { window.document.designMode = "off"; window.document.designMode = "on"; this.unloaded = false; } if (internetExplorer) { this.container.createTextRange().execCommand("unlink"); clearTimeout(this.saveSelectionSnapshot); var self = this; this.saveSelectionSnapshot = setTimeout(function() { var snapshot = select.getBookmark(self.container); if (snapshot) self.selectionSnapshot = snapshot; }, 200); } var activity = this.options.onCursorActivity; if (!safe || activity) { var cursor = select.selectionTopNode(this.container, false); if (cursor === false || !this.container.firstChild) return; cursor = cursor || this.container.firstChild; if (activity) activity(cursor); if (!safe) { this.scheduleHighlight(); this.addDirtyNode(cursor); } } }, reparseBuffer: function() { forEach(this.container.childNodes, function(node) {node.dirty = true;}); if (this.container.firstChild) this.addDirtyNode(this.container.firstChild); }, // Add a node to the set of dirty nodes, if it isn't already in // there. addDirtyNode: function(node) { node = node || this.container.firstChild; if (!node) return; for (var i = 0; i < this.dirty.length; i++) if (this.dirty[i] == node) return; if (node.nodeType != 3) node.dirty = true; this.dirty.push(node); }, allClean: function() { return !this.dirty.length; }, // Cause a highlight pass to happen in options.passDelay // milliseconds. Clear the existing timeout, if one exists. This // way, the passes do not happen while the user is typing, and // should as unobtrusive as possible. scheduleHighlight: function() { // Timeouts are routed through the parent window, because on // some browsers designMode windows do not fire timeouts. var self = this; parent.clearTimeout(this.highlightTimeout); this.highlightTimeout = parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay); }, // Fetch one dirty node, and remove it from the dirty set. getDirtyNode: function() { while (this.dirty.length > 0) { var found = this.dirty.pop(); // IE8 sometimes throws an unexplainable 'invalid argument' // exception for found.parentNode try { // If the node has been coloured in the meantime, or is no // longer in the document, it should not be returned. while (found && found.parentNode != this.container) found = found.parentNode; if (found && (found.dirty || found.nodeType == 3)) return found; } catch (e) {} } return null; }, // Pick dirty nodes, and highlight them, until options.passTime // milliseconds have gone by. The highlight method will continue // to next lines as long as it finds dirty nodes. It returns // information about the place where it stopped. If there are // dirty nodes left after this function has spent all its lines, // it shedules another highlight to finish the job. highlightDirty: function(force) { // Prevent FF from raising an error when it is firing timeouts // on a page that's no longer loaded. if (!window || !window.parent || !window.select) return false; if (!this.options.readOnly) select.markSelection(); var start, endTime = force ? null : time() + this.options.passTime; while ((time() < endTime || force) && (start = this.getDirtyNode())) { var result = this.highlight(start, endTime); if (result && result.node && result.dirty) this.addDirtyNode(result.node.nextSibling); } if (!this.options.readOnly) select.selectMarked(); if (start) this.scheduleHighlight(); return this.dirty.length == 0; }, // Creates a function that, when called through a timeout, will // continuously re-parse the document. documentScanner: function(passTime) { var self = this, pos = null; return function() { // FF timeout weirdness workaround. if (!window || !window.parent || !window.select) return; // If the current node is no longer in the document... oh // well, we start over. if (pos && pos.parentNode != self.container) pos = null; select.markSelection(); var result = self.highlight(pos, time() + passTime, true); select.selectMarked(); var newPos = result ? (result.node && result.node.nextSibling) : null; pos = (pos == newPos) ? null : newPos; self.delayScanning(); }; }, // Starts the continuous scanning process for this document after // a given interval. delayScanning: function() { if (this.scanner) { parent.clearTimeout(this.documentScan); this.documentScan = parent.setTimeout(this.scanner, this.options.continuousScanning); } }, // The function that does the actual highlighting/colouring (with // help from the parser and the DOM normalizer). Its interface is // rather overcomplicated, because it is used in different // situations: ensuring that a certain line is highlighted, or // highlighting up to X milliseconds starting from a certain // point. The 'from' argument gives the node at which it should // start. If this is null, it will start at the beginning of the // document. When a timestamp is given with the 'target' argument, // it will stop highlighting at that time. If this argument holds // a DOM node, it will highlight until it reaches that node. If at // any time it comes across two 'clean' lines (no dirty nodes), it // will stop, except when 'cleanLines' is true. maxBacktrack is // the maximum number of lines to backtrack to find an existing // parser instance. This is used to give up in situations where a // highlight would take too long and freeze the browser interface. highlight: function(from, target, cleanLines, maxBacktrack){ var container = this.container, self = this, active = this.options.activeTokens; var endTime = (typeof target == "number" ? target : null); if (!container.firstChild) return false; // Backtrack to the first node before from that has a partial // parse stored. while (from && (!from.parserFromHere || from.dirty)) { if (maxBacktrack != null && isBR(from) && (--maxBacktrack) < 0) return false; from = from.previousSibling; } // If we are at the end of the document, do nothing. if (from && !from.nextSibling) return false; // Check whether a part (<span> node) and the corresponding token // match. function correctPart(token, part){ return !part.reduced && part.currentText == token.value && part.className == token.style; } // Shorten the text associated with a part by chopping off // characters from the front. Note that only the currentText // property gets changed. For efficiency reasons, we leave the // nodeValue alone -- we set the reduced flag to indicate that // this part must be replaced. function shortenPart(part, minus){ part.currentText = part.currentText.substring(minus); part.reduced = true; } // Create a part corresponding to a given token. function tokenPart(token){ var part = makePartSpan(token.value); part.className = token.style; return part; } function maybeTouch(node) { if (node) { var old = node.oldNextSibling; if (lineDirty || old === undefined || node.nextSibling != old) self.history.touch(node); node.oldNextSibling = node.nextSibling; } else { var old = self.container.oldFirstChild; if (lineDirty || old === undefined || self.container.firstChild != old) self.history.touch(null); self.container.oldFirstChild = self.container.firstChild; } } // Get the token stream. If from is null, we start with a new // parser from the start of the frame, otherwise a partial parse // is resumed. var traversal = traverseDOM(from ? from.nextSibling : container.firstChild), stream = stringStream(traversal), parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream); function surroundedByBRs(node) { return (node.previousSibling == null || isBR(node.previousSibling)) && (node.nextSibling == null || isBR(node.nextSibling)); } // parts is an interface to make it possible to 'delay' fetching // the next DOM node until we are completely done with the one // before it. This is necessary because often the next node is // not yet available when we want to proceed past the current // one. var parts = { current: null, // Fetch current node. get: function(){ if (!this.current) this.current = traversal.nodes.shift(); return this.current; }, // Advance to the next part (do not fetch it yet). next: function(){ this.current = null; }, // Remove the current part from the DOM tree, and move to the // next. remove: function(){ container.removeChild(this.get()); this.current = null; }, // Advance to the next part that is not empty, discarding empty // parts. getNonEmpty: function(){ var part = this.get(); // Allow empty nodes when they are alone on a line, needed // for the FF cursor bug workaround (see select.js, // insertNewlineAtCursor). while (part && isSpan(part) && part.currentText == "") { // Leave empty nodes that are alone on a line alone in // Opera, since that browsers doesn't deal well with // having 2 BRs in a row. if (window.opera && surroundedByBRs(part)) { this.next(); part = this.get(); } else { var old = part; this.remove(); part = this.get(); // Adjust selection information, if any. See select.js for details. select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0); } } return part; } }; var lineDirty = false, prevLineDirty = true, lineNodes = 0; // This forEach loops over the tokens from the parsed stream, and // at the same time uses the parts object to proceed through the // corresponding DOM nodes. forEach(parsed, function(token){ var part = parts.getNonEmpty(); if (token.value == "\n"){ // The idea of the two streams actually staying synchronized // is such a long shot that we explicitly check. if (!isBR(part)) throw "Parser out of sync. Expected BR."; if (part.dirty || !part.indentation) lineDirty = true; maybeTouch(from); from = part; // Every <br> gets a copy of the parser state and a lexical // context assigned to it. The first is used to be able to // later resume parsing from this point, the second is used // for indentation. part.parserFromHere = parsed.copy(); part.indentation = token.indentation || alwaysZero; part.dirty = false; // If the target argument wasn't an integer, go at least // until that node. if (endTime == null && part == target) throw StopIteration; // A clean line with more than one node means we are done. // Throwing a StopIteration is the way to break out of a // MochiKit forEach loop. if ((endTime != null && time() >= endTime) || (!lineDirty && !prevLineDirty && lineNodes > 1 && !cleanLines)) throw StopIteration; prevLineDirty = lineDirty; lineDirty = false; lineNodes = 0; parts.next(); } else { if (!isSpan(part)) throw "Parser out of sync. Expected SPAN."; if (part.dirty) lineDirty = true; lineNodes++; // If the part matches the token, we can leave it alone. if (correctPart(token, part)){ if (active && part.dirty) active(part, token, self); part.dirty = false; parts.next(); } // Otherwise, we have to fix it. else { lineDirty = true; // Insert the correct part. var newPart = tokenPart(token); container.insertBefore(newPart, part); if (active) active(newPart, token, self); var tokensize = token.value.length; var offset = 0; // Eat up parts until the text for this token has been // removed, adjusting the stored selection info (see // select.js) in the process. while (tokensize > 0) { part = parts.get(); var partsize = part.currentText.length; select.snapshotReplaceNode(part.firstChild, newPart.firstChild, tokensize, offset); if (partsize > tokensize){ shortenPart(part, tokensize); tokensize = 0; } else { tokensize -= partsize; offset += partsize; parts.remove(); } } } } }); maybeTouch(from); webkitLastLineHack(this.container); // The function returns some status information that is used by // hightlightDirty to determine whether and where it has to // continue. return {node: parts.getNonEmpty(), dirty: lineDirty}; } }; return Editor; })(); addEventHandler(window, "load", function() { var CodeMirror = window.frameElement.CodeMirror; var e = CodeMirror.editor = new Editor(CodeMirror.options); parent.setTimeout(method(CodeMirror, "init"), 0); });
JavaScript
/* String streams are the things fed to parsers (which can feed them * to a tokenizer if they want). They provide peek and next methods * for looking at the current character (next 'consumes' this * character, peek does not), and a get method for retrieving all the * text that was consumed since the last time get was called. * * An easy mistake to make is to let a StopIteration exception finish * the token stream while there are still characters pending in the * string stream (hitting the end of the buffer while parsing a * token). To make it easier to detect such errors, the stringstreams * throw an exception when this happens. */ // Make a stringstream stream out of an iterator that returns strings. // This is applied to the result of traverseDOM (see codemirror.js), // and the resulting stream is fed to the parser. var stringStream = function(source){ // String that's currently being iterated over. var current = ""; // Position in that string. var pos = 0; // Accumulator for strings that have been iterated over but not // get()-ed yet. var accum = ""; // Make sure there are more characters ready, or throw // StopIteration. function ensureChars() { while (pos == current.length) { accum += current; current = ""; // In case source.next() throws pos = 0; try {current = source.next();} catch (e) { if (e != StopIteration) throw e; else return false; } } return true; } return { // peek: -> character // Return the next character in the stream. peek: function() { if (!ensureChars()) return null; return current.charAt(pos); }, // next: -> character // Get the next character, throw StopIteration if at end, check // for unused content. next: function() { if (!ensureChars()) { if (accum.length > 0) throw "End of stringstream reached without emptying buffer ('" + accum + "')."; else throw StopIteration; } return current.charAt(pos++); }, // get(): -> string // Return the characters iterated over since the last call to // .get(). get: function() { var temp = accum; accum = ""; if (pos > 0){ temp += current.slice(0, pos); current = current.slice(pos); pos = 0; } return temp; }, // Push a string back into the stream. push: function(str) { current = current.slice(0, pos) + str + current.slice(pos); }, lookAhead: function(str, consume, skipSpaces, caseInsensitive) { function cased(str) {return caseInsensitive ? str.toLowerCase() : str;} str = cased(str); var found = false; var _accum = accum, _pos = pos; if (skipSpaces) this.nextWhileMatches(/[\s\u00a0]/); while (true) { var end = pos + str.length, left = current.length - pos; if (end <= current.length) { found = str == cased(current.slice(pos, end)); pos = end; break; } else if (str.slice(0, left) == cased(current.slice(pos))) { accum += current; current = ""; try {current = source.next();} catch (e) {if (e != StopIteration) throw e; break;} pos = 0; str = str.slice(left); } else { break; } } if (!(found && consume)) { current = accum.slice(_accum.length) + current; pos = _pos; accum = _accum; } return found; }, // Wont't match past end of line. lookAheadRegex: function(regex, consume) { if (regex.source.charAt(0) != "^") throw new Error("Regexps passed to lookAheadRegex must start with ^"); // Fetch the rest of the line while (current.indexOf("\n", pos) == -1) { try {current += source.next();} catch (e) {if (e != StopIteration) throw e; break;} } var matched = current.slice(pos).match(regex); if (matched && consume) pos += matched[0].length; return matched; }, // Utils built on top of the above // more: -> boolean // Produce true if the stream isn't empty. more: function() { return this.peek() !== null; }, applies: function(test) { var next = this.peek(); return (next !== null && test(next)); }, nextWhile: function(test) { var next; while ((next = this.peek()) !== null && test(next)) this.next(); }, matches: function(re) { var next = this.peek(); return (next !== null && re.test(next)); }, nextWhileMatches: function(re) { var next; while ((next = this.peek()) !== null && re.test(next)) this.next(); }, equals: function(ch) { return ch === this.peek(); }, endOfLine: function() { var next = this.peek(); return next == null || next == "\n"; } }; };
JavaScript
/** * Storage and control for undo information within a CodeMirror * editor. 'Why on earth is such a complicated mess required for * that?', I hear you ask. The goal, in implementing this, was to make * the complexity of storing and reverting undo information depend * only on the size of the edited or restored content, not on the size * of the whole document. This makes it necessary to use a kind of * 'diff' system, which, when applied to a DOM tree, causes some * complexity and hackery. * * In short, the editor 'touches' BR elements as it parses them, and * the UndoHistory stores these. When nothing is touched in commitDelay * milliseconds, the changes are committed: It goes over all touched * nodes, throws out the ones that did not change since last commit or * are no longer in the document, and assembles the rest into zero or * more 'chains' -- arrays of adjacent lines. Links back to these * chains are added to the BR nodes, while the chain that previously * spanned these nodes is added to the undo history. Undoing a change * means taking such a chain off the undo history, restoring its * content (text is saved per line) and linking it back into the * document. */ // A history object needs to know about the DOM container holding the // document, the maximum amount of undo levels it should store, the // delay (of no input) after which it commits a set of changes, and, // unfortunately, the 'parent' window -- a window that is not in // designMode, and on which setTimeout works in every browser. function UndoHistory(container, maxDepth, commitDelay, editor) { this.container = container; this.maxDepth = maxDepth; this.commitDelay = commitDelay; this.editor = editor; // This line object represents the initial, empty editor. var initial = {text: "", from: null, to: null}; // As the borders between lines are represented by BR elements, the // start of the first line and the end of the last one are // represented by null. Since you can not store any properties // (links to line objects) in null, these properties are used in // those cases. this.first = initial; this.last = initial; // Similarly, a 'historyTouched' property is added to the BR in // front of lines that have already been touched, and 'firstTouched' // is used for the first line. this.firstTouched = false; // History is the set of committed changes, touched is the set of // nodes touched since the last commit. this.history = []; this.redoHistory = []; this.touched = []; this.lostundo = 0; } UndoHistory.prototype = { // Schedule a commit (if no other touches come in for commitDelay // milliseconds). scheduleCommit: function() { var self = this; parent.clearTimeout(this.commitTimeout); this.commitTimeout = parent.setTimeout(function(){self.tryCommit();}, this.commitDelay); }, // Mark a node as touched. Null is a valid argument. touch: function(node) { this.setTouched(node); this.scheduleCommit(); }, // Undo the last change. undo: function() { // Make sure pending changes have been committed. this.commit(); if (this.history.length) { // Take the top diff from the history, apply it, and store its // shadow in the redo history. var item = this.history.pop(); this.redoHistory.push(this.updateTo(item, "applyChain")); this.notifyEnvironment(); return this.chainNode(item); } }, // Redo the last undone change. redo: function() { this.commit(); if (this.redoHistory.length) { // The inverse of undo, basically. var item = this.redoHistory.pop(); this.addUndoLevel(this.updateTo(item, "applyChain")); this.notifyEnvironment(); return this.chainNode(item); } }, clear: function() { this.history = []; this.redoHistory = []; this.lostundo = 0; }, // Ask for the size of the un/redo histories. historySize: function() { return {undo: this.history.length, redo: this.redoHistory.length, lostundo: this.lostundo}; }, // Push a changeset into the document. push: function(from, to, lines) { var chain = []; for (var i = 0; i < lines.length; i++) { var end = (i == lines.length - 1) ? to : document.createElement("br"); chain.push({from: from, to: end, text: cleanText(lines[i])}); from = end; } this.pushChains([chain], from == null && to == null); this.notifyEnvironment(); }, pushChains: function(chains, doNotHighlight) { this.commit(doNotHighlight); this.addUndoLevel(this.updateTo(chains, "applyChain")); this.redoHistory = []; }, // Retrieve a DOM node from a chain (for scrolling to it after undo/redo). chainNode: function(chains) { for (var i = 0; i < chains.length; i++) { var start = chains[i][0], node = start && (start.from || start.to); if (node) return node; } }, // Clear the undo history, make the current document the start // position. reset: function() { this.history = []; this.redoHistory = []; this.lostundo = 0; }, textAfter: function(br) { return this.after(br).text; }, nodeAfter: function(br) { return this.after(br).to; }, nodeBefore: function(br) { return this.before(br).from; }, // Commit unless there are pending dirty nodes. tryCommit: function() { if (!window || !window.parent || !window.UndoHistory) return; // Stop when frame has been unloaded if (this.editor.highlightDirty()) this.commit(true); else this.scheduleCommit(); }, // Check whether the touched nodes hold any changes, if so, commit // them. commit: function(doNotHighlight) { parent.clearTimeout(this.commitTimeout); // Make sure there are no pending dirty nodes. if (!doNotHighlight) this.editor.highlightDirty(true); // Build set of chains. var chains = this.touchedChains(), self = this; if (chains.length) { this.addUndoLevel(this.updateTo(chains, "linkChain")); this.redoHistory = []; this.notifyEnvironment(); } }, // [ end of public interface ] // Update the document with a given set of chains, return its // shadow. updateFunc should be "applyChain" or "linkChain". In the // second case, the chains are taken to correspond the the current // document, and only the state of the line data is updated. In the // first case, the content of the chains is also pushed iinto the // document. updateTo: function(chains, updateFunc) { var shadows = [], dirty = []; for (var i = 0; i < chains.length; i++) { shadows.push(this.shadowChain(chains[i])); dirty.push(this[updateFunc](chains[i])); } if (updateFunc == "applyChain") this.notifyDirty(dirty); return shadows; }, // Notify the editor that some nodes have changed. notifyDirty: function(nodes) { forEach(nodes, method(this.editor, "addDirtyNode")) this.editor.scheduleHighlight(); }, notifyEnvironment: function() { if (this.onChange) this.onChange(this.editor); // Used by the line-wrapping line-numbering code. if (window.frameElement && window.frameElement.CodeMirror.updateNumbers) window.frameElement.CodeMirror.updateNumbers(); }, // Link a chain into the DOM nodes (or the first/last links for null // nodes). linkChain: function(chain) { for (var i = 0; i < chain.length; i++) { var line = chain[i]; if (line.from) line.from.historyAfter = line; else this.first = line; if (line.to) line.to.historyBefore = line; else this.last = line; } }, // Get the line object after/before a given node. after: function(node) { return node ? node.historyAfter : this.first; }, before: function(node) { return node ? node.historyBefore : this.last; }, // Mark a node as touched if it has not already been marked. setTouched: function(node) { if (node) { if (!node.historyTouched) { this.touched.push(node); node.historyTouched = true; } } else { this.firstTouched = true; } }, // Store a new set of undo info, throw away info if there is more of // it than allowed. addUndoLevel: function(diffs) { this.history.push(diffs); if (this.history.length > this.maxDepth) { this.history.shift(); this.lostundo += 1; } }, // Build chains from a set of touched nodes. touchedChains: function() { var self = this; // The temp system is a crummy hack to speed up determining // whether a (currently touched) node has a line object associated // with it. nullTemp is used to store the object for the first // line, other nodes get it stored in their historyTemp property. var nullTemp = null; function temp(node) {return node ? node.historyTemp : nullTemp;} function setTemp(node, line) { if (node) node.historyTemp = line; else nullTemp = line; } function buildLine(node) { var text = []; for (var cur = node ? node.nextSibling : self.container.firstChild; cur && (!isBR(cur) || cur.hackBR); cur = cur.nextSibling) if (!cur.hackBR && cur.currentText) text.push(cur.currentText); return {from: node, to: cur, text: cleanText(text.join(""))}; } // Filter out unchanged lines and nodes that are no longer in the // document. Build up line objects for remaining nodes. var lines = []; if (self.firstTouched) self.touched.push(null); forEach(self.touched, function(node) { if (node && (node.parentNode != self.container || node.hackBR)) return; if (node) node.historyTouched = false; else self.firstTouched = false; var line = buildLine(node), shadow = self.after(node); if (!shadow || shadow.text != line.text || shadow.to != line.to) { lines.push(line); setTemp(node, line); } }); // Get the BR element after/before the given node. function nextBR(node, dir) { var link = dir + "Sibling", search = node[link]; while (search && !isBR(search)) search = search[link]; return search; } // Assemble line objects into chains by scanning the DOM tree // around them. var chains = []; self.touched = []; forEach(lines, function(line) { // Note that this makes the loop skip line objects that have // been pulled into chains by lines before them. if (!temp(line.from)) return; var chain = [], curNode = line.from, safe = true; // Put any line objects (referred to by temp info) before this // one on the front of the array. while (true) { var curLine = temp(curNode); if (!curLine) { if (safe) break; else curLine = buildLine(curNode); } chain.unshift(curLine); setTemp(curNode, null); if (!curNode) break; safe = self.after(curNode); curNode = nextBR(curNode, "previous"); } curNode = line.to; safe = self.before(line.from); // Add lines after this one at end of array. while (true) { if (!curNode) break; var curLine = temp(curNode); if (!curLine) { if (safe) break; else curLine = buildLine(curNode); } chain.push(curLine); setTemp(curNode, null); safe = self.before(curNode); curNode = nextBR(curNode, "next"); } chains.push(chain); }); return chains; }, // Find the 'shadow' of a given chain by following the links in the // DOM nodes at its start and end. shadowChain: function(chain) { var shadows = [], next = this.after(chain[0].from), end = chain[chain.length - 1].to; while (true) { shadows.push(next); var nextNode = next.to; if (!nextNode || nextNode == end) break; else next = nextNode.historyAfter || this.before(end); // (The this.before(end) is a hack -- FF sometimes removes // properties from BR nodes, in which case the best we can hope // for is to not break.) } return shadows; }, // Update the DOM tree to contain the lines specified in a given // chain, link this chain into the DOM nodes. applyChain: function(chain) { // Some attempt is made to prevent the cursor from jumping // randomly when an undo or redo happens. It still behaves a bit // strange sometimes. var cursor = select.cursorPos(this.container, false), self = this; // Remove all nodes in the DOM tree between from and to (null for // start/end of container). function removeRange(from, to) { var pos = from ? from.nextSibling : self.container.firstChild; while (pos != to) { var temp = pos.nextSibling; removeElement(pos); pos = temp; } } var start = chain[0].from, end = chain[chain.length - 1].to; // Clear the space where this change has to be made. removeRange(start, end); // Insert the content specified by the chain into the DOM tree. for (var i = 0; i < chain.length; i++) { var line = chain[i]; // The start and end of the space are already correct, but BR // tags inside it have to be put back. if (i > 0) self.container.insertBefore(line.from, end); // Add the text. var node = makePartSpan(fixSpaces(line.text)); self.container.insertBefore(node, end); // See if the cursor was on this line. Put it back, adjusting // for changed line length, if it was. if (cursor && cursor.node == line.from) { var cursordiff = 0; var prev = this.after(line.from); if (prev && i == chain.length - 1) { // Only adjust if the cursor is after the unchanged part of // the line. for (var match = 0; match < cursor.offset && line.text.charAt(match) == prev.text.charAt(match); match++){} if (cursor.offset > match) cursordiff = line.text.length - prev.text.length; } select.setCursorPos(this.container, {node: line.from, offset: Math.max(0, cursor.offset + cursordiff)}); } // Cursor was in removed line, this is last new line. else if (cursor && (i == chain.length - 1) && cursor.node && cursor.node.parentNode != this.container) { select.setCursorPos(this.container, {node: line.from, offset: line.text.length}); } } // Anchor the chain in the DOM tree. this.linkChain(chain); return start; } };
JavaScript
/* Parse function for JavaScript. Makes use of the tokenizer from * tokenizejavascript.js. Note that your parsers do not have to be * this complicated -- if you don't want to recognize local variables, * in many languages it is enough to just look for braces, semicolons, * parentheses, etc, and know when you are inside a string or comment. * * See manual.html for more info about the parser interface. */ var JSParser = Editor.Parser = (function() { // Token types that can be considered to be atoms. var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true}; // Setting that can be used to have JSON data indent properly. var json = false; // Constructor for the lexical context objects. function JSLexical(indented, column, type, align, prev, info) { // indentation at start of this line this.indented = indented; // column at which this scope was opened this.column = column; // type of scope ('vardef', 'stat' (statement), 'form' (special form), '[', '{', or '(') this.type = type; // '[', '{', or '(' blocks that have any text after their opening // character are said to be 'aligned' -- any lines below are // indented all the way to the opening character. if (align != null) this.align = align; // Parent scope, if any. this.prev = prev; this.info = info; } // My favourite JavaScript indentation rules. function indentJS(lexical) { return function(firstChars) { var firstChar = firstChars && firstChars.charAt(0), type = lexical.type; var closing = firstChar == type; if (type == "vardef") return lexical.indented + 4; else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "stat" || type == "form") return lexical.indented + indentUnit; else if (lexical.info == "switch" && !closing) return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column - (closing ? 1 : 0); else return lexical.indented + (closing ? 0 : indentUnit); }; } // The parser-iterator-producing function itself. function parseJS(input, basecolumn) { // Wrap the input in a token stream var tokens = tokenizeJavaScript(input); // The parser state. cc is a stack of actions that have to be // performed to finish the current statement. For example we might // know that we still need to find a closing parenthesis and a // semicolon. Actions at the end of the stack go first. It is // initialized with an infinitely looping action that consumes // whole statements. var cc = [json ? expressions : statements]; // Context contains information about the current local scope, the // variables defined in that, and the scopes above it. var context = null; // The lexical scope, used mostly for indentation. var lexical = new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false); // Current column, and the indentation at the start of the current // line. Used to create lexical scope objects. var column = 0; var indented = 0; // Variables which are used by the mark, cont, and pass functions // below to communicate with the driver loop in the 'next' // function. var consume, marked; // The iterator object. var parser = {next: next, copy: copy}; function next(){ // Start by performing any 'lexical' actions (adjusting the // lexical variable), or the operations below will be working // with the wrong lexical state. while(cc[cc.length - 1].lex) cc.pop()(); // Fetch a token. var token = tokens.next(); // Adjust column and indented. if (token.type == "whitespace" && column == 0) indented = token.value.length; column += token.value.length; if (token.content == "\n"){ indented = column = 0; // If the lexical scope's align property is still undefined at // the end of the line, it is an un-aligned scope. if (!("align" in lexical)) lexical.align = false; // Newline tokens get an indentation function associated with // them. token.indentation = indentJS(lexical); } // No more processing for meaningless tokens. if (token.type == "whitespace" || token.type == "comment") return token; // When a meaningful token is found and the lexical scope's // align is undefined, it is an aligned scope. if (!("align" in lexical)) lexical.align = true; // Execute actions until one 'consumes' the token and we can // return it. while(true) { consume = marked = false; // Take and execute the topmost action. cc.pop()(token.type, token.content); if (consume){ // Marked is used to change the style of the current token. if (marked) token.style = marked; // Here we differentiate between local and global variables. else if (token.type == "variable" && inScope(token.content)) token.style = "js-localvariable"; return token; } } } // This makes a copy of the parser state. It stores all the // stateful variables in a closure, and returns a function that // will restore them when called with a new input stream. Note // that the cc array has to be copied, because it is contantly // being modified. Lexical objects are not mutated, and context // objects are not mutated in a harmful way, so they can be shared // between runs of the parser. function copy(){ var _context = context, _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state; return function copyParser(input){ context = _context; lexical = _lexical; cc = _cc.concat([]); // copies the array column = indented = 0; tokens = tokenizeJavaScript(input, _tokenState); return parser; }; } // Helper function for pushing a number of actions onto the cc // stack in reverse order. function push(fs){ for (var i = fs.length - 1; i >= 0; i--) cc.push(fs[i]); } // cont and pass are used by the action functions to add other // actions to the stack. cont will cause the current token to be // consumed, pass will leave it for the next action. function cont(){ push(arguments); consume = true; } function pass(){ push(arguments); consume = false; } // Used to change the style of the current token. function mark(style){ marked = style; } // Push a new scope. Will automatically link the current scope. function pushcontext(){ context = {prev: context, vars: {"this": true, "arguments": true}}; } // Pop off the current scope. function popcontext(){ context = context.prev; } // Register a variable in the current scope. function register(varname){ if (context){ mark("js-variabledef"); context.vars[varname] = true; } } // Check whether a variable is defined in the current scope. function inScope(varname){ var cursor = context; while (cursor) { if (cursor.vars[varname]) return true; cursor = cursor.prev; } return false; } // Push a new lexical context of the given type. function pushlex(type, info) { var result = function(){ lexical = new JSLexical(indented, column, type, null, lexical, info) }; result.lex = true; return result; } // Pop off the current lexical context. function poplex(){ if (lexical.type == ")") indented = lexical.indented; lexical = lexical.prev; } poplex.lex = true; // The 'lex' flag on these actions is used by the 'next' function // to know they can (and have to) be ran before moving on to the // next token. // Creates an action that discards tokens until it finds one of // the given type. function expect(wanted){ return function expecting(type){ if (type == wanted) cont(); else if (wanted == ";") pass(); else cont(arguments.callee); }; } // Looks for a statement, and then calls itself. function statements(type){ return pass(statement, statements); } function expressions(type){ return pass(expression, expressions); } // Dispatches various types of statements based on the type of the // current token. function statement(type){ if (type == "var") cont(pushlex("vardef"), vardef1, expect(";"), poplex); else if (type == "keyword a") cont(pushlex("form"), expression, statement, poplex); else if (type == "keyword b") cont(pushlex("form"), statement, poplex); else if (type == "{") cont(pushlex("}"), block, poplex); else if (type == ";") cont(); else if (type == "function") cont(functiondef); else if (type == "for") cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex); else if (type == "variable") cont(pushlex("stat"), maybelabel); else if (type == "switch") cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex); else if (type == "case") cont(expression, expect(":")); else if (type == "default") cont(expect(":")); else if (type == "catch") cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext); else pass(pushlex("stat"), expression, expect(";"), poplex); } // Dispatch expression types. function expression(type){ if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator); else if (type == "function") cont(functiondef); else if (type == "keyword c") cont(expression); else if (type == "(") cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator); else if (type == "operator") cont(expression); else if (type == "[") cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator); else if (type == "{") cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); else cont(); } // Called for places where operators, function calls, or // subscripts are valid. Will skip on to the next action if none // is found. function maybeoperator(type, value){ if (type == "operator" && /\+\+|--/.test(value)) cont(maybeoperator); else if (type == "operator") cont(expression); else if (type == ";") pass(); else if (type == "(") cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator); else if (type == ".") cont(property, maybeoperator); else if (type == "[") cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); } // When a statement starts with a variable name, it might be a // label. If no colon follows, it's a regular statement. function maybelabel(type){ if (type == ":") cont(poplex, statement); else pass(maybeoperator, expect(";"), poplex); } // Property names need to have their style adjusted -- the // tokenizer thinks they are variables. function property(type){ if (type == "variable") {mark("js-property"); cont();} } // This parses a property and its value in an object literal. function objprop(type){ if (type == "variable") mark("js-property"); if (atomicTypes.hasOwnProperty(type)) cont(expect(":"), expression); } // Parses a comma-separated list of the things that are recognized // by the 'what' argument. function commasep(what, end){ function proceed(type) { if (type == ",") cont(what, proceed); else if (type == end) cont(); else cont(expect(end)); } return function commaSeparated(type) { if (type == end) cont(); else pass(what, proceed); }; } // Look for statements until a closing brace is found. function block(type){ if (type == "}") cont(); else pass(statement, block); } // Variable definitions are split into two actions -- 1 looks for // a name or the end of the definition, 2 looks for an '=' sign or // a comma. function vardef1(type, value){ if (type == "variable"){register(value); cont(vardef2);} else cont(); } function vardef2(type, value){ if (value == "=") cont(expression, vardef2); else if (type == ",") cont(vardef1); } // For loops. function forspec1(type){ if (type == "var") cont(vardef1, forspec2); else if (type == ";") pass(forspec2); else if (type == "variable") cont(formaybein); else pass(forspec2); } function formaybein(type, value){ if (value == "in") cont(expression); else cont(maybeoperator, forspec2); } function forspec2(type, value){ if (type == ";") cont(forspec3); else if (value == "in") cont(expression); else cont(expression, expect(";"), forspec3); } function forspec3(type) { if (type == ")") pass(); else cont(expression); } // A function definition creates a new context, and the variables // in its argument list have to be added to this context. function functiondef(type, value){ if (type == "variable"){register(value); cont(functiondef);} else if (type == "(") cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext); } function funarg(type, value){ if (type == "variable"){register(value); cont();} } return parser; } return { make: parseJS, electricChars: "{}:", configure: function(obj) { if (obj.json != null) json = obj.json; } }; })();
JavaScript
var DummyParser = Editor.Parser = (function() { function tokenizeDummy(source) { while (!source.endOfLine()) source.next(); return "text"; } function parseDummy(source) { function indentTo(n) {return function() {return n;}} source = tokenizer(source, tokenizeDummy); var space = 0; var iter = { next: function() { var tok = source.next(); if (tok.type == "whitespace") { if (tok.value == "\n") tok.indentation = indentTo(space); else space = tok.value.length; } return tok; }, copy: function() { var _space = space; return function(_source) { space = _space; source = tokenizer(_source, tokenizeDummy); return iter; }; } }; return iter; } return {make: parseDummy}; })();
JavaScript
/* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed by Yahoo! Inc. under the BSD (revised) open source license @author Vlad Dan Dascalescu <dandv@yahoo-inc.com> Tokenizer for PHP code References: + http://php.net/manual/en/reserved.php + http://php.net/tokens + get_defined_constants(), get_defined_functions(), get_declared_classes() executed on a realistic (not vanilla) PHP installation with typical LAMP modules. Specifically, the PHP bundled with the Uniform Web Server (www.uniformserver.com). */ // add the forEach method for JS engines that don't support it (e.g. IE) // code from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) fun.call(thisp, this[i], i, this); } }; } var tokenizePHP = (function() { /* A map of PHP's reserved words (keywords, predefined classes, functions and constants. Each token has a type ('keyword', 'operator' etc.) and a style. The style corresponds to the CSS span class in phpcolors.css. Keywords can be of three types: a - takes an expression and forms a statement - e.g. if b - takes just a statement - e.g. else c - takes an optinoal expression, but no statement - e.g. return This distinction gives the parser enough information to parse correct code correctly (we don't care that much how we parse incorrect code). Reference: http://us.php.net/manual/en/reserved.php */ var keywords = function(){ function token(type, style){ return {type: type, style: style}; } var result = {}; // for each(var element in ["...", "..."]) can pick up elements added to // Array.prototype, so we'll use the loop structure below. See also // http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each...in // keywords that take an expression and form a statement ["if", "elseif", "while", "declare"].forEach(function(element, index, array) { result[element] = token("keyword a", "php-keyword"); }); // keywords that take just a statement ["do", "else", "try" ].forEach(function(element, index, array) { result[element] = token("keyword b", "php-keyword"); }); // keywords that take an optional expression, but no statement ["return", "break", "continue", // the expression is optional "new", "clone", "throw" // the expression is mandatory ].forEach(function(element, index, array) { result[element] = token("keyword c", "php-keyword"); }); ["__CLASS__", "__DIR__", "__FILE__", "__FUNCTION__", "__METHOD__", "__NAMESPACE__"].forEach(function(element, index, array) { result[element] = token("atom", "php-compile-time-constant"); }); ["true", "false", "null"].forEach(function(element, index, array) { result[element] = token("atom", "php-atom"); }); ["and", "or", "xor", "instanceof"].forEach(function(element, index, array) { result[element] = token("operator", "php-keyword php-operator"); }); ["class", "interface"].forEach(function(element, index, array) { result[element] = token("class", "php-keyword"); }); ["namespace", "use", "extends", "implements"].forEach(function(element, index, array) { result[element] = token("namespace", "php-keyword"); }); // reserved "language constructs"... http://php.net/manual/en/reserved.php [ "die", "echo", "empty", "exit", "eval", "include", "include_once", "isset", "list", "require", "require_once", "return", "print", "unset", "array" // a keyword rather, but mandates a parenthesized parameter list ].forEach(function(element, index, array) { result[element] = token("t_string", "php-reserved-language-construct"); }); result["switch"] = token("switch", "php-keyword"); result["case"] = token("case", "php-keyword"); result["default"] = token("default", "php-keyword"); result["catch"] = token("catch", "php-keyword"); result["function"] = token("function", "php-keyword"); // http://php.net/manual/en/control-structures.alternative-syntax.php must be followed by a ':' ["endif", "endwhile", "endfor", "endforeach", "endswitch", "enddeclare"].forEach(function(element, index, array) { result[element] = token("altsyntaxend", "php-keyword"); }); result["const"] = token("const", "php-keyword"); ["final", "private", "protected", "public", "global", "static"].forEach(function(element, index, array) { result[element] = token("modifier", "php-keyword"); }); result["var"] = token("modifier", "php-keyword deprecated"); result["abstract"] = token("abstract", "php-keyword"); result["foreach"] = token("foreach", "php-keyword"); result["as"] = token("as", "php-keyword"); result["for"] = token("for", "php-keyword"); // PHP built-in functions - output of get_defined_functions()["internal"] [ "zend_version", "func_num_args", "func_get_arg", "func_get_args", "strlen", "strcmp", "strncmp", "strcasecmp", "strncasecmp", "each", "error_reporting", "define", "defined", "get_class", "get_parent_class", "method_exists", "property_exists", "class_exists", "interface_exists", "function_exists", "get_included_files", "get_required_files", "is_subclass_of", "is_a", "get_class_vars", "get_object_vars", "get_class_methods", "trigger_error", "user_error", "set_error_handler", "restore_error_handler", "set_exception_handler", "restore_exception_handler", "get_declared_classes", "get_declared_interfaces", "get_defined_functions", "get_defined_vars", "create_function", "get_resource_type", "get_loaded_extensions", "extension_loaded", "get_extension_funcs", "get_defined_constants", "debug_backtrace", "debug_print_backtrace", "bcadd", "bcsub", "bcmul", "bcdiv", "bcmod", "bcpow", "bcsqrt", "bcscale", "bccomp", "bcpowmod", "jdtogregorian", "gregoriantojd", "jdtojulian", "juliantojd", "jdtojewish", "jewishtojd", "jdtofrench", "frenchtojd", "jddayofweek", "jdmonthname", "easter_date", "easter_days", "unixtojd", "jdtounix", "cal_to_jd", "cal_from_jd", "cal_days_in_month", "cal_info", "variant_set", "variant_add", "variant_cat", "variant_sub", "variant_mul", "variant_and", "variant_div", "variant_eqv", "variant_idiv", "variant_imp", "variant_mod", "variant_or", "variant_pow", "variant_xor", "variant_abs", "variant_fix", "variant_int", "variant_neg", "variant_not", "variant_round", "variant_cmp", "variant_date_to_timestamp", "variant_date_from_timestamp", "variant_get_type", "variant_set_type", "variant_cast", "com_create_guid", "com_event_sink", "com_print_typeinfo", "com_message_pump", "com_load_typelib", "com_get_active_object", "ctype_alnum", "ctype_alpha", "ctype_cntrl", "ctype_digit", "ctype_lower", "ctype_graph", "ctype_print", "ctype_punct", "ctype_space", "ctype_upper", "ctype_xdigit", "strtotime", "date", "idate", "gmdate", "mktime", "gmmktime", "checkdate", "strftime", "gmstrftime", "time", "localtime", "getdate", "date_create", "date_parse", "date_format", "date_modify", "date_timezone_get", "date_timezone_set", "date_offset_get", "date_time_set", "date_date_set", "date_isodate_set", "timezone_open", "timezone_name_get", "timezone_name_from_abbr", "timezone_offset_get", "timezone_transitions_get", "timezone_identifiers_list", "timezone_abbreviations_list", "date_default_timezone_set", "date_default_timezone_get", "date_sunrise", "date_sunset", "date_sun_info", "filter_input", "filter_var", "filter_input_array", "filter_var_array", "filter_list", "filter_has_var", "filter_id", "ftp_connect", "ftp_login", "ftp_pwd", "ftp_cdup", "ftp_chdir", "ftp_exec", "ftp_raw", "ftp_mkdir", "ftp_rmdir", "ftp_chmod", "ftp_alloc", "ftp_nlist", "ftp_rawlist", "ftp_systype", "ftp_pasv", "ftp_get", "ftp_fget", "ftp_put", "ftp_fput", "ftp_size", "ftp_mdtm", "ftp_rename", "ftp_delete", "ftp_site", "ftp_close", "ftp_set_option", "ftp_get_option", "ftp_nb_fget", "ftp_nb_get", "ftp_nb_continue", "ftp_nb_put", "ftp_nb_fput", "ftp_quit", "hash", "hash_file", "hash_hmac", "hash_hmac_file", "hash_init", "hash_update", "hash_update_stream", "hash_update_file", "hash_final", "hash_algos", "iconv", "ob_iconv_handler", "iconv_get_encoding", "iconv_set_encoding", "iconv_strlen", "iconv_substr", "iconv_strpos", "iconv_strrpos", "iconv_mime_encode", "iconv_mime_decode", "iconv_mime_decode_headers", "json_encode", "json_decode", "odbc_autocommit", "odbc_binmode", "odbc_close", "odbc_close_all", "odbc_columns", "odbc_commit", "odbc_connect", "odbc_cursor", "odbc_data_source", "odbc_execute", "odbc_error", "odbc_errormsg", "odbc_exec", "odbc_fetch_array", "odbc_fetch_object", "odbc_fetch_row", "odbc_fetch_into", "odbc_field_len", "odbc_field_scale", "odbc_field_name", "odbc_field_type", "odbc_field_num", "odbc_free_result", "odbc_gettypeinfo", "odbc_longreadlen", "odbc_next_result", "odbc_num_fields", "odbc_num_rows", "odbc_pconnect", "odbc_prepare", "odbc_result", "odbc_result_all", "odbc_rollback", "odbc_setoption", "odbc_specialcolumns", "odbc_statistics", "odbc_tables", "odbc_primarykeys", "odbc_columnprivileges", "odbc_tableprivileges", "odbc_foreignkeys", "odbc_procedures", "odbc_procedurecolumns", "odbc_do", "odbc_field_precision", "preg_match", "preg_match_all", "preg_replace", "preg_replace_callback", "preg_split", "preg_quote", "preg_grep", "preg_last_error", "session_name", "session_module_name", "session_save_path", "session_id", "session_regenerate_id", "session_decode", "session_register", "session_unregister", "session_is_registered", "session_encode", "session_start", "session_destroy", "session_unset", "session_set_save_handler", "session_cache_limiter", "session_cache_expire", "session_set_cookie_params", "session_get_cookie_params", "session_write_close", "session_commit", "spl_classes", "spl_autoload", "spl_autoload_extensions", "spl_autoload_register", "spl_autoload_unregister", "spl_autoload_functions", "spl_autoload_call", "class_parents", "class_implements", "spl_object_hash", "iterator_to_array", "iterator_count", "iterator_apply", "constant", "bin2hex", "sleep", "usleep", "flush", "wordwrap", "htmlspecialchars", "htmlentities", "html_entity_decode", "htmlspecialchars_decode", "get_html_translation_table", "sha1", "sha1_file", "md5", "md5_file", "crc32", "iptcparse", "iptcembed", "getimagesize", "image_type_to_mime_type", "image_type_to_extension", "phpinfo", "phpversion", "phpcredits", "php_logo_guid", "php_real_logo_guid", "php_egg_logo_guid", "zend_logo_guid", "php_sapi_name", "php_uname", "php_ini_scanned_files", "strnatcmp", "strnatcasecmp", "substr_count", "strspn", "strcspn", "strtok", "strtoupper", "strtolower", "strpos", "stripos", "strrpos", "strripos", "strrev", "hebrev", "hebrevc", "nl2br", "basename", "dirname", "pathinfo", "stripslashes", "stripcslashes", "strstr", "stristr", "strrchr", "str_shuffle", "str_word_count", "str_split", "strpbrk", "substr_compare", "strcoll", "substr", "substr_replace", "quotemeta", "ucfirst", "ucwords", "strtr", "addslashes", "addcslashes", "rtrim", "str_replace", "str_ireplace", "str_repeat", "count_chars", "chunk_split", "trim", "ltrim", "strip_tags", "similar_text", "explode", "implode", "setlocale", "localeconv", "soundex", "levenshtein", "chr", "ord", "parse_str", "str_pad", "chop", "strchr", "sprintf", "printf", "vprintf", "vsprintf", "fprintf", "vfprintf", "sscanf", "fscanf", "parse_url", "urlencode", "urldecode", "rawurlencode", "rawurldecode", "http_build_query", "unlink", "exec", "system", "escapeshellcmd", "escapeshellarg", "passthru", "shell_exec", "proc_open", "proc_close", "proc_terminate", "proc_get_status", "rand", "srand", "getrandmax", "mt_rand", "mt_srand", "mt_getrandmax", "getservbyname", "getservbyport", "getprotobyname", "getprotobynumber", "getmyuid", "getmygid", "getmypid", "getmyinode", "getlastmod", "base64_decode", "base64_encode", "convert_uuencode", "convert_uudecode", "abs", "ceil", "floor", "round", "sin", "cos", "tan", "asin", "acos", "atan", "atan2", "sinh", "cosh", "tanh", "pi", "is_finite", "is_nan", "is_infinite", "pow", "exp", "log", "log10", "sqrt", "hypot", "deg2rad", "rad2deg", "bindec", "hexdec", "octdec", "decbin", "decoct", "dechex", "base_convert", "number_format", "fmod", "ip2long", "long2ip", "getenv", "putenv", "microtime", "gettimeofday", "uniqid", "quoted_printable_decode", "convert_cyr_string", "get_current_user", "set_time_limit", "get_cfg_var", "magic_quotes_runtime", "set_magic_quotes_runtime", "get_magic_quotes_gpc", "get_magic_quotes_runtime", "import_request_variables", "error_log", "error_get_last", "call_user_func", "call_user_func_array", "call_user_method", "call_user_method_array", "serialize", "unserialize", "var_dump", "var_export", "debug_zval_dump", "print_r", "memory_get_usage", "memory_get_peak_usage", "register_shutdown_function", "register_tick_function", "unregister_tick_function", "highlight_file", "show_source", "highlight_string", "php_strip_whitespace", "ini_get", "ini_get_all", "ini_set", "ini_alter", "ini_restore", "get_include_path", "set_include_path", "restore_include_path", "setcookie", "setrawcookie", "header", "headers_sent", "headers_list", "connection_aborted", "connection_status", "ignore_user_abort", "parse_ini_file", "is_uploaded_file", "move_uploaded_file", "gethostbyaddr", "gethostbyname", "gethostbynamel", "intval", "floatval", "doubleval", "strval", "gettype", "settype", "is_null", "is_resource", "is_bool", "is_long", "is_float", "is_int", "is_integer", "is_double", "is_real", "is_numeric", "is_string", "is_array", "is_object", "is_scalar", "is_callable", "ereg", "ereg_replace", "eregi", "eregi_replace", "split", "spliti", "join", "sql_regcase", "dl", "pclose", "popen", "readfile", "rewind", "rmdir", "umask", "fclose", "feof", "fgetc", "fgets", "fgetss", "fread", "fopen", "fpassthru", "ftruncate", "fstat", "fseek", "ftell", "fflush", "fwrite", "fputs", "mkdir", "rename", "copy", "tempnam", "tmpfile", "file", "file_get_contents", "file_put_contents", "stream_select", "stream_context_create", "stream_context_set_params", "stream_context_set_option", "stream_context_get_options", "stream_context_get_default", "stream_filter_prepend", "stream_filter_append", "stream_filter_remove", "stream_socket_client", "stream_socket_server", "stream_socket_accept", "stream_socket_get_name", "stream_socket_recvfrom", "stream_socket_sendto", "stream_socket_enable_crypto", "stream_socket_shutdown", "stream_copy_to_stream", "stream_get_contents", "fgetcsv", "fputcsv", "flock", "get_meta_tags", "stream_set_write_buffer", "set_file_buffer", "set_socket_blocking", "stream_set_blocking", "socket_set_blocking", "stream_get_meta_data", "stream_get_line", "stream_wrapper_register", "stream_register_wrapper", "stream_wrapper_unregister", "stream_wrapper_restore", "stream_get_wrappers", "stream_get_transports", "get_headers", "stream_set_timeout", "socket_set_timeout", "socket_get_status", "realpath", "fsockopen", "pfsockopen", "pack", "unpack", "get_browser", "crypt", "opendir", "closedir", "chdir", "getcwd", "rewinddir", "readdir", "dir", "scandir", "glob", "fileatime", "filectime", "filegroup", "fileinode", "filemtime", "fileowner", "fileperms", "filesize", "filetype", "file_exists", "is_writable", "is_writeable", "is_readable", "is_executable", "is_file", "is_dir", "is_link", "stat", "lstat", "chown", "chgrp", "chmod", "touch", "clearstatcache", "disk_total_space", "disk_free_space", "diskfreespace", "mail", "ezmlm_hash", "openlog", "syslog", "closelog", "define_syslog_variables", "lcg_value", "metaphone", "ob_start", "ob_flush", "ob_clean", "ob_end_flush", "ob_end_clean", "ob_get_flush", "ob_get_clean", "ob_get_length", "ob_get_level", "ob_get_status", "ob_get_contents", "ob_implicit_flush", "ob_list_handlers", "ksort", "krsort", "natsort", "natcasesort", "asort", "arsort", "sort", "rsort", "usort", "uasort", "uksort", "shuffle", "array_walk", "array_walk_recursive", "count", "end", "prev", "next", "reset", "current", "key", "min", "max", "in_array", "array_search", "extract", "compact", "array_fill", "array_fill_keys", "range", "array_multisort", "array_push", "array_pop", "array_shift", "array_unshift", "array_splice", "array_slice", "array_merge", "array_merge_recursive", "array_keys", "array_values", "array_count_values", "array_reverse", "array_reduce", "array_pad", "array_flip", "array_change_key_case", "array_rand", "array_unique", "array_intersect", "array_intersect_key", "array_intersect_ukey", "array_uintersect", "array_intersect_assoc", "array_uintersect_assoc", "array_intersect_uassoc", "array_uintersect_uassoc", "array_diff", "array_diff_key", "array_diff_ukey", "array_udiff", "array_diff_assoc", "array_udiff_assoc", "array_diff_uassoc", "array_udiff_uassoc", "array_sum", "array_product", "array_filter", "array_map", "array_chunk", "array_combine", "array_key_exists", "pos", "sizeof", "key_exists", "assert", "assert_options", "version_compare", "str_rot13", "stream_get_filters", "stream_filter_register", "stream_bucket_make_writeable", "stream_bucket_prepend", "stream_bucket_append", "stream_bucket_new", "output_add_rewrite_var", "output_reset_rewrite_vars", "sys_get_temp_dir", "token_get_all", "token_name", "readgzfile", "gzrewind", "gzclose", "gzeof", "gzgetc", "gzgets", "gzgetss", "gzread", "gzopen", "gzpassthru", "gzseek", "gztell", "gzwrite", "gzputs", "gzfile", "gzcompress", "gzuncompress", "gzdeflate", "gzinflate", "gzencode", "ob_gzhandler", "zlib_get_coding_type", "libxml_set_streams_context", "libxml_use_internal_errors", "libxml_get_last_error", "libxml_clear_errors", "libxml_get_errors", "dom_import_simplexml", "simplexml_load_file", "simplexml_load_string", "simplexml_import_dom", "wddx_serialize_value", "wddx_serialize_vars", "wddx_packet_start", "wddx_packet_end", "wddx_add_vars", "wddx_deserialize", "xml_parser_create", "xml_parser_create_ns", "xml_set_object", "xml_set_element_handler", "xml_set_character_data_handler", "xml_set_processing_instruction_handler", "xml_set_default_handler", "xml_set_unparsed_entity_decl_handler", "xml_set_notation_decl_handler", "xml_set_external_entity_ref_handler", "xml_set_start_namespace_decl_handler", "xml_set_end_namespace_decl_handler", "xml_parse", "xml_parse_into_struct", "xml_get_error_code", "xml_error_string", "xml_get_current_line_number", "xml_get_current_column_number", "xml_get_current_byte_index", "xml_parser_free", "xml_parser_set_option", "xml_parser_get_option", "utf8_encode", "utf8_decode", "xmlwriter_open_uri", "xmlwriter_open_memory", "xmlwriter_set_indent", "xmlwriter_set_indent_string", "xmlwriter_start_comment", "xmlwriter_end_comment", "xmlwriter_start_attribute", "xmlwriter_end_attribute", "xmlwriter_write_attribute", "xmlwriter_start_attribute_ns", "xmlwriter_write_attribute_ns", "xmlwriter_start_element", "xmlwriter_end_element", "xmlwriter_full_end_element", "xmlwriter_start_element_ns", "xmlwriter_write_element", "xmlwriter_write_element_ns", "xmlwriter_start_pi", "xmlwriter_end_pi", "xmlwriter_write_pi", "xmlwriter_start_cdata", "xmlwriter_end_cdata", "xmlwriter_write_cdata", "xmlwriter_text", "xmlwriter_write_raw", "xmlwriter_start_document", "xmlwriter_end_document", "xmlwriter_write_comment", "xmlwriter_start_dtd", "xmlwriter_end_dtd", "xmlwriter_write_dtd", "xmlwriter_start_dtd_element", "xmlwriter_end_dtd_element", "xmlwriter_write_dtd_element", "xmlwriter_start_dtd_attlist", "xmlwriter_end_dtd_attlist", "xmlwriter_write_dtd_attlist", "xmlwriter_start_dtd_entity", "xmlwriter_end_dtd_entity", "xmlwriter_write_dtd_entity", "xmlwriter_output_memory", "xmlwriter_flush", "gd_info", "imagearc", "imageellipse", "imagechar", "imagecharup", "imagecolorat", "imagecolorallocate", "imagepalettecopy", "imagecreatefromstring", "imagecolorclosest", "imagecolordeallocate", "imagecolorresolve", "imagecolorexact", "imagecolorset", "imagecolortransparent", "imagecolorstotal", "imagecolorsforindex", "imagecopy", "imagecopymerge", "imagecopymergegray", "imagecopyresized", "imagecreate", "imagecreatetruecolor", "imageistruecolor", "imagetruecolortopalette", "imagesetthickness", "imagefilledarc", "imagefilledellipse", "imagealphablending", "imagesavealpha", "imagecolorallocatealpha", "imagecolorresolvealpha", "imagecolorclosestalpha", "imagecolorexactalpha", "imagecopyresampled", "imagegrabwindow", "imagegrabscreen", "imagerotate", "imageantialias", "imagesettile", "imagesetbrush", "imagesetstyle", "imagecreatefrompng", "imagecreatefromgif", "imagecreatefromjpeg", "imagecreatefromwbmp", "imagecreatefromxbm", "imagecreatefromgd", "imagecreatefromgd2", "imagecreatefromgd2part", "imagepng", "imagegif", "imagejpeg", "imagewbmp", "imagegd", "imagegd2", "imagedestroy", "imagegammacorrect", "imagefill", "imagefilledpolygon", "imagefilledrectangle", "imagefilltoborder", "imagefontwidth", "imagefontheight", "imageinterlace", "imageline", "imageloadfont", "imagepolygon", "imagerectangle", "imagesetpixel", "imagestring", "imagestringup", "imagesx", "imagesy", "imagedashedline", "imagettfbbox", "imagettftext", "imageftbbox", "imagefttext", "imagepsloadfont", "imagepsfreefont", "imagepsencodefont", "imagepsextendfont", "imagepsslantfont", "imagepstext", "imagepsbbox", "imagetypes", "jpeg2wbmp", "png2wbmp", "image2wbmp", "imagelayereffect", "imagecolormatch", "imagexbm", "imagefilter", "imageconvolution", "mb_convert_case", "mb_strtoupper", "mb_strtolower", "mb_language", "mb_internal_encoding", "mb_http_input", "mb_http_output", "mb_detect_order", "mb_substitute_character", "mb_parse_str", "mb_output_handler", "mb_preferred_mime_name", "mb_strlen", "mb_strpos", "mb_strrpos", "mb_stripos", "mb_strripos", "mb_strstr", "mb_strrchr", "mb_stristr", "mb_strrichr", "mb_substr_count", "mb_substr", "mb_strcut", "mb_strwidth", "mb_strimwidth", "mb_convert_encoding", "mb_detect_encoding", "mb_list_encodings", "mb_convert_kana", "mb_encode_mimeheader", "mb_decode_mimeheader", "mb_convert_variables", "mb_encode_numericentity", "mb_decode_numericentity", "mb_send_mail", "mb_get_info", "mb_check_encoding", "mb_regex_encoding", "mb_regex_set_options", "mb_ereg", "mb_eregi", "mb_ereg_replace", "mb_eregi_replace", "mb_split", "mb_ereg_match", "mb_ereg_search", "mb_ereg_search_pos", "mb_ereg_search_regs", "mb_ereg_search_init", "mb_ereg_search_getregs", "mb_ereg_search_getpos", "mb_ereg_search_setpos", "mbregex_encoding", "mbereg", "mberegi", "mbereg_replace", "mberegi_replace", "mbsplit", "mbereg_match", "mbereg_search", "mbereg_search_pos", "mbereg_search_regs", "mbereg_search_init", "mbereg_search_getregs", "mbereg_search_getpos", "mbereg_search_setpos", "mysql_connect", "mysql_pconnect", "mysql_close", "mysql_select_db", "mysql_query", "mysql_unbuffered_query", "mysql_db_query", "mysql_list_dbs", "mysql_list_tables", "mysql_list_fields", "mysql_list_processes", "mysql_error", "mysql_errno", "mysql_affected_rows", "mysql_insert_id", "mysql_result", "mysql_num_rows", "mysql_num_fields", "mysql_fetch_row", "mysql_fetch_array", "mysql_fetch_assoc", "mysql_fetch_object", "mysql_data_seek", "mysql_fetch_lengths", "mysql_fetch_field", "mysql_field_seek", "mysql_free_result", "mysql_field_name", "mysql_field_table", "mysql_field_len", "mysql_field_type", "mysql_field_flags", "mysql_escape_string", "mysql_real_escape_string", "mysql_stat", "mysql_thread_id", "mysql_client_encoding", "mysql_ping", "mysql_get_client_info", "mysql_get_host_info", "mysql_get_proto_info", "mysql_get_server_info", "mysql_info", "mysql_set_charset", "mysql", "mysql_fieldname", "mysql_fieldtable", "mysql_fieldlen", "mysql_fieldtype", "mysql_fieldflags", "mysql_selectdb", "mysql_freeresult", "mysql_numfields", "mysql_numrows", "mysql_listdbs", "mysql_listtables", "mysql_listfields", "mysql_db_name", "mysql_dbname", "mysql_tablename", "mysql_table_name", "mysqli_affected_rows", "mysqli_autocommit", "mysqli_change_user", "mysqli_character_set_name", "mysqli_close", "mysqli_commit", "mysqli_connect", "mysqli_connect_errno", "mysqli_connect_error", "mysqli_data_seek", "mysqli_debug", "mysqli_disable_reads_from_master", "mysqli_disable_rpl_parse", "mysqli_dump_debug_info", "mysqli_enable_reads_from_master", "mysqli_enable_rpl_parse", "mysqli_embedded_server_end", "mysqli_embedded_server_start", "mysqli_errno", "mysqli_error", "mysqli_stmt_execute", "mysqli_execute", "mysqli_fetch_field", "mysqli_fetch_fields", "mysqli_fetch_field_direct", "mysqli_fetch_lengths", "mysqli_fetch_array", "mysqli_fetch_assoc", "mysqli_fetch_object", "mysqli_fetch_row", "mysqli_field_count", "mysqli_field_seek", "mysqli_field_tell", "mysqli_free_result", "mysqli_get_charset", "mysqli_get_client_info", "mysqli_get_client_version", "mysqli_get_host_info", "mysqli_get_proto_info", "mysqli_get_server_info", "mysqli_get_server_version", "mysqli_get_warnings", "mysqli_init", "mysqli_info", "mysqli_insert_id", "mysqli_kill", "mysqli_set_local_infile_default", "mysqli_set_local_infile_handler", "mysqli_master_query", "mysqli_more_results", "mysqli_multi_query", "mysqli_next_result", "mysqli_num_fields", "mysqli_num_rows", "mysqli_options", "mysqli_ping", "mysqli_prepare", "mysqli_report", "mysqli_query", "mysqli_real_connect", "mysqli_real_escape_string", "mysqli_real_query", "mysqli_rollback", "mysqli_rpl_parse_enabled", "mysqli_rpl_probe", "mysqli_rpl_query_type", "mysqli_select_db", "mysqli_set_charset", "mysqli_stmt_attr_get", "mysqli_stmt_attr_set", "mysqli_stmt_field_count", "mysqli_stmt_init", "mysqli_stmt_prepare", "mysqli_stmt_result_metadata", "mysqli_stmt_send_long_data", "mysqli_stmt_bind_param", "mysqli_stmt_bind_result", "mysqli_stmt_fetch", "mysqli_stmt_free_result", "mysqli_stmt_get_warnings", "mysqli_stmt_insert_id", "mysqli_stmt_reset", "mysqli_stmt_param_count", "mysqli_send_query", "mysqli_slave_query", "mysqli_sqlstate", "mysqli_ssl_set", "mysqli_stat", "mysqli_stmt_affected_rows", "mysqli_stmt_close", "mysqli_stmt_data_seek", "mysqli_stmt_errno", "mysqli_stmt_error", "mysqli_stmt_num_rows", "mysqli_stmt_sqlstate", "mysqli_store_result", "mysqli_stmt_store_result", "mysqli_thread_id", "mysqli_thread_safe", "mysqli_use_result", "mysqli_warning_count", "mysqli_bind_param", "mysqli_bind_result", "mysqli_client_encoding", "mysqli_escape_string", "mysqli_fetch", "mysqli_param_count", "mysqli_get_metadata", "mysqli_send_long_data", "mysqli_set_opt", "pdo_drivers", "socket_select", "socket_create", "socket_create_listen", "socket_accept", "socket_set_nonblock", "socket_set_block", "socket_listen", "socket_close", "socket_write", "socket_read", "socket_getsockname", "socket_getpeername", "socket_connect", "socket_strerror", "socket_bind", "socket_recv", "socket_send", "socket_recvfrom", "socket_sendto", "socket_get_option", "socket_set_option", "socket_shutdown", "socket_last_error", "socket_clear_error", "socket_getopt", "socket_setopt", "eaccelerator_put", "eaccelerator_get", "eaccelerator_rm", "eaccelerator_gc", "eaccelerator_lock", "eaccelerator_unlock", "eaccelerator_caching", "eaccelerator_optimizer", "eaccelerator_clear", "eaccelerator_clean", "eaccelerator_info", "eaccelerator_purge", "eaccelerator_cached_scripts", "eaccelerator_removed_scripts", "eaccelerator_list_keys", "eaccelerator_encode", "eaccelerator_load", "_eaccelerator_loader_file", "_eaccelerator_loader_line", "eaccelerator_set_session_handlers", "_eaccelerator_output_handler", "eaccelerator_cache_page", "eaccelerator_rm_page", "eaccelerator_cache_output", "eaccelerator_cache_result", "xdebug_get_stack_depth", "xdebug_get_function_stack", "xdebug_print_function_stack", "xdebug_get_declared_vars", "xdebug_call_class", "xdebug_call_function", "xdebug_call_file", "xdebug_call_line", "xdebug_var_dump", "xdebug_debug_zval", "xdebug_debug_zval_stdout", "xdebug_enable", "xdebug_disable", "xdebug_is_enabled", "xdebug_break", "xdebug_start_trace", "xdebug_stop_trace", "xdebug_get_tracefile_name", "xdebug_get_profiler_filename", "xdebug_dump_aggr_profiling_data", "xdebug_clear_aggr_profiling_data", "xdebug_memory_usage", "xdebug_peak_memory_usage", "xdebug_time_index", "xdebug_start_error_collection", "xdebug_stop_error_collection", "xdebug_get_collected_errors", "xdebug_start_code_coverage", "xdebug_stop_code_coverage", "xdebug_get_code_coverage", "xdebug_get_function_count", "xdebug_dump_superglobals", "_", /* alias for gettext()*/ "get_called_class","class_alias","gc_collect_cycles","gc_enabled","gc_enable", "gc_disable","date_create_from_format","date_parse_from_format", "date_get_last_errors","date_add","date_sub","date_diff","date_timestamp_set", "date_timestamp_get","timezone_location_get","timezone_version_get", "date_interval_create_from_date_string","date_interval_format", "libxml_disable_entity_loader","openssl_pkey_free","openssl_pkey_new", "openssl_pkey_export","openssl_pkey_export_to_file","openssl_pkey_get_private", "openssl_pkey_get_public","openssl_pkey_get_details","openssl_free_key", "openssl_get_privatekey","openssl_get_publickey","openssl_x509_read", "openssl_x509_free","openssl_x509_parse","openssl_x509_checkpurpose", "openssl_x509_check_private_key","openssl_x509_export","openssl_x509_export_to_file", "openssl_pkcs12_export","openssl_pkcs12_export_to_file","openssl_pkcs12_read", "openssl_csr_new","openssl_csr_export","openssl_csr_export_to_file", "openssl_csr_sign","openssl_csr_get_subject","openssl_csr_get_public_key", "openssl_digest","openssl_encrypt","openssl_decrypt","openssl_cipher_iv_length", "openssl_sign","openssl_verify","openssl_seal","openssl_open","openssl_pkcs7_verify", "openssl_pkcs7_decrypt","openssl_pkcs7_sign","openssl_pkcs7_encrypt", "openssl_private_encrypt","openssl_private_decrypt","openssl_public_encrypt", "openssl_public_decrypt","openssl_get_md_methods","openssl_get_cipher_methods", "openssl_dh_compute_key","openssl_random_pseudo_bytes","openssl_error_string", "preg_filter","bzopen","bzread","bzwrite","bzflush","bzclose","bzerrno", "bzerrstr","bzerror","bzcompress","bzdecompress","curl_init","curl_copy_handle", "curl_version","curl_setopt","curl_setopt_array","curl_exec","curl_getinfo", "curl_error","curl_errno","curl_close","curl_multi_init","curl_multi_add_handle", "curl_multi_remove_handle","curl_multi_select","curl_multi_exec","curl_multi_getcontent", "curl_multi_info_read","curl_multi_close","exif_read_data","read_exif_data", "exif_tagname","exif_thumbnail","exif_imagetype","ftp_ssl_connect", "imagecolorclosesthwb","imagecreatefromxpm","textdomain","gettext","dgettext", "dcgettext","bindtextdomain","ngettext","dngettext","dcngettext", "bind_textdomain_codeset","hash_copy","imap_open","imap_reopen","imap_close", "imap_num_msg","imap_num_recent","imap_headers","imap_headerinfo", "imap_rfc822_parse_headers","imap_rfc822_write_address","imap_rfc822_parse_adrlist", "imap_body","imap_bodystruct","imap_fetchbody","imap_savebody","imap_fetchheader", "imap_fetchstructure","imap_gc","imap_expunge","imap_delete","imap_undelete", "imap_check","imap_listscan","imap_mail_copy","imap_mail_move","imap_mail_compose", "imap_createmailbox","imap_renamemailbox","imap_deletemailbox","imap_subscribe", "imap_unsubscribe","imap_append","imap_ping","imap_base64","imap_qprint","imap_8bit", "imap_binary","imap_utf8","imap_status","imap_mailboxmsginfo","imap_setflag_full", "imap_clearflag_full","imap_sort","imap_uid","imap_msgno","imap_list","imap_lsub", "imap_fetch_overview","imap_alerts","imap_errors","imap_last_error","imap_search", "imap_utf7_decode","imap_utf7_encode","imap_mime_header_decode","imap_thread", "imap_timeout","imap_get_quota","imap_get_quotaroot","imap_set_quota","imap_setacl", "imap_getacl","imap_mail","imap_header","imap_listmailbox","imap_getmailboxes", "imap_scanmailbox","imap_listsubscribed","imap_getsubscribed","imap_fetchtext", "imap_scan","imap_create","imap_rename","json_last_error","mb_encoding_aliases", "mcrypt_ecb","mcrypt_cbc","mcrypt_cfb","mcrypt_ofb","mcrypt_get_key_size", "mcrypt_get_block_size","mcrypt_get_cipher_name","mcrypt_create_iv","mcrypt_list_algorithms", "mcrypt_list_modes","mcrypt_get_iv_size","mcrypt_encrypt","mcrypt_decrypt", "mcrypt_module_open","mcrypt_generic_init","mcrypt_generic","mdecrypt_generic", "mcrypt_generic_end","mcrypt_generic_deinit","mcrypt_enc_self_test", "mcrypt_enc_is_block_algorithm_mode","mcrypt_enc_is_block_algorithm", "mcrypt_enc_is_block_mode","mcrypt_enc_get_block_size","mcrypt_enc_get_key_size", "mcrypt_enc_get_supported_key_sizes","mcrypt_enc_get_iv_size", "mcrypt_enc_get_algorithms_name","mcrypt_enc_get_modes_name","mcrypt_module_self_test", "mcrypt_module_is_block_algorithm_mode","mcrypt_module_is_block_algorithm", "mcrypt_module_is_block_mode","mcrypt_module_get_algo_block_size", "mcrypt_module_get_algo_key_size","mcrypt_module_get_supported_key_sizes", "mcrypt_module_close","mysqli_refresh","posix_kill","posix_getpid","posix_getppid", "posix_getuid","posix_setuid","posix_geteuid","posix_seteuid","posix_getgid", "posix_setgid","posix_getegid","posix_setegid","posix_getgroups","posix_getlogin", "posix_getpgrp","posix_setsid","posix_setpgid","posix_getpgid","posix_getsid", "posix_uname","posix_times","posix_ctermid","posix_ttyname","posix_isatty", "posix_getcwd","posix_mkfifo","posix_mknod","posix_access","posix_getgrnam", "posix_getgrgid","posix_getpwnam","posix_getpwuid","posix_getrlimit", "posix_get_last_error","posix_errno","posix_strerror","posix_initgroups", "pspell_new","pspell_new_personal","pspell_new_config","pspell_check", "pspell_suggest","pspell_store_replacement","pspell_add_to_personal", "pspell_add_to_session","pspell_clear_session","pspell_save_wordlist", "pspell_config_create","pspell_config_runtogether","pspell_config_mode", "pspell_config_ignore","pspell_config_personal","pspell_config_dict_dir", "pspell_config_data_dir","pspell_config_repl","pspell_config_save_repl", "snmpget","snmpgetnext","snmpwalk","snmprealwalk","snmpwalkoid", "snmp_get_quick_print","snmp_set_quick_print","snmp_set_enum_print", "snmp_set_oid_output_format","snmp_set_oid_numeric_print","snmpset", "snmp2_get","snmp2_getnext","snmp2_walk","snmp2_real_walk","snmp2_set", "snmp3_get","snmp3_getnext","snmp3_walk","snmp3_real_walk","snmp3_set", "snmp_set_valueretrieval","snmp_get_valueretrieval","snmp_read_mib", "use_soap_error_handler","is_soap_fault","socket_create_pair","time_nanosleep", "time_sleep_until","strptime","php_ini_loaded_file","money_format","lcfirst", "nl_langinfo","str_getcsv","readlink","linkinfo","symlink","link","proc_nice", "atanh","asinh","acosh","expm1","log1p","inet_ntop","inet_pton","getopt", "sys_getloadavg","getrusage","quoted_printable_encode","forward_static_call", "forward_static_call_array","header_remove","parse_ini_string","gethostname", "dns_check_record","checkdnsrr","dns_get_mx","getmxrr","dns_get_record", "stream_context_get_params","stream_context_set_default","stream_socket_pair", "stream_supports_lock","stream_set_read_buffer","stream_resolve_include_path", "stream_is_local","fnmatch","chroot","lchown","lchgrp","realpath_cache_size", "realpath_cache_get","array_replace","array_replace_recursive","ftok","xmlrpc_encode", "xmlrpc_decode","xmlrpc_decode_request","xmlrpc_encode_request","xmlrpc_get_type", "xmlrpc_set_type","xmlrpc_is_fault","xmlrpc_server_create","xmlrpc_server_destroy", "xmlrpc_server_register_method","xmlrpc_server_call_method", "xmlrpc_parse_method_descriptions","xmlrpc_server_add_introspection_data", "xmlrpc_server_register_introspection_callback","zip_open","zip_close", "zip_read","zip_entry_open","zip_entry_close","zip_entry_read","zip_entry_filesize", "zip_entry_name","zip_entry_compressedsize","zip_entry_compressionmethod", "svn_checkout","svn_cat","svn_ls","svn_log","svn_auth_set_parameter", "svn_auth_get_parameter","svn_client_version","svn_config_ensure","svn_diff", "svn_cleanup","svn_revert","svn_resolved","svn_commit","svn_lock","svn_unlock", "svn_add","svn_status","svn_update","svn_import","svn_info","svn_export", "svn_copy","svn_switch","svn_blame","svn_delete","svn_mkdir","svn_move", "svn_proplist","svn_propget","svn_repos_create","svn_repos_recover", "svn_repos_hotcopy","svn_repos_open","svn_repos_fs", "svn_repos_fs_begin_txn_for_commit","svn_repos_fs_commit_txn", "svn_fs_revision_root","svn_fs_check_path","svn_fs_revision_prop", "svn_fs_dir_entries","svn_fs_node_created_rev","svn_fs_youngest_rev", "svn_fs_file_contents","svn_fs_file_length","svn_fs_txn_root","svn_fs_make_file", "svn_fs_make_dir","svn_fs_apply_text","svn_fs_copy","svn_fs_delete", "svn_fs_begin_txn2","svn_fs_is_dir","svn_fs_is_file","svn_fs_node_prop", "svn_fs_change_node_prop","svn_fs_contents_changed","svn_fs_props_changed", "svn_fs_abort_txn","sqlite_open","sqlite_popen","sqlite_close","sqlite_query", "sqlite_exec","sqlite_array_query","sqlite_single_query","sqlite_fetch_array", "sqlite_fetch_object","sqlite_fetch_single","sqlite_fetch_string", "sqlite_fetch_all","sqlite_current","sqlite_column","sqlite_libversion", "sqlite_libencoding","sqlite_changes","sqlite_last_insert_rowid", "sqlite_num_rows","sqlite_num_fields","sqlite_field_name","sqlite_seek", "sqlite_rewind","sqlite_next","sqlite_prev","sqlite_valid","sqlite_has_more", "sqlite_has_prev","sqlite_escape_string","sqlite_busy_timeout","sqlite_last_error", "sqlite_error_string","sqlite_unbuffered_query","sqlite_create_aggregate", "sqlite_create_function","sqlite_factory","sqlite_udf_encode_binary", "sqlite_udf_decode_binary","sqlite_fetch_column_types" ].forEach(function(element, index, array) { result[element] = token("t_string", "php-predefined-function"); }); // output of get_defined_constants(). Differs significantly from http://php.net/manual/en/reserved.constants.php [ "E_ERROR", "E_RECOVERABLE_ERROR", "E_WARNING", "E_PARSE", "E_NOTICE", "E_STRICT", "E_CORE_ERROR", "E_CORE_WARNING", "E_COMPILE_ERROR", "E_COMPILE_WARNING", "E_USER_ERROR", "E_USER_WARNING", "E_USER_NOTICE", "E_ALL", "TRUE", "FALSE", "NULL", "ZEND_THREAD_SAFE", "PHP_VERSION", "PHP_OS", "PHP_SAPI", "DEFAULT_INCLUDE_PATH", "PEAR_INSTALL_DIR", "PEAR_EXTENSION_DIR", "PHP_EXTENSION_DIR", "PHP_PREFIX", "PHP_BINDIR", "PHP_LIBDIR", "PHP_DATADIR", "PHP_SYSCONFDIR", "PHP_LOCALSTATEDIR", "PHP_CONFIG_FILE_PATH", "PHP_CONFIG_FILE_SCAN_DIR", "PHP_SHLIB_SUFFIX", "PHP_EOL", "PHP_EOL", "PHP_INT_MAX", "PHP_INT_SIZE", "PHP_OUTPUT_HANDLER_START", "PHP_OUTPUT_HANDLER_CONT", "PHP_OUTPUT_HANDLER_END", "UPLOAD_ERR_OK", "UPLOAD_ERR_INI_SIZE", "UPLOAD_ERR_FORM_SIZE", "UPLOAD_ERR_PARTIAL", "UPLOAD_ERR_NO_FILE", "UPLOAD_ERR_NO_TMP_DIR", "UPLOAD_ERR_CANT_WRITE", "UPLOAD_ERR_EXTENSION", "CAL_GREGORIAN", "CAL_JULIAN", "CAL_JEWISH", "CAL_FRENCH", "CAL_NUM_CALS", "CAL_DOW_DAYNO", "CAL_DOW_SHORT", "CAL_DOW_LONG", "CAL_MONTH_GREGORIAN_SHORT", "CAL_MONTH_GREGORIAN_LONG", "CAL_MONTH_JULIAN_SHORT", "CAL_MONTH_JULIAN_LONG", "CAL_MONTH_JEWISH", "CAL_MONTH_FRENCH", "CAL_EASTER_DEFAULT", "CAL_EASTER_ROMAN", "CAL_EASTER_ALWAYS_GREGORIAN", "CAL_EASTER_ALWAYS_JULIAN", "CAL_JEWISH_ADD_ALAFIM_GERESH", "CAL_JEWISH_ADD_ALAFIM", "CAL_JEWISH_ADD_GERESHAYIM", "CLSCTX_INPROC_SERVER", "CLSCTX_INPROC_HANDLER", "CLSCTX_LOCAL_SERVER", "CLSCTX_REMOTE_SERVER", "CLSCTX_SERVER", "CLSCTX_ALL", "VT_NULL", "VT_EMPTY", "VT_UI1", "VT_I1", "VT_UI2", "VT_I2", "VT_UI4", "VT_I4", "VT_R4", "VT_R8", "VT_BOOL", "VT_ERROR", "VT_CY", "VT_DATE", "VT_BSTR", "VT_DECIMAL", "VT_UNKNOWN", "VT_DISPATCH", "VT_VARIANT", "VT_INT", "VT_UINT", "VT_ARRAY", "VT_BYREF", "CP_ACP", "CP_MACCP", "CP_OEMCP", "CP_UTF7", "CP_UTF8", "CP_SYMBOL", "CP_THREAD_ACP", "VARCMP_LT", "VARCMP_EQ", "VARCMP_GT", "VARCMP_NULL", "NORM_IGNORECASE", "NORM_IGNORENONSPACE", "NORM_IGNORESYMBOLS", "NORM_IGNOREWIDTH", "NORM_IGNOREKANATYPE", "DISP_E_DIVBYZERO", "DISP_E_OVERFLOW", "DISP_E_BADINDEX", "MK_E_UNAVAILABLE", "INPUT_POST", "INPUT_GET", "INPUT_COOKIE", "INPUT_ENV", "INPUT_SERVER", "INPUT_SESSION", "INPUT_REQUEST", "FILTER_FLAG_NONE", "FILTER_REQUIRE_SCALAR", "FILTER_REQUIRE_ARRAY", "FILTER_FORCE_ARRAY", "FILTER_NULL_ON_FAILURE", "FILTER_VALIDATE_INT", "FILTER_VALIDATE_BOOLEAN", "FILTER_VALIDATE_FLOAT", "FILTER_VALIDATE_REGEXP", "FILTER_VALIDATE_URL", "FILTER_VALIDATE_EMAIL", "FILTER_VALIDATE_IP", "FILTER_DEFAULT", "FILTER_UNSAFE_RAW", "FILTER_SANITIZE_STRING", "FILTER_SANITIZE_STRIPPED", "FILTER_SANITIZE_ENCODED", "FILTER_SANITIZE_SPECIAL_CHARS", "FILTER_SANITIZE_EMAIL", "FILTER_SANITIZE_URL", "FILTER_SANITIZE_NUMBER_INT", "FILTER_SANITIZE_NUMBER_FLOAT", "FILTER_SANITIZE_MAGIC_QUOTES", "FILTER_CALLBACK", "FILTER_FLAG_ALLOW_OCTAL", "FILTER_FLAG_ALLOW_HEX", "FILTER_FLAG_STRIP_LOW", "FILTER_FLAG_STRIP_HIGH", "FILTER_FLAG_ENCODE_LOW", "FILTER_FLAG_ENCODE_HIGH", "FILTER_FLAG_ENCODE_AMP", "FILTER_FLAG_NO_ENCODE_QUOTES", "FILTER_FLAG_EMPTY_STRING_NULL", "FILTER_FLAG_ALLOW_FRACTION", "FILTER_FLAG_ALLOW_THOUSAND", "FILTER_FLAG_ALLOW_SCIENTIFIC", "FILTER_FLAG_SCHEME_REQUIRED", "FILTER_FLAG_HOST_REQUIRED", "FILTER_FLAG_PATH_REQUIRED", "FILTER_FLAG_QUERY_REQUIRED", "FILTER_FLAG_IPV4", "FILTER_FLAG_IPV6", "FILTER_FLAG_NO_RES_RANGE", "FILTER_FLAG_NO_PRIV_RANGE", "FTP_ASCII", "FTP_TEXT", "FTP_BINARY", "FTP_IMAGE", "FTP_AUTORESUME", "FTP_TIMEOUT_SEC", "FTP_AUTOSEEK", "FTP_FAILED", "FTP_FINISHED", "FTP_MOREDATA", "HASH_HMAC", "ICONV_IMPL", "ICONV_VERSION", "ICONV_MIME_DECODE_STRICT", "ICONV_MIME_DECODE_CONTINUE_ON_ERROR", "ODBC_TYPE", "ODBC_BINMODE_PASSTHRU", "ODBC_BINMODE_RETURN", "ODBC_BINMODE_CONVERT", "SQL_ODBC_CURSORS", "SQL_CUR_USE_DRIVER", "SQL_CUR_USE_IF_NEEDED", "SQL_CUR_USE_ODBC", "SQL_CONCURRENCY", "SQL_CONCUR_READ_ONLY", "SQL_CONCUR_LOCK", "SQL_CONCUR_ROWVER", "SQL_CONCUR_VALUES", "SQL_CURSOR_TYPE", "SQL_CURSOR_FORWARD_ONLY", "SQL_CURSOR_KEYSET_DRIVEN", "SQL_CURSOR_DYNAMIC", "SQL_CURSOR_STATIC", "SQL_KEYSET_SIZE", "SQL_FETCH_FIRST", "SQL_FETCH_NEXT", "SQL_CHAR", "SQL_VARCHAR", "SQL_LONGVARCHAR", "SQL_DECIMAL", "SQL_NUMERIC", "SQL_BIT", "SQL_TINYINT", "SQL_SMALLINT", "SQL_INTEGER", "SQL_BIGINT", "SQL_REAL", "SQL_FLOAT", "SQL_DOUBLE", "SQL_BINARY", "SQL_VARBINARY", "SQL_LONGVARBINARY", "SQL_DATE", "SQL_TIME", "SQL_TIMESTAMP", "PREG_PATTERN_ORDER", "PREG_SET_ORDER", "PREG_OFFSET_CAPTURE", "PREG_SPLIT_NO_EMPTY", "PREG_SPLIT_DELIM_CAPTURE", "PREG_SPLIT_OFFSET_CAPTURE", "PREG_GREP_INVERT", "PREG_NO_ERROR", "PREG_INTERNAL_ERROR", "PREG_BACKTRACK_LIMIT_ERROR", "PREG_RECURSION_LIMIT_ERROR", "PREG_BAD_UTF8_ERROR", "DATE_ATOM", "DATE_COOKIE", "DATE_ISO8601", "DATE_RFC822", "DATE_RFC850", "DATE_RFC1036", "DATE_RFC1123", "DATE_RFC2822", "DATE_RFC3339", "DATE_RSS", "DATE_W3C", "SUNFUNCS_RET_TIMESTAMP", "SUNFUNCS_RET_STRING", "SUNFUNCS_RET_DOUBLE", "LIBXML_VERSION", "LIBXML_DOTTED_VERSION", "LIBXML_NOENT", "LIBXML_DTDLOAD", "LIBXML_DTDATTR", "LIBXML_DTDVALID", "LIBXML_NOERROR", "LIBXML_NOWARNING", "LIBXML_NOBLANKS", "LIBXML_XINCLUDE", "LIBXML_NSCLEAN", "LIBXML_NOCDATA", "LIBXML_NONET", "LIBXML_COMPACT", "LIBXML_NOXMLDECL", "LIBXML_NOEMPTYTAG", "LIBXML_ERR_NONE", "LIBXML_ERR_WARNING", "LIBXML_ERR_ERROR", "LIBXML_ERR_FATAL", "CONNECTION_ABORTED", "CONNECTION_NORMAL", "CONNECTION_TIMEOUT", "INI_USER", "INI_PERDIR", "INI_SYSTEM", "INI_ALL", "PHP_URL_SCHEME", "PHP_URL_HOST", "PHP_URL_PORT", "PHP_URL_USER", "PHP_URL_PASS", "PHP_URL_PATH", "PHP_URL_QUERY", "PHP_URL_FRAGMENT", "M_E", "M_LOG2E", "M_LOG10E", "M_LN2", "M_LN10", "M_PI", "M_PI_2", "M_PI_4", "M_1_PI", "M_2_PI", "M_SQRTPI", "M_2_SQRTPI", "M_LNPI", "M_EULER", "M_SQRT2", "M_SQRT1_2", "M_SQRT3", "INF", "NAN", "INFO_GENERAL", "INFO_CREDITS", "INFO_CONFIGURATION", "INFO_MODULES", "INFO_ENVIRONMENT", "INFO_VARIABLES", "INFO_LICENSE", "INFO_ALL", "CREDITS_GROUP", "CREDITS_GENERAL", "CREDITS_SAPI", "CREDITS_MODULES", "CREDITS_DOCS", "CREDITS_FULLPAGE", "CREDITS_QA", "CREDITS_ALL", "HTML_SPECIALCHARS", "HTML_ENTITIES", "ENT_COMPAT", "ENT_QUOTES", "ENT_NOQUOTES", "STR_PAD_LEFT", "STR_PAD_RIGHT", "STR_PAD_BOTH", "PATHINFO_DIRNAME", "PATHINFO_BASENAME", "PATHINFO_EXTENSION", "PATHINFO_FILENAME", "CHAR_MAX", "LC_CTYPE", "LC_NUMERIC", "LC_TIME", "LC_COLLATE", "LC_MONETARY", "LC_ALL", "SEEK_SET", "SEEK_CUR", "SEEK_END", "LOCK_SH", "LOCK_EX", "LOCK_UN", "LOCK_NB", "STREAM_NOTIFY_CONNECT", "STREAM_NOTIFY_AUTH_REQUIRED", "STREAM_NOTIFY_AUTH_RESULT", "STREAM_NOTIFY_MIME_TYPE_IS", "STREAM_NOTIFY_FILE_SIZE_IS", "STREAM_NOTIFY_REDIRECTED", "STREAM_NOTIFY_PROGRESS", "STREAM_NOTIFY_FAILURE", "STREAM_NOTIFY_COMPLETED", "STREAM_NOTIFY_RESOLVE", "STREAM_NOTIFY_SEVERITY_INFO", "STREAM_NOTIFY_SEVERITY_WARN", "STREAM_NOTIFY_SEVERITY_ERR", "STREAM_FILTER_READ", "STREAM_FILTER_WRITE", "STREAM_FILTER_ALL", "STREAM_CLIENT_PERSISTENT", "STREAM_CLIENT_ASYNC_CONNECT", "STREAM_CLIENT_CONNECT", "STREAM_CRYPTO_METHOD_SSLv2_CLIENT", "STREAM_CRYPTO_METHOD_SSLv3_CLIENT", "STREAM_CRYPTO_METHOD_SSLv23_CLIENT", "STREAM_CRYPTO_METHOD_TLS_CLIENT", "STREAM_CRYPTO_METHOD_SSLv2_SERVER", "STREAM_CRYPTO_METHOD_SSLv3_SERVER", "STREAM_CRYPTO_METHOD_SSLv23_SERVER", "STREAM_CRYPTO_METHOD_TLS_SERVER", "STREAM_SHUT_RD", "STREAM_SHUT_WR", "STREAM_SHUT_RDWR", "STREAM_PF_INET", "STREAM_PF_INET6", "STREAM_PF_UNIX", "STREAM_IPPROTO_IP", "STREAM_IPPROTO_TCP", "STREAM_IPPROTO_UDP", "STREAM_IPPROTO_ICMP", "STREAM_IPPROTO_RAW", "STREAM_SOCK_STREAM", "STREAM_SOCK_DGRAM", "STREAM_SOCK_RAW", "STREAM_SOCK_SEQPACKET", "STREAM_SOCK_RDM", "STREAM_PEEK", "STREAM_OOB", "STREAM_SERVER_BIND", "STREAM_SERVER_LISTEN", "FILE_USE_INCLUDE_PATH", "FILE_IGNORE_NEW_LINES", "FILE_SKIP_EMPTY_LINES", "FILE_APPEND", "FILE_NO_DEFAULT_CONTEXT", "PSFS_PASS_ON", "PSFS_FEED_ME", "PSFS_ERR_FATAL", "PSFS_FLAG_NORMAL", "PSFS_FLAG_FLUSH_INC", "PSFS_FLAG_FLUSH_CLOSE", "CRYPT_SALT_LENGTH", "CRYPT_STD_DES", "CRYPT_EXT_DES", "CRYPT_MD5", "CRYPT_BLOWFISH", "DIRECTORY_SEPARATOR", "PATH_SEPARATOR", "GLOB_BRACE", "GLOB_MARK", "GLOB_NOSORT", "GLOB_NOCHECK", "GLOB_NOESCAPE", "GLOB_ERR", "GLOB_ONLYDIR", "LOG_EMERG", "LOG_ALERT", "LOG_CRIT", "LOG_ERR", "LOG_WARNING", "LOG_NOTICE", "LOG_INFO", "LOG_DEBUG", "LOG_KERN", "LOG_USER", "LOG_MAIL", "LOG_DAEMON", "LOG_AUTH", "LOG_SYSLOG", "LOG_LPR", "LOG_NEWS", "LOG_UUCP", "LOG_CRON", "LOG_AUTHPRIV", "LOG_PID", "LOG_CONS", "LOG_ODELAY", "LOG_NDELAY", "LOG_NOWAIT", "LOG_PERROR", "EXTR_OVERWRITE", "EXTR_SKIP", "EXTR_PREFIX_SAME", "EXTR_PREFIX_ALL", "EXTR_PREFIX_INVALID", "EXTR_PREFIX_IF_EXISTS", "EXTR_IF_EXISTS", "EXTR_REFS", "SORT_ASC", "SORT_DESC", "SORT_REGULAR", "SORT_NUMERIC", "SORT_STRING", "SORT_LOCALE_STRING", "CASE_LOWER", "CASE_UPPER", "COUNT_NORMAL", "COUNT_RECURSIVE", "ASSERT_ACTIVE", "ASSERT_CALLBACK", "ASSERT_BAIL", "ASSERT_WARNING", "ASSERT_QUIET_EVAL", "STREAM_USE_PATH", "STREAM_IGNORE_URL", "STREAM_ENFORCE_SAFE_MODE", "STREAM_REPORT_ERRORS", "STREAM_MUST_SEEK", "STREAM_URL_STAT_LINK", "STREAM_URL_STAT_QUIET", "STREAM_MKDIR_RECURSIVE", "IMAGETYPE_GIF", "IMAGETYPE_JPEG", "IMAGETYPE_PNG", "IMAGETYPE_SWF", "IMAGETYPE_PSD", "IMAGETYPE_BMP", "IMAGETYPE_TIFF_II", "IMAGETYPE_TIFF_MM", "IMAGETYPE_JPC", "IMAGETYPE_JP2", "IMAGETYPE_JPX", "IMAGETYPE_JB2", "IMAGETYPE_SWC", "IMAGETYPE_IFF", "IMAGETYPE_WBMP", "IMAGETYPE_JPEG2000", "IMAGETYPE_XBM", "T_INCLUDE", "T_INCLUDE_ONCE", "T_EVAL", "T_REQUIRE", "T_REQUIRE_ONCE", "T_LOGICAL_OR", "T_LOGICAL_XOR", "T_LOGICAL_AND", "T_PRINT", "T_PLUS_EQUAL", "T_MINUS_EQUAL", "T_MUL_EQUAL", "T_DIV_EQUAL", "T_CONCAT_EQUAL", "T_MOD_EQUAL", "T_AND_EQUAL", "T_OR_EQUAL", "T_XOR_EQUAL", "T_SL_EQUAL", "T_SR_EQUAL", "T_BOOLEAN_OR", "T_BOOLEAN_AND", "T_IS_EQUAL", "T_IS_NOT_EQUAL", "T_IS_IDENTICAL", "T_IS_NOT_IDENTICAL", "T_IS_SMALLER_OR_EQUAL", "T_IS_GREATER_OR_EQUAL", "T_SL", "T_SR", "T_INC", "T_DEC", "T_INT_CAST", "T_DOUBLE_CAST", "T_STRING_CAST", "T_ARRAY_CAST", "T_OBJECT_CAST", "T_BOOL_CAST", "T_UNSET_CAST", "T_NEW", "T_EXIT", "T_IF", "T_ELSEIF", "T_ELSE", "T_ENDIF", "T_LNUMBER", "T_DNUMBER", "T_STRING", "T_STRING_VARNAME", "T_VARIABLE", "T_NUM_STRING", "T_INLINE_HTML", "T_CHARACTER", "T_BAD_CHARACTER", "T_ENCAPSED_AND_WHITESPACE", "T_CONSTANT_ENCAPSED_STRING", "T_ECHO", "T_DO", "T_WHILE", "T_ENDWHILE", "T_FOR", "T_ENDFOR", "T_FOREACH", "T_ENDFOREACH", "T_DECLARE", "T_ENDDECLARE", "T_AS", "T_SWITCH", "T_ENDSWITCH", "T_CASE", "T_DEFAULT", "T_BREAK", "T_CONTINUE", "T_FUNCTION", "T_CONST", "T_RETURN", "T_USE", "T_GLOBAL", "T_STATIC", "T_VAR", "T_UNSET", "T_ISSET", "T_EMPTY", "T_CLASS", "T_EXTENDS", "T_INTERFACE", "T_IMPLEMENTS", "T_OBJECT_OPERATOR", "T_DOUBLE_ARROW", "T_LIST", "T_ARRAY", "T_CLASS_C", "T_FUNC_C", "T_METHOD_C", "T_LINE", "T_FILE", "T_COMMENT", "T_DOC_COMMENT", "T_OPEN_TAG", "T_OPEN_TAG_WITH_ECHO", "T_CLOSE_TAG", "T_WHITESPACE", "T_START_HEREDOC", "T_END_HEREDOC", "T_DOLLAR_OPEN_CURLY_BRACES", "T_CURLY_OPEN", "T_PAAMAYIM_NEKUDOTAYIM", "T_DOUBLE_COLON", "T_ABSTRACT", "T_CATCH", "T_FINAL", "T_INSTANCEOF", "T_PRIVATE", "T_PROTECTED", "T_PUBLIC", "T_THROW", "T_TRY", "T_CLONE", "T_HALT_COMPILER", "FORCE_GZIP", "FORCE_DEFLATE", "XML_ELEMENT_NODE", "XML_ATTRIBUTE_NODE", "XML_TEXT_NODE", "XML_CDATA_SECTION_NODE", "XML_ENTITY_REF_NODE", "XML_ENTITY_NODE", "XML_PI_NODE", "XML_COMMENT_NODE", "XML_DOCUMENT_NODE", "XML_DOCUMENT_TYPE_NODE", "XML_DOCUMENT_FRAG_NODE", "XML_NOTATION_NODE", "XML_HTML_DOCUMENT_NODE", "XML_DTD_NODE", "XML_ELEMENT_DECL_NODE", "XML_ATTRIBUTE_DECL_NODE", "XML_ENTITY_DECL_NODE", "XML_NAMESPACE_DECL_NODE", "XML_LOCAL_NAMESPACE", "XML_ATTRIBUTE_CDATA", "XML_ATTRIBUTE_ID", "XML_ATTRIBUTE_IDREF", "XML_ATTRIBUTE_IDREFS", "XML_ATTRIBUTE_ENTITY", "XML_ATTRIBUTE_NMTOKEN", "XML_ATTRIBUTE_NMTOKENS", "XML_ATTRIBUTE_ENUMERATION", "XML_ATTRIBUTE_NOTATION", "DOM_PHP_ERR", "DOM_INDEX_SIZE_ERR", "DOMSTRING_SIZE_ERR", "DOM_HIERARCHY_REQUEST_ERR", "DOM_WRONG_DOCUMENT_ERR", "DOM_INVALID_CHARACTER_ERR", "DOM_NO_DATA_ALLOWED_ERR", "DOM_NO_MODIFICATION_ALLOWED_ERR", "DOM_NOT_FOUND_ERR", "DOM_NOT_SUPPORTED_ERR", "DOM_INUSE_ATTRIBUTE_ERR", "DOM_INVALID_STATE_ERR", "DOM_SYNTAX_ERR", "DOM_INVALID_MODIFICATION_ERR", "DOM_NAMESPACE_ERR", "DOM_INVALID_ACCESS_ERR", "DOM_VALIDATION_ERR", "XML_ERROR_NONE", "XML_ERROR_NO_MEMORY", "XML_ERROR_SYNTAX", "XML_ERROR_NO_ELEMENTS", "XML_ERROR_INVALID_TOKEN", "XML_ERROR_UNCLOSED_TOKEN", "XML_ERROR_PARTIAL_CHAR", "XML_ERROR_TAG_MISMATCH", "XML_ERROR_DUPLICATE_ATTRIBUTE", "XML_ERROR_JUNK_AFTER_DOC_ELEMENT", "XML_ERROR_PARAM_ENTITY_REF", "XML_ERROR_UNDEFINED_ENTITY", "XML_ERROR_RECURSIVE_ENTITY_REF", "XML_ERROR_ASYNC_ENTITY", "XML_ERROR_BAD_CHAR_REF", "XML_ERROR_BINARY_ENTITY_REF", "XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", "XML_ERROR_MISPLACED_XML_PI", "XML_ERROR_UNKNOWN_ENCODING", "XML_ERROR_INCORRECT_ENCODING", "XML_ERROR_UNCLOSED_CDATA_SECTION", "XML_ERROR_EXTERNAL_ENTITY_HANDLING", "XML_OPTION_CASE_FOLDING", "XML_OPTION_TARGET_ENCODING", "XML_OPTION_SKIP_TAGSTART", "XML_OPTION_SKIP_WHITE", "XML_SAX_IMPL", "IMG_GIF", "IMG_JPG", "IMG_JPEG", "IMG_PNG", "IMG_WBMP", "IMG_XPM", "IMG_COLOR_TILED", "IMG_COLOR_STYLED", "IMG_COLOR_BRUSHED", "IMG_COLOR_STYLEDBRUSHED", "IMG_COLOR_TRANSPARENT", "IMG_ARC_ROUNDED", "IMG_ARC_PIE", "IMG_ARC_CHORD", "IMG_ARC_NOFILL", "IMG_ARC_EDGED", "IMG_GD2_RAW", "IMG_GD2_COMPRESSED", "IMG_EFFECT_REPLACE", "IMG_EFFECT_ALPHABLEND", "IMG_EFFECT_NORMAL", "IMG_EFFECT_OVERLAY", "GD_BUNDLED", "IMG_FILTER_NEGATE", "IMG_FILTER_GRAYSCALE", "IMG_FILTER_BRIGHTNESS", "IMG_FILTER_CONTRAST", "IMG_FILTER_COLORIZE", "IMG_FILTER_EDGEDETECT", "IMG_FILTER_GAUSSIAN_BLUR", "IMG_FILTER_SELECTIVE_BLUR", "IMG_FILTER_EMBOSS", "IMG_FILTER_MEAN_REMOVAL", "IMG_FILTER_SMOOTH", "PNG_NO_FILTER", "PNG_FILTER_NONE", "PNG_FILTER_SUB", "PNG_FILTER_UP", "PNG_FILTER_AVG", "PNG_FILTER_PAETH", "PNG_ALL_FILTERS", "MB_OVERLOAD_MAIL", "MB_OVERLOAD_STRING", "MB_OVERLOAD_REGEX", "MB_CASE_UPPER", "MB_CASE_LOWER", "MB_CASE_TITLE", "MYSQL_ASSOC", "MYSQL_NUM", "MYSQL_BOTH", "MYSQL_CLIENT_COMPRESS", "MYSQL_CLIENT_SSL", "MYSQL_CLIENT_INTERACTIVE", "MYSQL_CLIENT_IGNORE_SPACE", "MYSQLI_READ_DEFAULT_GROUP", "MYSQLI_READ_DEFAULT_FILE", "MYSQLI_OPT_CONNECT_TIMEOUT", "MYSQLI_OPT_LOCAL_INFILE", "MYSQLI_INIT_COMMAND", "MYSQLI_CLIENT_SSL", "MYSQLI_CLIENT_COMPRESS", "MYSQLI_CLIENT_INTERACTIVE", "MYSQLI_CLIENT_IGNORE_SPACE", "MYSQLI_CLIENT_NO_SCHEMA", "MYSQLI_CLIENT_FOUND_ROWS", "MYSQLI_STORE_RESULT", "MYSQLI_USE_RESULT", "MYSQLI_ASSOC", "MYSQLI_NUM", "MYSQLI_BOTH", "MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH", "MYSQLI_STMT_ATTR_CURSOR_TYPE", "MYSQLI_CURSOR_TYPE_NO_CURSOR", "MYSQLI_CURSOR_TYPE_READ_ONLY", "MYSQLI_CURSOR_TYPE_FOR_UPDATE", "MYSQLI_CURSOR_TYPE_SCROLLABLE", "MYSQLI_STMT_ATTR_PREFETCH_ROWS", "MYSQLI_NOT_NULL_FLAG", "MYSQLI_PRI_KEY_FLAG", "MYSQLI_UNIQUE_KEY_FLAG", "MYSQLI_MULTIPLE_KEY_FLAG", "MYSQLI_BLOB_FLAG", "MYSQLI_UNSIGNED_FLAG", "MYSQLI_ZEROFILL_FLAG", "MYSQLI_AUTO_INCREMENT_FLAG", "MYSQLI_TIMESTAMP_FLAG", "MYSQLI_SET_FLAG", "MYSQLI_NUM_FLAG", "MYSQLI_PART_KEY_FLAG", "MYSQLI_GROUP_FLAG", "MYSQLI_TYPE_DECIMAL", "MYSQLI_TYPE_TINY", "MYSQLI_TYPE_SHORT", "MYSQLI_TYPE_LONG", "MYSQLI_TYPE_FLOAT", "MYSQLI_TYPE_DOUBLE", "MYSQLI_TYPE_NULL", "MYSQLI_TYPE_TIMESTAMP", "MYSQLI_TYPE_LONGLONG", "MYSQLI_TYPE_INT24", "MYSQLI_TYPE_DATE", "MYSQLI_TYPE_TIME", "MYSQLI_TYPE_DATETIME", "MYSQLI_TYPE_YEAR", "MYSQLI_TYPE_NEWDATE", "MYSQLI_TYPE_ENUM", "MYSQLI_TYPE_SET", "MYSQLI_TYPE_TINY_BLOB", "MYSQLI_TYPE_MEDIUM_BLOB", "MYSQLI_TYPE_LONG_BLOB", "MYSQLI_TYPE_BLOB", "MYSQLI_TYPE_VAR_STRING", "MYSQLI_TYPE_STRING", "MYSQLI_TYPE_CHAR", "MYSQLI_TYPE_INTERVAL", "MYSQLI_TYPE_GEOMETRY", "MYSQLI_TYPE_NEWDECIMAL", "MYSQLI_TYPE_BIT", "MYSQLI_RPL_MASTER", "MYSQLI_RPL_SLAVE", "MYSQLI_RPL_ADMIN", "MYSQLI_NO_DATA", "MYSQLI_DATA_TRUNCATED", "MYSQLI_REPORT_INDEX", "MYSQLI_REPORT_ERROR", "MYSQLI_REPORT_STRICT", "MYSQLI_REPORT_ALL", "MYSQLI_REPORT_OFF", "AF_UNIX", "AF_INET", "AF_INET6", "SOCK_STREAM", "SOCK_DGRAM", "SOCK_RAW", "SOCK_SEQPACKET", "SOCK_RDM", "MSG_OOB", "MSG_WAITALL", "MSG_PEEK", "MSG_DONTROUTE", "SO_DEBUG", "SO_REUSEADDR", "SO_KEEPALIVE", "SO_DONTROUTE", "SO_LINGER", "SO_BROADCAST", "SO_OOBINLINE", "SO_SNDBUF", "SO_RCVBUF", "SO_SNDLOWAT", "SO_RCVLOWAT", "SO_SNDTIMEO", "SO_RCVTIMEO", "SO_TYPE", "SO_ERROR", "SOL_SOCKET", "SOMAXCONN", "PHP_NORMAL_READ", "PHP_BINARY_READ", "SOCKET_EINTR", "SOCKET_EBADF", "SOCKET_EACCES", "SOCKET_EFAULT", "SOCKET_EINVAL", "SOCKET_EMFILE", "SOCKET_EWOULDBLOCK", "SOCKET_EINPROGRESS", "SOCKET_EALREADY", "SOCKET_ENOTSOCK", "SOCKET_EDESTADDRREQ", "SOCKET_EMSGSIZE", "SOCKET_EPROTOTYPE", "SOCKET_ENOPROTOOPT", "SOCKET_EPROTONOSUPPORT", "SOCKET_ESOCKTNOSUPPORT", "SOCKET_EOPNOTSUPP", "SOCKET_EPFNOSUPPORT", "SOCKET_EAFNOSUPPORT", "SOCKET_EADDRINUSE", "SOCKET_EADDRNOTAVAIL", "SOCKET_ENETDOWN", "SOCKET_ENETUNREACH", "SOCKET_ENETRESET", "SOCKET_ECONNABORTED", "SOCKET_ECONNRESET", "SOCKET_ENOBUFS", "SOCKET_EISCONN", "SOCKET_ENOTCONN", "SOCKET_ESHUTDOWN", "SOCKET_ETOOMANYREFS", "SOCKET_ETIMEDOUT", "SOCKET_ECONNREFUSED", "SOCKET_ELOOP", "SOCKET_ENAMETOOLONG", "SOCKET_EHOSTDOWN", "SOCKET_EHOSTUNREACH", "SOCKET_ENOTEMPTY", "SOCKET_EPROCLIM", "SOCKET_EUSERS", "SOCKET_EDQUOT", "SOCKET_ESTALE", "SOCKET_EREMOTE", "SOCKET_EDISCON", "SOCKET_SYSNOTREADY", "SOCKET_VERNOTSUPPORTED", "SOCKET_NOTINITIALISED", "SOCKET_HOST_NOT_FOUND", "SOCKET_TRY_AGAIN", "SOCKET_NO_RECOVERY", "SOCKET_NO_DATA", "SOCKET_NO_ADDRESS", "SOL_TCP", "SOL_UDP", "EACCELERATOR_VERSION", "EACCELERATOR_SHM_AND_DISK", "EACCELERATOR_SHM", "EACCELERATOR_SHM_ONLY", "EACCELERATOR_DISK_ONLY", "EACCELERATOR_NONE", "XDEBUG_TRACE_APPEND", "XDEBUG_TRACE_COMPUTERIZED", "XDEBUG_TRACE_HTML", "XDEBUG_CC_UNUSED", "XDEBUG_CC_DEAD_CODE", "STDIN", "STDOUT", "STDERR", "DNS_HINFO", "DNS_PTR", "SQLITE_EMPTY", "SVN_SHOW_UPDATES", "SVN_NO_IGNORE", "MSG_EOF", "DNS_MX", "GD_EXTRA_VERSION", "PHP_VERSION_ID", "SQLITE_OK", "LIBXML_LOADED_VERSION", "RADIXCHAR", "OPENSSL_VERSION_TEXT", "OPENSSL_VERSION_NUMBER", "PCRE_VERSION", "CURLOPT_FILE", "CURLOPT_INFILE", "CURLOPT_URL", "CURLOPT_PROXY", "CURLE_FUNCTION_NOT_FOUND", "SOCKET_ENOMSG", "CURLOPT_HTTPHEADER", "SOCKET_EIDRM", "CURLOPT_PROGRESSFUNCTION", "SOCKET_ECHRNG", "SOCKET_EL2NSYNC", "SOCKET_EL3HLT", "SOCKET_EL3RST", "SOCKET_ELNRNG", "SOCKET_ENOCSI", "SOCKET_EL2HLT", "SOCKET_EBADE", "SOCKET_EXFULL", "CURLOPT_USERPWD", "CURLOPT_PROXYUSERPWD", "CURLOPT_RANGE", "CURLOPT_TIMEOUT_MS", "CURLOPT_POSTFIELDS", "CURLOPT_REFERER", "CURLOPT_USERAGENT", "CURLOPT_FTPPORT", "SOCKET_ERESTART", "SQLITE_CONSTRAINT", "SQLITE_MISMATCH", "SQLITE_MISUSE", "CURLOPT_COOKIE", "CURLE_SSL_CERTPROBLEM", "CURLOPT_SSLCERT", "CURLOPT_KEYPASSWD", "CURLOPT_WRITEHEADER", "CURLOPT_SSL_VERIFYHOST", "CURLOPT_COOKIEFILE", "CURLE_HTTP_RANGE_ERROR", "CURLE_HTTP_POST_ERROR", "CURLOPT_CUSTOMREQUEST", "CURLOPT_STDERR", "SOCKET_EBADR", "CURLOPT_RETURNTRANSFER", "CURLOPT_QUOTE", "CURLOPT_POSTQUOTE", "CURLOPT_INTERFACE", "CURLOPT_KRB4LEVEL", "SOCKET_ENODATA", "SOCKET_ESRMNT", "CURLOPT_WRITEFUNCTION", "CURLOPT_READFUNCTION", "CURLOPT_HEADERFUNCTION", "SOCKET_EADV", "SOCKET_EPROTO", "SOCKET_EMULTIHOP", "SOCKET_EBADMSG", "CURLOPT_FORBID_REUSE", "CURLOPT_RANDOM_FILE", "CURLOPT_EGDSOCKET", "SOCKET_EREMCHG", "CURLOPT_CONNECTTIMEOUT_MS", "CURLOPT_CAINFO", "CURLOPT_CAPATH", "CURLOPT_COOKIEJAR", "CURLOPT_SSL_CIPHER_LIST", "CURLOPT_BINARYTRANSFER", "SQLITE_DONE", "CURLOPT_HTTP_VERSION", "CURLOPT_SSLKEY", "CURLOPT_SSLKEYTYPE", "CURLOPT_SSLENGINE", "CURLOPT_SSLCERTTYPE", "CURLE_OUT_OF_MEMORY", "CURLOPT_ENCODING", "CURLE_SSL_CIPHER", "SOCKET_EREMOTEIO", "CURLOPT_HTTP200ALIASES", "CURLAUTH_ANY", "CURLAUTH_ANYSAFE", "CURLOPT_PRIVATE", "CURLINFO_EFFECTIVE_URL", "CURLINFO_HTTP_CODE", "CURLINFO_HEADER_SIZE", "CURLINFO_REQUEST_SIZE", "CURLINFO_TOTAL_TIME", "CURLINFO_NAMELOOKUP_TIME", "CURLINFO_CONNECT_TIME", "CURLINFO_PRETRANSFER_TIME", "CURLINFO_SIZE_UPLOAD", "CURLINFO_SIZE_DOWNLOAD", "CURLINFO_SPEED_DOWNLOAD", "CURLINFO_SPEED_UPLOAD", "CURLINFO_FILETIME", "CURLINFO_SSL_VERIFYRESULT", "CURLINFO_CONTENT_LENGTH_DOWNLOAD", "CURLINFO_CONTENT_LENGTH_UPLOAD", "CURLINFO_STARTTRANSFER_TIME", "CURLINFO_CONTENT_TYPE", "CURLINFO_REDIRECT_TIME", "CURLINFO_REDIRECT_COUNT", "CURLINFO_PRIVATE", "CURLINFO_CERTINFO", "SQLITE_PROTOCOL", "SQLITE_SCHEMA", "SQLITE_TOOBIG", "SQLITE_NOLFS", "SQLITE_AUTH", "SQLITE_FORMAT", "SOCKET_ENOTTY", "SQLITE_NOTADB", "SOCKET_ENOSPC", "SOCKET_ESPIPE", "SOCKET_EROFS", "SOCKET_EMLINK", "GD_RELEASE_VERSION", "SOCKET_ENOLCK", "SOCKET_ENOSYS", "SOCKET_EUNATCH", "SOCKET_ENOANO", "SOCKET_EBADRQC", "SOCKET_EBADSLT", "SOCKET_ENOSTR", "SOCKET_ETIME", "SOCKET_ENOSR", "SVN_REVISION_HEAD", "XSD_ENTITY", "XSD_NOTATION", "CURLOPT_CERTINFO", "CURLOPT_POSTREDIR", "CURLOPT_SSH_AUTH_TYPES", "CURLOPT_SSH_PUBLIC_KEYFILE", "CURLOPT_SSH_PRIVATE_KEYFILE", "CURLOPT_SSH_HOST_PUBLIC_KEY_MD5", "CURLE_SSH", "CURLOPT_REDIR_PROTOCOLS", "CURLOPT_PROTOCOLS", "XSD_NONNEGATIVEINTEGER", "XSD_BYTE","DNS_SRV","DNS_A6", "DNS_NAPTR", "DNS_AAAA", "FILTER_SANITIZE_FULL_SPECIAL_CHARS", "ABDAY_1", "SVN_REVISION_UNSPECIFIED", "SVN_REVISION_BASE", "SVN_REVISION_COMMITTED", "SVN_REVISION_PREV", "GD_VERSION", "MCRYPT_TRIPLEDES", "MCRYPT_ARCFOUR_IV", "MCRYPT_ARCFOUR", "MCRYPT_BLOWFISH", "MCRYPT_BLOWFISH_COMPAT", "MCRYPT_CAST_128", "MCRYPT_CAST_256", "MCRYPT_ENIGNA", "MCRYPT_DES", "MCRYPT_GOST", "MCRYPT_LOKI97", "MCRYPT_PANAMA", "MCRYPT_RC2", "MCRYPT_RIJNDAEL_128", "MCRYPT_RIJNDAEL_192", "MCRYPT_RIJNDAEL_256", "MCRYPT_SAFER64", "MCRYPT_SAFER128","MCRYPT_SAFERPLUS", "MCRYPT_SERPENT", "MCRYPT_THREEWAY", "MCRYPT_TWOFISH", "MCRYPT_WAKE", "MCRYPT_XTEA", "MCRYPT_IDEA", "MCRYPT_MARS", "MCRYPT_RC6", "MCRYPT_SKIPJACK", "MCRYPT_MODE_CBC", "MCRYPT_MODE_CFB", "MCRYPT_MODE_ECB", "MCRYPT_MODE_NOFB", "MCRYPT_MODE_OFB", "MCRYPT_MODE_STREAM", "CL_EXPUNGE", "SQLITE_ROW", "POSIX_S_IFBLK", "POSIX_S_IFSOCK", "XSD_IDREF", "ABDAY_2", "ABDAY_3", "ABDAY_4", "ABDAY_5", "ABDAY_6", "ABDAY_7", "DAY_1", "DAY_2", "DAY_3", "DAY_4", "DAY_5", "DAY_6", "DAY_7", "ABMON_1", "ABMON_2", "ABMON_3", "ABMON_4", "ABMON_5", "ABMON_6", "ABMON_7","ABMON_8", "ABMON_9", "ABMON_10", "ABMON_11", "ABMON_12", "MON_1", "MON_2", "MON_3", "MON_4", "MON_5", "MON_6", "MON_7", "MON_8", "MON_9", "MON_10", "MON_11", "MON_12", "AM_STR", "PM_STR", "D_T_FMT", "D_FMT", "T_FMT", "T_FMT_AMPM", "ERA", "ERA_D_T_FMT", "ERA_D_FMT", "ERA_T_FMT", "ALT_DIGITS", "CRNCYSTR", "THOUSEP", "YESEXPR", "NOEXPR", "SOCKET_ENOMEDIUM", "GLOB_AVAILABLE_FLAGS", "XSD_SHORT", "XSD_NMTOKENS", "LOG_LOCAL3", "LOG_LOCAL4", "LOG_LOCAL5", "LOG_LOCAL6", "LOG_LOCAL7", "DNS_ANY", "DNS_ALL", "SOCKET_ENOLINK", "SOCKET_ECOMM", "SOAP_FUNCTIONS_ALL", "UNKNOWN_TYPE", "XSD_BASE64BINARY", "XSD_ANYURI", "XSD_QNAME", "SOCKET_EISNAM", "SOCKET_EMEDIUMTYPE", "XSD_NCNAME", "XSD_ID", "XSD_ENTITIES", "XSD_INTEGER", "XSD_NONPOSITIVEINTEGER", "XSD_NEGATIVEINTEGER", "XSD_LONG", "XSD_INT", "XSD_UNSIGNEDLONG", "XSD_UNSIGNEDINT", "XSD_UNSIGNEDSHORT", "XSD_UNSIGNEDBYTE", "XSD_POSITIVEINTEGER", "XSD_ANYTYPE", "XSD_ANYXML", "APACHE_MAP", "XSD_1999_TIMEINSTANT", "XSD_NAMESPACE", "XSD_1999_NAMESPACE", "SOCKET_ENOTUNIQ", "SOCKET_EBADFD", "SOCKET_ESTRPIPE", "T_GOTO", "T_NAMESPACE", "T_NS_C", "T_DIR", "T_NS_SEPARATOR", "LIBXSLT_VERSION","LIBEXSLT_DOTTED_VERSION", "LIBEXSLT_VERSION", "SVN_AUTH_PARAM_DEFAULT_USERNAME", "SVN_AUTH_PARAM_DEFAULT_PASSWORD", "SVN_AUTH_PARAM_NON_INTERACTIVE", "SVN_AUTH_PARAM_DONT_STORE_PASSWORDS", "SVN_AUTH_PARAM_NO_AUTH_CACHE", "SVN_AUTH_PARAM_SSL_SERVER_FAILURES", "SVN_AUTH_PARAM_SSL_SERVER_CERT_INFO", "SVN_AUTH_PARAM_CONFIG", "SVN_AUTH_PARAM_SERVER_GROUP", "SVN_AUTH_PARAM_CONFIG_DIR", "PHP_SVN_AUTH_PARAM_IGNORE_SSL_VERIFY_ERRORS", "SVN_FS_CONFIG_FS_TYPE", "SVN_FS_TYPE_BDB", "SVN_FS_TYPE_FSFS", "SVN_PROP_REVISION_DATE", "SVN_PROP_REVISION_ORIG_DATE", "SVN_PROP_REVISION_AUTHOR", "SVN_PROP_REVISION_LOG" ].forEach(function(element, index, array) { result[element] = token("atom", "php-predefined-constant"); }); // PHP declared classes - output of get_declared_classes(). Differs from http://php.net/manual/en/reserved.classes.php [ "stdClass", "Exception", "ErrorException", "COMPersistHelper", "com_exception", "com_safearray_proxy", "variant", "com", "dotnet", "ReflectionException", "Reflection", "ReflectionFunctionAbstract", "ReflectionFunction", "ReflectionParameter", "ReflectionMethod", "ReflectionClass", "ReflectionObject", "ReflectionProperty", "ReflectionExtension", "DateTime", "DateTimeZone", "LibXMLError", "__PHP_Incomplete_Class", "php_user_filter", "Directory", "SimpleXMLElement", "DOMException", "DOMStringList", "DOMNameList", "DOMImplementationList", "DOMImplementationSource", "DOMImplementation", "DOMNode", "DOMNameSpaceNode", "DOMDocumentFragment", "DOMDocument", "DOMNodeList", "DOMNamedNodeMap", "DOMCharacterData", "DOMAttr", "DOMElement", "DOMText", "DOMComment", "DOMTypeinfo", "DOMUserDataHandler", "DOMDomError", "DOMErrorHandler", "DOMLocator", "DOMConfiguration", "DOMCdataSection", "DOMDocumentType", "DOMNotation", "DOMEntity", "DOMEntityReference", "DOMProcessingInstruction", "DOMStringExtend", "DOMXPath", "RecursiveIteratorIterator", "IteratorIterator", "FilterIterator", "RecursiveFilterIterator", "ParentIterator", "LimitIterator", "CachingIterator", "RecursiveCachingIterator", "NoRewindIterator", "AppendIterator", "InfiniteIterator", "RegexIterator", "RecursiveRegexIterator", "EmptyIterator", "ArrayObject", "ArrayIterator", "RecursiveArrayIterator", "SplFileInfo", "DirectoryIterator", "RecursiveDirectoryIterator", "SplFileObject", "SplTempFileObject", "SimpleXMLIterator", "LogicException", "BadFunctionCallException", "BadMethodCallException", "DomainException", "InvalidArgumentException", "LengthException", "OutOfRangeException", "RuntimeException", "OutOfBoundsException", "OverflowException", "RangeException", "UnderflowException", "UnexpectedValueException", "SplObjectStorage", "XMLReader", "XMLWriter", "mysqli_sql_exception", "mysqli_driver", "mysqli", "mysqli_warning", "mysqli_result", "mysqli_stmt", "PDOException", "PDO", "PDOStatement", "PDORow","Closure", "DateInterval", "DatePeriod", "FilesystemIterator", "GlobIterator", "MultipleIterator", "RecursiveTreeIterator", "SoapClient", "SoapFault", "SoapHeader", "SoapParam", "SoapServer", "SoapVar", "SplDoublyLinkedList", "SplFixedArray", "SplHeap", "SplMaxHeap", "SplMinHeap", "SplPriorityQueue", "SplQueue", "SplStack", "SQLite3", "SQLite3Result", "SQLite3Stmt", "SQLiteDatabase", "SQLiteException", "SQLiteResult", "SQLiteUnbuffered", "Svn", "SvnNode", "SvnWc", "SvnWcSchedule", "XSLTProcessor", "ZipArchive" ].forEach(function(element, index, array) { result[element] = token("t_string", "php-predefined-class"); }); return result; }(); // Helper regexps var isOperatorChar = /[+*&%\/=<>!?.|^@-]/; var isHexDigit = /[0-9A-Fa-f]/; var isWordChar = /[\w\$_\\]/; // Wrapper around phpToken that helps maintain parser state (whether // we are inside of a multi-line comment) function phpTokenState(inside) { return function(source, setState) { var newInside = inside; var type = phpToken(inside, source, function(c) {newInside = c;}); if (newInside != inside) setState(phpTokenState(newInside)); return type; }; } // The token reader, inteded to be used by the tokenizer from // tokenize.js (through phpTokenState). Advances the source stream // over a token, and returns an object containing the type and style // of that token. function phpToken(inside, source, setInside) { function readHexNumber(){ source.next(); // skip the 'x' source.nextWhileMatches(isHexDigit); return {type: "number", style: "php-atom"}; } function readNumber() { source.nextWhileMatches(/[0-9]/); if (source.equals(".")){ source.next(); source.nextWhileMatches(/[0-9]/); } if (source.equals("e") || source.equals("E")){ source.next(); if (source.equals("-")) source.next(); source.nextWhileMatches(/[0-9]/); } return {type: "number", style: "php-atom"}; } // Read a word and look it up in the keywords array. If found, it's a // keyword of that type; otherwise it's a PHP T_STRING. function readWord() { source.nextWhileMatches(isWordChar); var word = source.get(); var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word]; // since we called get(), tokenize::take won't get() anything. Thus, we must set token.content return known ? {type: known.type, style: known.style, content: word} : {type: "t_string", style: "php-t_string", content: word}; } function readVariable() { source.nextWhileMatches(isWordChar); var word = source.get(); // in PHP, '$this' is a reserved word, but 'this' isn't. You can have function this() {...} if (word == "$this") return {type: "variable", style: "php-keyword", content: word}; else return {type: "variable", style: "php-variable", content: word}; } // Advance the stream until the given character (not preceded by a // backslash) is encountered, or the end of the line is reached. function nextUntilUnescaped(source, end) { var escaped = false; while(!source.endOfLine()){ var next = source.next(); if (next == end && !escaped) return false; escaped = next == "\\" && !escaped; } return escaped; } function readSingleLineComment() { // read until the end of the line or until ?>, which terminates single-line comments // `<?php echo 1; // comment ?> foo` will display "1 foo" while(!source.lookAhead("?>") && !source.endOfLine()) source.next(); return {type: "comment", style: "php-comment"}; } /* For multi-line comments, we want to return a comment token for every line of the comment, but we also want to return the newlines in them as regular newline tokens. We therefore need to save a state variable ("inside") to indicate whether we are inside a multi-line comment. */ function readMultilineComment(start){ var newInside = "/*"; var maybeEnd = (start == "*"); while (true) { if (source.endOfLine()) break; var next = source.next(); if (next == "/" && maybeEnd){ newInside = null; break; } maybeEnd = (next == "*"); } setInside(newInside); return {type: "comment", style: "php-comment"}; } // similar to readMultilineComment and nextUntilUnescaped // unlike comments, strings are not stopped by ?> function readMultilineString(start){ var newInside = start; var escaped = false; while (true) { if (source.endOfLine()) break; var next = source.next(); if (next == start && !escaped){ newInside = null; // we're outside of the string now break; } escaped = (next == "\\" && !escaped); } setInside(newInside); return { type: newInside == null? "string" : "string_not_terminated", style: (start == "'"? "php-string-single-quoted" : "php-string-double-quoted") }; } // http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc // See also 'nowdoc' on the page. Heredocs are not interrupted by the '?>' token. function readHeredoc(identifier){ var token = {}; if (identifier == "<<<") { // on our first invocation after reading the <<<, we must determine the closing identifier if (source.equals("'")) { // nowdoc source.nextWhileMatches(isWordChar); identifier = "'" + source.get() + "'"; source.next(); // consume the closing "'" } else if (source.matches(/[A-Za-z_]/)) { // heredoc source.nextWhileMatches(isWordChar); identifier = source.get(); } else { // syntax error setInside(null); return { type: "error", style: "syntax-error" }; } setInside(identifier); token.type = "string_not_terminated"; token.style = identifier.charAt(0) == "'"? "php-string-single-quoted" : "php-string-double-quoted"; token.content = identifier; } else { token.style = identifier.charAt(0) == "'"? "php-string-single-quoted" : "php-string-double-quoted"; // consume a line of heredoc and check if it equals the closing identifier plus an optional semicolon if (source.lookAhead(identifier, true) && (source.lookAhead(";\n") || source.endOfLine())) { // the closing identifier can only appear at the beginning of the line // note that even whitespace after the ";" is forbidden by the PHP heredoc syntax token.type = "string"; token.content = source.get(); // don't get the ";" if there is one setInside(null); } else { token.type = "string_not_terminated"; source.nextWhileMatches(/[^\n]/); token.content = source.get(); } } return token; } function readOperator() { source.nextWhileMatches(isOperatorChar); return {type: "operator", style: "php-operator"}; } function readStringSingleQuoted() { var endBackSlash = nextUntilUnescaped(source, "'", false); setInside(endBackSlash ? "'" : null); return {type: "string", style: "php-string-single-quoted"}; } function readStringDoubleQuoted() { var endBackSlash = nextUntilUnescaped(source, "\"", false); setInside(endBackSlash ? "\"": null); return {type: "string", style: "php-string-double-quoted"}; } // Fetch the next token. Dispatches on first character in the // stream, or first two characters when the first is a slash. switch (inside) { case null: case false: break; case "'": case "\"": return readMultilineString(inside); case "/*": return readMultilineComment(source.next()); default: return readHeredoc(inside); } var ch = source.next(); if (ch == "'" || ch == "\"") return readMultilineString(ch); else if (ch == "#") return readSingleLineComment(); else if (ch == "$") return readVariable(); else if (ch == ":" && source.equals(":")) { source.next(); // the T_DOUBLE_COLON can only follow a T_STRING (class name) return {type: "t_double_colon", style: "php-operator"}; } // with punctuation, the type of the token is the symbol itself else if (/[\[\]{}\(\),;:]/.test(ch)) { return {type: ch, style: "php-punctuation"}; } else if (ch == "0" && (source.equals("x") || source.equals("X"))) return readHexNumber(); else if (/[0-9]/.test(ch)) return readNumber(); else if (ch == "/") { if (source.equals("*")) { source.next(); return readMultilineComment(ch); } else if (source.equals("/")) return readSingleLineComment(); else return readOperator(); } else if (ch == "<") { if (source.lookAhead("<<", true)) { setInside("<<<"); return {type: "<<<", style: "php-punctuation"}; } else return readOperator(); } else if (isOperatorChar.test(ch)) return readOperator(); else return readWord(); } // The external interface to the tokenizer. return function(source, startState) { return tokenizer(source, startState || phpTokenState(false, true)); }; })();
JavaScript
/** * Tinymce template_list.js sample file * @version tinymce 3.3.9 * @package Joomla * @copyright Copyright (C) 2005 - 2012 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ // This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system. // There templates will be displayed as a dropdown in all media dialog if the "template_external_list_url" // option is defined in TinyMCE init. var tinyMCETemplateList = [ // Name, URL, Description ["Simple snippet", "media/editors/tinymce/templates/snippet1.html", "Simple HTML snippet."], ["Layout", "media/editors/tinymce/templates/layout1.html", "HTMLLayout."] ];
JavaScript
var FinderProgressBar = new Class({ Implements: [Events, Options], options: { container: document.body, boxID: 'progress-bar-box-id', percentageID: 'progress-bar-percentage-id', displayID: 'progress-bar-display-id', startPercentage: 0, displayText: false, speed: 10, step: 1, allowMore: false, onComplete: function () {}, onChange: function () {} }, initialize: function (options) { this.setOptions(options); this.options.container = document.id(this.options.container); this.createElements(); }, createElements: function () { var box = new Element('div', { id: this.options.boxID }); var perc = new Element('div', { id: this.options.percentageID, 'style': 'width:0px;' }); perc.inject(box); box.inject(this.options.container); if (this.options.displayText) { var text = new Element('div', { id: this.options.displayID }); text.inject(this.options.container); } this.set(this.options.startPercentage); }, calculate: function (percentage) { return (document.id(this.options.boxID).getStyle('width').replace('px', '') * (percentage / 100)).toInt(); }, animate: function (go) { var run = false; var self = this; if (!self.options.allowMore && go > 100) { go = 100; } self.to = go.toInt(); document.id(self.options.percentageID).set('morph', { duration: this.options.speed, link: 'cancel', onComplete: function () { self.fireEvent('change', [self.to]); if (go >= 100) { self.fireEvent('complete', [self.to]); } } }).morph({ width: self.calculate(go) }); if (self.options.displayText) { document.id(self.options.displayID).set('text', self.to + '%'); } }, set: function (to) { this.animate(to); }, step: function () { this.set(this.to + this.options.step); } }); var FinderIndexer = new Class({ totalItems: null, batchSize: null, offset: null, progress: null, optimized: false, path: 'index.php?option=com_finder&tmpl=component&format=json', initialize: function () { this.offset = 0; this.progress = 0; this.pb = new FinderProgressBar({ container: document.id('finder-progress-container'), startPercentage: 0, speed: 600, boxID: 'finder-progress-box', percentageID: 'finder-progress-perc', displayID: 'finder-progress-status', displayText: true }); this.path = this.path + '&' + document.id('finder-indexer-token').get('name') + '=1'; this.getRequest('indexer.start').send() }, getRequest: function (task) { return new Request.JSON({ url: this.path, method: 'get', data: 'task=' + task, onSuccess: this.handleResponse.bind(this), onFailure: this.handleFailure.bind(this) }); }, handleResponse: function (json, resp) { try { if (json === null) { throw resp; } if (json.error) { throw json; } if (json.start) this.totalItems = json.totalItems; this.offset += json.batchOffset; this.updateProgress(json.header, json.message); if (this.offset < this.totalItems) { this.getRequest('indexer.batch').send(); } else if (!this.optimized) { this.optimized = true; this.getRequest('indexer.optimize').send(); } } catch (error) { if (this.pb) document.id(this.pb.options.container).dispose(); try { if (json.error) { document.id('finder-progress-header').set('text', json.header).addClass('finder-error'); document.id('finder-progress-message').set('html', json.message).addClass('finder-error'); } } catch (ignore) { if (error == '') { error = Joomla.JText._('COM_FINDER_NO_ERROR_RETURNED'); } document.id('finder-progress-header').set('text', Joomla.JText._('COM_FINDER_AN_ERROR_HAS_OCCURRED')).addClass('finder-error'); document.id('finder-progress-message').set('html', error).addClass('finder-error'); } } return true; }, handleFailure: function (xhr) { json = (typeof xhr == 'object' && xhr.responseText) ? xhr.responseText : null; json = json ? JSON.decode(json, true) : null; if (this.pb) document.id(this.pb.options.container).dispose(); if (json) { json = json.responseText != null ? Json.evaluate(json.responseText, true) : json; } var header = json ? json.header : Joomla.JText._('COM_FINDER_AN_ERROR_HAS_OCCURRED'); var message = json ? json.message : Joomla.JText._('COM_FINDER_MESSAGE_RETURNED') + ' <br />' + json document.id('finder-progress-header').set('text', header).addClass('finder-error'); document.id('finder-progress-message').set('html', message).addClass('finder-error'); }, updateProgress: function (header, message) { this.progress = (this.offset / this.totalItems) * 100; document.id('finder-progress-header').set('text', header); document.id('finder-progress-message').set('html', message); if (this.pb && this.progress < 100) { this.pb.set(this.progress); } else if (this.pb) { document.id(this.pb.options.container).dispose(); this.pb = false; } } }); window.addEvent('domready', function () { Indexer = new FinderIndexer(); if (typeof window.parent.SqueezeBox == 'object') { window.parent.SqueezeBox.addEvent('onClose', function () { window.parent.location.reload(true); }); } });
JavaScript
var Observer = new Class({ Implements: [Options, Events], options: { periodical: false, delay: 1000 }, initialize: function (el, onFired, options) { this.element = document.id(el) || $document.id(el); this.addEvent('onFired', onFired); this.setOptions(options); this.bound = this.changed.bind(this); this.resume(); }, changed: function () { var value = this.element.get('value'); if ($equals(this.value, value)) return; this.clear(); this.value = value; this.timeout = this.onFired.delay(this.options.delay, this); }, setValue: function (value) { this.value = value; this.element.set('value', value); return this.clear(); }, onFired: function () { this.fireEvent('onFired', [this.value, this.element]); }, clear: function () { clearTimeout(this.timeout || null); return this; }, pause: function () { if (this.timer) clearTimeout(this.timer); else this.element.removeEvent('keyup', this.bound); return this.clear(); }, resume: function () { this.value = this.element.get('value'); if (this.options.periodical) this.timer = this.changed.periodical(this.options.periodical, this); else this.element.addEvent('keyup', this.bound); return this; } }); var $equals = function (obj1, obj2) { return (obj1 == obj2 || JSON.encode(obj1) == JSON.encode(obj2)); }; var Autocompleter = new Class({ Implements: [Options, Events], options: { minLength: 1, markQuery: true, width: 'inherit', maxChoices: 10, injectChoice: null, customChoices: null, emptyChoices: null, visibleChoices: true, className: 'autocompleter-choices', zIndex: 1000, delay: 400, observerOptions: {}, fxOptions: {}, autoSubmit: false, overflow: false, overflowMargin: 25, selectFirst: false, filter: null, filterCase: false, filterSubset: false, forceSelect: false, selectMode: true, choicesMatch: null, multiple: false, separator: ', ', separatorSplit: /\s*[,;]\s*/, autoTrim: false, allowDupes: false, cache: true, relative: false }, initialize: function (element, options) { this.element = document.id(element); this.setOptions(options); this.build(); this.observer = new Observer(this.element, this.prefetch.bind(this), Object.merge({}, { 'delay': this.options.delay }, this.options.observerOptions)); this.queryValue = null; if (this.options.filter) this.filter = this.options.filter.bind(this); var mode = this.options.selectMode; this.typeAhead = (mode == 'type-ahead'); this.selectMode = (mode === true) ? 'selection' : mode; this.cached = []; }, build: function () { if (document.id(this.options.customChoices)) { this.choices = this.options.customChoices; } else { this.choices = new Element('ul', { 'class': this.options.className, 'styles': { 'zIndex': this.options.zIndex } }).inject(document.body); this.relative = false; if (this.options.relative) { this.choices.inject(this.element, 'after'); this.relative = this.element.getOffsetParent(); } this.fix = new OverlayFix(this.choices); } if (!this.options.separator.test(this.options.separatorSplit)) { this.options.separatorSplit = this.options.separator; } this.fx = (!this.options.fxOptions) ? null : new Fx.Tween(this.choices, Object.merge({}, { 'property': 'opacity', 'link': 'cancel', 'duration': 200 }, this.options.fxOptions)).addEvent('onStart', Chain.prototype.clearChain).set(0); this.element.setProperty('autocomplete', 'off').addEvent((Browser.ie || Browser.safari || Browser.chrome) ? 'keydown' : 'keypress', this.onCommand.bind(this)).addEvent('click', this.onCommand.bind(this, [false])).addEvent('focus', this.toggleFocus.create({ bind: this, arguments: true, delay: 100 })).addEvent('blur', this.toggleFocus.create({ bind: this, arguments: false, delay: 100 })); }, destroy: function () { if (this.fix) this.fix.destroy(); this.choices = this.selected = this.choices.destroy(); }, toggleFocus: function (state) { this.focussed = state; if (!state) this.hideChoices(true); this.fireEvent((state) ? 'onFocus' : 'onBlur', [this.element]); }, onCommand: function (e) { if (!e && this.focussed) return this.prefetch(); if (e && e.key && !e.shift) { switch (e.key) { case 'enter': if (this.element.value != this.opted) return true; if (this.selected && this.visible) { this.choiceSelect(this.selected); return !!(this.options.autoSubmit); } break; case 'up': case 'down': if (!this.prefetch() && this.queryValue !== null) { var up = (e.key == 'up'); this.choiceOver((this.selected || this.choices)[(this.selected) ? ((up) ? 'getPrevious' : 'getNext') : ((up) ? 'getLast' : 'getFirst')](this.options.choicesMatch), true); } return false; case 'esc': case 'tab': this.hideChoices(true); break; } } return true; }, setSelection: function (finish) { var input = this.selected.inputValue, value = input; var start = this.queryValue.length, end = input.length; if (input.substr(0, start).toLowerCase() != this.queryValue.toLowerCase()) start = 0; if (this.options.multiple) { var split = this.options.separatorSplit; value = this.element.value; start += this.queryIndex; end += this.queryIndex; var old = value.substr(this.queryIndex).split(split, 1)[0]; value = value.substr(0, this.queryIndex) + input + value.substr(this.queryIndex + old.length); if (finish) { var tokens = value.split(this.options.separatorSplit).filter(function (entry) { return this.test(entry); }, /[^\s,]+/); if (!this.options.allowDupes) tokens = [].combine(tokens); var sep = this.options.separator; value = tokens.join(sep) + sep; end = value.length; } } this.observer.setValue(value); this.opted = value; if (finish || this.selectMode == 'pick') start = end; this.element.selectRange(start, end); this.fireEvent('onSelection', [this.element, this.selected, value, input]); }, showChoices: function () { var match = this.options.choicesMatch, first = this.choices.getFirst(match); this.selected = this.selectedValue = null; if (this.fix) { var pos = this.element.getCoordinates(this.relative), width = this.options.width || 'auto'; this.choices.setStyles({ 'left': pos.left, 'top': pos.bottom, 'width': (width === true || width == 'inherit') ? pos.width : width }); } if (!first) return; if (!this.visible) { this.visible = true; this.choices.setStyle('display', ''); if (this.fx) this.fx.start(1); this.fireEvent('onShow', [this.element, this.choices]); } if (this.options.selectFirst || this.typeAhead || first.inputValue == this.queryValue) this.choiceOver(first, this.typeAhead); var items = this.choices.getChildren(match), max = this.options.maxChoices; var styles = { 'overflowY': 'hidden', 'height': '' }; this.overflown = false; if (items.length > max) { var item = items[max - 1]; styles.overflowY = 'scroll'; styles.height = item.getCoordinates(this.choices).bottom; this.overflown = true; }; this.choices.setStyles(styles); this.fix.show(); if (this.options.visibleChoices) { var scroll = document.getScroll(), size = document.getSize(), coords = this.choices.getCoordinates(); if (coords.right > scroll.x + size.x) scroll.x = coords.right - size.x; if (coords.bottom > scroll.y + size.y) scroll.y = coords.bottom - size.y; window.scrollTo(Math.min(scroll.x, coords.left), Math.min(scroll.y, coords.top)); } }, // TODO: No $arguments in MT 1.3 hideChoices: function (clear) { if (clear) { var value = this.element.value; if (this.options.forceSelect) value = this.opted; if (this.options.autoTrim) { value = value.split(this.options.separatorSplit).filter($arguments(0)).join(this.options.separator); } this.observer.setValue(value); } if (!this.visible) return; this.visible = false; if (this.selected) this.selected.removeClass('autocompleter-selected'); this.observer.clear(); var hide = function () { this.choices.setStyle('display', 'none'); this.fix.hide(); }.bind(this); if (this.fx) this.fx.start(0).chain(hide); else hide(); this.fireEvent('onHide', [this.element, this.choices]); }, prefetch: function () { var value = this.element.value, query = value; if (this.options.multiple) { var split = this.options.separatorSplit; var values = value.split(split); var index = this.element.getSelectedRange().start; var toIndex = value.substr(0, index).split(split); var last = toIndex.length - 1; index -= toIndex[last].length; query = values[last]; } if (query.length < this.options.minLength) { this.hideChoices(); } else { if (query === this.queryValue || (this.visible && query == this.selectedValue)) { if (this.visible) return false; this.showChoices(); } else { this.queryValue = query; this.queryIndex = index; if (!this.fetchCached()) this.query(); } } return true; }, fetchCached: function () { return false; if (!this.options.cache || !this.cached || !this.cached.length || this.cached.length >= this.options.maxChoices || this.queryValue) return false; this.update(this.filter(this.cached)); return true; }, update: function (tokens) { this.choices.empty(); this.cached = tokens; var type = tokens && typeOf(tokens); if (!type || (type == 'array' && !tokens.length) || (type == 'hash' && !tokens.getLength())) { (this.options.emptyChoices || this.hideChoices).call(this); } else { if (this.options.maxChoices < tokens.length && !this.options.overflow) tokens.length = this.options.maxChoices; tokens.each(this.options.injectChoice || function (token) { var choice = new Element('li', { 'html': this.markQueryValue(token) }); choice.inputValue = token; this.addChoiceEvents(choice).inject(this.choices); }, this); this.showChoices(); } }, choiceOver: function (choice, selection) { if (!choice || choice == this.selected) return; if (this.selected) this.selected.removeClass('autocompleter-selected'); this.selected = choice.addClass('autocompleter-selected'); this.fireEvent('onSelect', [this.element, this.selected, selection]); if (!this.selectMode) this.opted = this.element.value; if (!selection) return; this.selectedValue = this.selected.inputValue; if (this.overflown) { var coords = this.selected.getCoordinates(this.choices), margin = this.options.overflowMargin, top = this.choices.scrollTop, height = this.choices.offsetHeight, bottom = top + height; if (coords.top - margin < top && top) this.choices.scrollTop = Math.max(coords.top - margin, 0); else if (coords.bottom + margin > bottom) this.choices.scrollTop = Math.min(coords.bottom - height + margin, bottom); } if (this.selectMode) this.setSelection(); }, choiceSelect: function (choice) { if (choice) this.choiceOver(choice); this.setSelection(true); this.queryValue = false; this.hideChoices(); }, filter: function (tokens) { return (tokens || this.tokens).filter(function (token) { return this.test(token); }, new RegExp(((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp(), (this.options.filterCase) ? '' : 'i')); }, markQueryValue: function (str) { return (!this.options.markQuery || !this.queryValue) ? str : str.replace(new RegExp('(' + ((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp() + ')', (this.options.filterCase) ? '' : 'i'), '<span class="autocompleter-queried">$1</span>'); }, addChoiceEvents: function (el) { return el.addEvents({ 'mouseover': this.choiceOver.bind(this, el), 'click': this.choiceSelect.bind(this, el) }); } }); var OverlayFix = new Class({ initialize: function (el) { if (Browser.ie) { this.element = document.id(el); this.relative = this.element.getOffsetParent(); this.fix = new Element('iframe', { 'frameborder': '0', 'scrolling': 'no', 'src': 'javascript:false;', 'styles': { 'position': 'absolute', 'border': 'none', 'display': 'none', 'filter': 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)' } }).inject(this.element, 'after'); } }, show: function () { if (this.fix) { var coords = this.element.getCoordinates(this.relative); delete coords.right; delete coords.bottom; this.fix.setStyles(Object.append(coords, { 'display': '', 'zIndex': (this.element.getStyle('zIndex') || 1) - 1 })); } return this; }, hide: function () { if (this.fix) this.fix.setStyle('display', 'none'); return this; }, destroy: function () { if (this.fix) this.fix = this.fix.destroy(); } }); Element.implement({ getSelectedRange: function () { if (!Browser.ie) return { start: this.selectionStart, end: this.selectionEnd }; var pos = { start: 0, end: 0 }; var range = this.getDocument().selection.createRange(); if (!range || range.parentElement() != this) return pos; var dup = range.duplicate(); if (this.type == 'text') { pos.start = 0 - dup.moveStart('character', -100000); pos.end = pos.start + range.text.length; } else { var value = this.value; var offset = value.length - value.match(/[\n\r]*$/)[0].length; dup.moveToElementText(this); dup.setEndPoint('StartToEnd', range); pos.end = offset - dup.text.length; dup.setEndPoint('StartToStart', range); pos.start = offset - dup.text.length; } return pos; }, selectRange: function (start, end) { if (Browser.ie) { var diff = this.value.substr(start, end - start).replace(/\r/g, '').length; start = this.value.substr(0, start).replace(/\r/g, '').length; var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', start + diff); range.moveStart('character', start); range.select(); } else { this.focus(); this.setSelectionRange(start, end); } return this; } }); Autocompleter.Base = Autocompleter; Autocompleter.Request = new Class({ Extends: Autocompleter, options: { postData: {}, ajaxOptions: {}, postVar: 'value' }, query: function () { var data = this.options.postData.unlink || {}; data[this.options.postVar] = this.queryValue; var indicator = document.id(this.options.indicator); if (indicator) indicator.setStyle('display', ''); var cls = this.options.indicatorClass; if (cls) this.element.addClass(cls); this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]); this.request.send({ 'data': data }); }, queryResponse: function () { var indicator = document.id(this.options.indicator); if (indicator) indicator.setStyle('display', 'none'); var cls = this.options.indicatorClass; if (cls) this.element.removeClass(cls); return this.fireEvent('onComplete', [this.element, this.request]); } }); Autocompleter.Request.JSON = new Class({ Extends: Autocompleter.Request, initialize: function (el, url, options) { this.parent(el, options); this.request = new Request.JSON(Object.merge({}, { 'url': url, 'link': 'cancel' }, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this)); }, queryResponse: function (response) { this.parent(); this.update(response); } }); Autocompleter.Request.HTML = new Class({ Extends: Autocompleter.Request, initialize: function (el, url, options) { this.parent(el, options); this.request = new Request.HTML(Object.merge({}, { 'url': url, 'link': 'cancel', 'update': this.choices }, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this)); }, queryResponse: function (tree, elements) { this.parent(); if (!elements || !elements.length) { this.hideChoices(); } else { this.choices.getChildren(this.options.choicesMatch).each(this.options.injectChoice || function (choice) { var value = choice.innerHTML; choice.inputValue = value; this.addChoiceEvents(choice.set('html', this.markQueryValue(value))); }, this); this.showChoices(); } } }); Autocompleter.Ajax = { Base: Autocompleter.Request, Json: Autocompleter.Request.JSON, Xhtml: Autocompleter.Request.HTML };
JavaScript
FinderFilter = new Class({ Extends: Fx.Elements, options: { onActive: Class.empty, onBackground: Class.empty, height: false, width: true, opacity: true, fixedHeight: false, fixedWidth: 220, wait: true }, initialize: function (togglers, elements, container, frame) { this.togglers = togglers || []; this.elements = elements || []; this.container = document.id(container); this.frame = document.id(frame); this.effects = {}; if (this.options.opacity) this.effects.opacity = 'fullOpacity'; if (this.options.width) this.effects.width = this.options.fixedWidth ? 'fullWidth' : 'offsetWidth'; this.container.setStyle('width', '230px'); this.addEvent('onActive', function (toggler, element) { element.set('styles', { 'border-top': '1px solid #ccc', 'border-right': '1px solid #ccc', 'border-bottom': '1px solid #ccc', 'overflow': 'auto' }); this.container.set('styles', { width: this.container.getStyle('width').toInt() + element.fullWidth }); coord = element.getCoordinates([this.frame]); scroller = new Fx.Scroll(frame); scroller.start(coord.top, coord.left); }); this.addEvent('onBackground', function () { el = this.elements[this.active]; el.getElements('input').each(function (n) { n.removeProperty('checked'); }); }); this.addEvent('onComplete', function () { el = this.elements[this.active]; if (!el.getStyle('width').toInt()) { this.container.set('styles', { 'width': this.container.getStyle('width').toInt() - el.fullWidth }); } this.active = null; }); for (var i = 0, l = this.togglers.length; i < l; i++) this.addSection(this.togglers[i], this.elements[i]); this.elements.each(function (el, i) { var cbs = el.getElements('input.selector').length; var cba = 0; el.getElements('input.selector').each(function (n) { if (n.getProperty('checked')) { this.togglers[i].setProperty('checked', 'checked'); cba += 1; } }, this); if (cbs > 0 && cbs === cba && el.getElement('input.branch-selector') != null) { el.getElement('input.branch-selector').setProperty('checked', 'checked'); } if (cba) { this.fireEvent('onActive', [this.togglers[i], el]); } else { for (var fx in this.effects) el.setStyle(fx, 0); } el.getElement('dt').getElement('input').addEvent('change', function (e) { if (e.target.getProperty('checked')) { el.getElements('dd').each(function (dd) { dd.getElement('input').setProperty('checked', 'checked'); }); } else { el.getElements('dd').each(function (dd) { dd.getElement('input').removeProperty('checked'); }); } }); }, this); }, addSection: function (toggler, element, pos) { toggler = document.id(toggler); element = document.id(element); var test = this.togglers.contains(toggler); var len = this.togglers.length; this.togglers.include(toggler); this.elements.include(element); if (len && (!test || pos)) { pos = Array.pick(pos, len - 1); toggler.inject(this.togglers[pos], 'before'); element.inject(toggler, 'after'); } else if (this.container && !test) { toggler.inject(this.container); element.inject(this.container); } var idx = this.togglers.indexOf(toggler); toggler.addEvent('click', this.toggle.bind(this, idx)); if (this.options.width) element.set('styles', { 'padding-left': 0, 'border-left': 'none', 'padding-right': 0, 'border-right': 'none' }); element.fullOpacity = 1; if (this.options.fixedWidth) element.fullWidth = this.options.fixedWidth; if (this.options.fixedHeight) element.fullHeight = this.options.fixedHeight; element.set('styles', {'overflow': 'hidden'}); return this; }, toggle: function (index) { index = (typeOf(index) == 'element') ? this.elements.indexOf(index) : index; if (this.timer && this.options.wait) return this; this.active = index; var obj = {}; obj[index] = {}; var el = this.elements[index]; if (this.togglers[index].getProperty('checked')) { for (var fx in this.effects) obj[index][fx] = el[this.effects[fx]]; this.start(obj); this.fireEvent('onActive', [this.togglers[index], el]); } else { for (var fx in this.effects) obj[index][fx] = 0; this.start(obj); this.fireEvent('onBackground', [this.togglers[index], el]); } return this; } }); window.addEvent('domready', function () { Filter = new FinderFilter(document.getElements('input.toggler'), document.getElements('dl.checklist'), document.id('finder-filter-container'), document.id('finder-filter-window')); document.id('tax-select-all').addEvent('change', function () { if (document.id('tax-select-all').getProperty('checked')) { document.id('finder-filter-window').getElements('input').each(function (input) { if (input.getProperty('id') != 'tax-select-all') { input.removeProperty('checked'); } }); } }); });
JavaScript
window.addEvent('domready', function () { sm = document.id('system-message'); if (sm) { sm.addEvent('check', function () { open = 0; messages = this.getElements('li'); for (i = 0, n = messages.length; i < n; i++) { if (messages[i].getProperty('hidden') != 'hidden') { open++; } } if (open < 1) { this.remove(); } }); } function hideWarning(e) { new Json.Remote(this.getProperty('link') + '&format=json', { linkId: this.getProperty('id'), onComplete: function (response) { if (response.error == false) { document.id(this.options.linkId).fireEvent('hide'); document.id('system-message').fireEvent('check'); } else { alert(response.message); } } }).send(); } document.id('a.hide-warning').each(function (a) { a.setProperty('link', a.getProperty('href')); a.setProperty('href', 'javascript: void(0);'); a.addEvent('hide', function () { this.getParent().setProperty('hidden', 'hidden'); var mySlider = new Fx.Slide(this.getParent(), { duration: 300 }); mySlider.slideOut(); }); // TODO: bindWithEvent deprecated in MT 1.3 a.addEvent('click', hideWarning.bindWithEvent(a)); }); });
JavaScript
var Highlighter = new Class({ options: { autoUnhighlight: true, caseSensitive: false, startElement: false, endElement: false, elements: new Array(), className: 'highlight', onlyWords: true, tag: 'span' }, initialize: function (options) { this.setOptions(options); this.getElements(this.options.startElement, this.options.endElement); this.words = []; }, highlight: function (words) { if (words.constructor === String) { words = [words]; } if (this.options.autoUnhighlight) { this.unhighlight(words); } var pattern = this.options.onlyWords ? '\b' + pattern + '\b' : '(' + words.join('\\b|\\b') + ')'; var regex = new RegExp(pattern, this.options.caseSensitive ? '' : 'i'); this.options.elements.each(function (el) { this.recurse(el, regex, this.options.className); }, this); return this; }, unhighlight: function (words) { if (words.constructor === String) { words = [words]; } words.each(function (word) { word = (this.options.caseSensitive ? word : word.toUpperCase()); if (this.words[word]) { var elements = $$(this.words[word]); elements.setProperty('class', ''); elements.each(function (el) { var tn = document.createTextNode(el.getText()); el.getParent().replaceChild(tn, el); }); } }, this); return this; }, recurse: function (node, regex, klass) { if (node.nodeType === 3) { var match = node.data.match(regex); if (match) { var highlight = new Element(this.options.tag); highlight.addClass(klass); var wordNode = node.splitText(match.index); wordNode.splitText(match[0].length); var wordClone = wordNode.cloneNode(true); highlight.appendChild(wordClone); wordNode.parentNode.replaceChild(highlight, wordNode); highlight.setProperty('rel', highlight.get('text')); var comparer = highlight.get('text'); if (!this.options.caseSensitive) { comparer = highlight.get('text').toUpperCase(); } if (!this.words[comparer]) { this.words[comparer] = []; } this.words[comparer].push(highlight); return 1; } } else if ((node.nodeType === 1 && node.childNodes) && !/(script|style|textarea|iframe)/i.test(node.tagName) && !(node.tagName === this.options.tag.toUpperCase() && node.className === klass)) { for (var i = 0; i < node.childNodes.length; i++) { i += this.recurse(node.childNodes[i], regex, klass); } } return 0; }, getElements: function (start, end) { var next = start.getNext(); if (next.id != end.id) { this.options.elements.include(next); this.getElements(next, end); } } }); Highlighter.implement(new Options); window.addEvent('domready', function () { var start = document.id('highlighter-start'); var end = document.id('highlighter-end'); if (!start || !end || !window.highlight) { return true; } highlighter = new Highlighter({ startElement: start, endElement: end, autoUnhighlight: true, onlyWords: false }).highlight(window.highlight); start.dispose(); end.dispose(); });
JavaScript
/** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * JMediaManager behavior for media component * * @package Joomla.Extensions * @subpackage Media * @since 1.5 */ (function() { var MediaManager = this.MediaManager = { initialize: function() { this.folderframe = document.id('folderframe'); this.folderpath = document.id('folderpath'); this.updatepaths = $$('input.update-folder'); this.frame = window.frames['folderframe']; this.frameurl = this.frame.location.href; //this.frameurl = window.frames['folderframe'].location.href; this.tree = new MooTreeControl({ div: 'media-tree_tree', mode: 'folders', grid: true, theme: '../media/system/images/mootree.gif', onClick: function(node){ target = node.data.target != null ? node.data.target : '_self'; // Get the current URL. uri = this._getUriObject(this.frameurl); current = uri.file+'?'+uri.query; if (current != 'undefined?undefined' && current != node.data.url) { window.frames[target].location.href = node.data.url; } }.bind(this) },{ text: '', open: true, data: { url: 'index.php?option=com_media&view=mediaList&tmpl=component', target: 'folderframe'}}); this.tree.adopt('media-tree'); }, submit: function(task) { form = window.frames['folderframe'].document.id('mediamanager-form'); form.task.value = task; if (document.id('username')) { form.username.value = document.id('username').value; form.password.value = document.id('password').value; } form.submit(); }, onloadframe: function() { // Update the frame url this.frameurl = this.frame.location.href; var folder = this.getFolder(); if (folder) { this.updatepaths.each(function(path){ path.value =folder; }); this.folderpath.value = basepath+'/'+folder; node = this.tree.get('node_'+folder); node.toggle(false, true); } else { this.updatepaths.each(function(path){ path.value = ''; }); this.folderpath.value = basepath; node = this.tree.root; } if (node) { this.tree.select(node, true); } document.id(viewstyle).addClass('active'); a = this._getUriObject(document.id('uploadForm').getProperty('action')); q = new Hash(this._getQueryObject(a.query)); q.set('folder', folder); var query = []; q.each(function(v, k){ if (v != null) { this.push(k+'='+v); } }, query); a.query = query.join('&'); if (a.port) { document.id('uploadForm').setProperty('action', a.scheme+'://'+a.domain+':'+a.port+a.path+'?'+a.query); } else { document.id('uploadForm').setProperty('action', a.scheme+'://'+a.domain+a.path+'?'+a.query); } }, oncreatefolder: function() { if (document.id('foldername').value.length) { document.id('dirpath').value = this.getFolder(); Joomla.submitbutton('createfolder'); } }, setViewType: function(type) { document.id(type).addClass('active'); document.id(viewstyle).removeClass('active'); viewstyle = type; var folder = this.getFolder(); this._setFrameUrl('index.php?option=com_media&view=mediaList&tmpl=component&folder='+folder+'&layout='+type); }, refreshFrame: function() { this._setFrameUrl(); }, getFolder: function() { var url = this.frame.location.search.substring(1); var args = this.parseQuery(url); if (args['folder'] == "undefined") { args['folder'] = ""; } return args['folder']; }, parseQuery: function(query) { var params = new Object(); if (!query) { return params; } var pairs = query.split(/[;&]/); for ( var i = 0; i < pairs.length; i++ ) { var KeyVal = pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) { continue; } var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ).replace(/\+ /g, ' '); params[key] = val; } return params; }, _setFrameUrl: function(url) { if (url != null) { this.frameurl = url; } this.frame.location.href = this.frameurl; }, _getQueryObject: function(q) { var vars = q.split(/[&;]/); var rs = {}; if (vars.length) vars.each(function(val) { var keys = val.split('='); if (keys.length && keys.length == 2) rs[encodeURIComponent(keys[0])] = encodeURIComponent(keys[1]); }); return rs; }, _getUriObject: function(u){ var bits = u.match(/^(?:([^:\/?#.]+):)?(?:\/\/)?(([^:\/?#]*)(?::(\d*))?)((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[\?#]|$)))*\/?)?([^?#\/]*))?(?:\?([^#]*))?(?:#(.*))?/); return (bits) ? bits.associate(['uri', 'scheme', 'authority', 'domain', 'port', 'path', 'directory', 'file', 'query', 'fragment']) : null; } }; })(document.id); window.addEvent('domready', function(){ // Added to populate data on iframe load MediaManager.initialize(); MediaManager.trace = 'start'; document.updateUploader = function() { MediaManager.onloadframe(); }; MediaManager.onloadframe(); });
JavaScript
/** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * JImageManager behavior for media component * * @package Joomla.Extensions * @subpackage Media * @since 1.5 */ (function() { var ImageManager = this.ImageManager = { initialize: function() { o = this._getUriObject(window.self.location.href); //console.log(o); q = new Hash(this._getQueryObject(o.query)); this.editor = decodeURIComponent(q.get('e_name')); // Setup image manager fields object this.fields = new Object(); this.fields.url = document.id("f_url"); this.fields.alt = document.id("f_alt"); this.fields.align = document.id("f_align"); this.fields.title = document.id("f_title"); this.fields.caption = document.id("f_caption"); // Setup image listing objects this.folderlist = document.id('folderlist'); this.frame = window.frames['imageframe']; this.frameurl = this.frame.location.href; // Setup imave listing frame this.imageframe = document.id('imageframe'); this.imageframe.manager = this; this.imageframe.addEvent('load', function(){ ImageManager.onloadimageview(); }); // Setup folder up button this.upbutton = document.id('upbutton'); this.upbutton.removeEvents('click'); this.upbutton.addEvent('click', function(){ ImageManager.upFolder(); }); }, onloadimageview: function() { // Update the frame url this.frameurl = this.frame.location.href; var folder = this.getImageFolder(); for(var i = 0; i < this.folderlist.length; i++) { if(folder == this.folderlist.options[i].value) { this.folderlist.selectedIndex = i; break; } } a = this._getUriObject(document.id('uploadForm').getProperty('action')); //console.log(a); q = new Hash(this._getQueryObject(a.query)); q.set('folder', folder); var query = []; q.each(function(v, k){ if (v !== null) { this.push(k+'='+v); } }, query); a.query = query.join('&'); var portString = ''; if (typeof(a.port) !== 'undefined' && a.port != 80) { portString = ':'+a.port; } document.id('uploadForm').setProperty('action', a.scheme+'://'+a.domain+portString+a.path+'?'+a.query); }, getImageFolder: function() { var url = this.frame.location.search.substring(1); var args = this.parseQuery(url); return args['folder']; }, onok: function() { extra = ''; // Get the image tag field information var url = this.fields.url.get('value'); var alt = this.fields.alt.get('value'); var align = this.fields.align.get('value'); var title = this.fields.title.get('value'); var caption = this.fields.caption.get('value'); if (url != '') { // Set alt attribute if (alt != '') { extra = extra + 'alt="'+alt+'" '; } else { extra = extra + 'alt="" '; } // Set align attribute if (align != '') { extra = extra + 'align="'+align+'" '; } // Set align attribute if (title != '') { extra = extra + 'title="'+title+'" '; } // Set align attribute if (caption != '') { extra = extra + 'class="caption" '; } var tag = "<img src=\""+url+"\" "+extra+"/>"; } window.parent.jInsertEditorText(tag, this.editor); return false; }, setFolder: function(folder,asset,author) { //this.showMessage('Loading'); for(var i = 0; i < this.folderlist.length; i++) { if(folder == this.folderlist.options[i].value) { this.folderlist.selectedIndex = i; break; } } this.frame.location.href='index.php?option=com_media&view=imagesList&tmpl=component&folder=' + folder + '&asset=' + asset + '&author=' + author; }, getFolder: function() { return this.folderlist.get('value'); }, upFolder: function() { var currentFolder = this.getFolder(); if(currentFolder.length < 2) { return false; } var folders = currentFolder.split('/'); var search = ''; for(var i = 0; i < folders.length - 1; i++) { search += folders[i]; search += '/'; } // remove the trailing slash search = search.substring(0, search.length - 1); for(var i = 0; i < this.folderlist.length; i++) { var thisFolder = this.folderlist.options[i].value; if(thisFolder == search) { this.folderlist.selectedIndex = i; var newFolder = this.folderlist.options[i].value; this.setFolder(newFolder); break; } } }, populateFields: function(file) { document.id("f_url").value = image_base_path+file; }, showMessage: function(text) { var message = document.id('message'); var messages = document.id('messages'); if(message.firstChild) message.removeChild(message.firstChild); message.appendChild(document.createTextNode(text)); messages.style.display = "block"; }, parseQuery: function(query) { var params = new Object(); if (!query) { return params; } var pairs = query.split(/[;&]/); for ( var i = 0; i < pairs.length; i++ ) { var KeyVal = pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) { continue; } var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ).replace(/\+ /g, ' '); params[key] = val; } return params; }, refreshFrame: function() { this._setFrameUrl(); }, _setFrameUrl: function(url) { if (url != null) { this.frameurl = url; } this.frame.location.href = this.frameurl; }, _getQueryObject: function(q) { var vars = q.split(/[&;]/); var rs = {}; if (vars.length) vars.each(function(val) { var keys = val.split('='); if (keys.length && keys.length == 2) rs[encodeURIComponent(keys[0])] = encodeURIComponent(keys[1]); }); return rs; }, _getUriObject: function(u){ var bits = u.match(/^(?:([^:\/?#.]+):)?(?:\/\/)?(([^:\/?#]*)(?::(\d*))?)((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[\?#]|$)))*\/?)?([^?#\/]*))?(?:\?([^#]*))?(?:#(.*))?/); return (bits) ? bits.associate(['uri', 'scheme', 'authority', 'domain', 'port', 'path', 'directory', 'file', 'query', 'fragment']) : null; } }; })(document.id); window.addEvent('domready', function(){ ImageManager.initialize(); });
JavaScript
/** * @package Joomla.JavaScript * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // Only define the Joomla namespace if not defined. if (typeof(Joomla) === 'undefined') { var Joomla = {}; } /** * JCombobox JavaScript behavior. * * Inspired by: Subrata Chakrabarty <http://chakrabarty.com/editable_dropdown_samplecode.html> * * @package Joomla.JavaScript * @since 1.6 */ Joomla.combobox = {}; Joomla.combobox.transform = function(el, options) { // Add the editable option to the select. var o = new Element('option', {'class':'custom'}).set('text', Joomla.JText._('ComboBoxInitString', 'type custom...')); o.inject(el, 'top'); document.id(el).set('changeType', 'manual'); // Add a key press event handler. el.addEvent('keypress', function(e){ // The change in selected option was browser behavior. if ((this.options.selectedIndex != 0) && (this.get('changeType') == 'auto')) { this.options.selectedIndex = 0; this.set('changeType', 'manual'); } // Check to see if the character is valid. if ((e.code > 47 && e.code < 59) || (e.code > 62 && e.code < 127) || (e.code == 32)) { var validChar = true; } else { var validChar = false; } // If the editable option is selected, proceed. if (this.options.selectedIndex == 0) { // Get the custom string for editing. var customString = this.options[0].value; // If the string is being edited for the first time, nullify it. if ((validChar == true) || (e.key == 'backspace')) { if (customString == Joomla.JText._('ComboBoxInitString', 'type custom...')) { customString = ''; } } // If the backspace key was used, remove a character from the end of the string. if (e.key == 'backspace') { customString = customString.substring(0, customString.length - 1); if (customString == '') { customString = Joomla.JText._('ComboBoxInitString', 'type custom...'); } // Indicate that the change event was manually initiated. this.set('changeType', 'manual'); } // Handle valid characters to add to the editable option. if (validChar == true) { // Concatenate the new character to the custom string. customString += String.fromCharCode(e.code); } // Set the new custom string into the editable select option. this.options.selectedIndex = 0; this.options[0].text = customString; this.options[0].value = customString; e.stop(); } }); // Add a change event handler. el.addEvent('change', function(e){ // The change in selected option was browser behavior. if ((this.options.selectedIndex != 0) && (this.get('changeType') == 'auto')) { this.options.selectedIndex = 0; this.set('changeType', 'manual'); } }); // Add a keydown event handler. el.addEvent('keydown', function(e){ // Stop the backspace key from firing the back button of the browser. if (e.code == 8 || e.code == 127) { e.stop(); // Stopping the keydown event in WebKit stops the keypress event as well. if (Browser.Engine.webkit || Browser.Engine.trident) { this.fireEvent('keypress', e); } } if (this.options.selectedIndex == 0) { /* * In some browsers a feature exists to automatically jump to select options which * have the same letter typed as the first letter of the option. The following * section is designed to mitigate this issue when editing the custom option. * * Compare the entered character with the first character of all non-editable * select options. If they match, then we assume the change happened because of * the browser trying to auto-change for the given character. */ var character = String.fromCharCode(e.code).toLowerCase(); for (var i = 1; i < this.options.length; i++) { // Get the first character from the select option. var FirstChar = this.options[i].value.charAt(0).toLowerCase(); // If the first character matches the entered character, the change was automatic. if ((FirstChar == character)) { this.options.selectedIndex = 0; this.set('changeType', 'auto'); } } } }); // Add a keyup event handler. el.addEvent('keyup', function(e){ // If the left or right arrow keys are pressed, return to the editable option. if ((e.key == 'left') || (e.key == 'right')) { this.options.selectedIndex = 0; } // The change in selected option was browser behavior. if ((this.options.selectedIndex != 0) && (this.get('changeType') == 'auto')) { this.options.selectedIndex = 0; this.set('changeType', 'manual'); } }); }; // Load the combobox behavior into the Joomla namespace when the document is ready. window.addEvent('domready', function(){ $$('select.combobox').each(function(el){ Joomla.combobox.transform(el); }); });
JavaScript
/** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ Object.append(Browser.Features, { localstorage: (function() { return ('localStorage' in window) && window.localStorage !== null; })() }); /** * Tabs behavior * * @package Joomla! * @subpackage JavaScript * @since 1.5 */ var JTabs = new Class({ Implements: [Options, Events], options : { display: 0, useStorage: true, onActive: function(title, description) { description.setStyle('display', 'block'); title.addClass('open').removeClass('closed'); }, onBackground: function(title, description){ description.setStyle('display', 'none'); title.addClass('closed').removeClass('open'); }, titleSelector: 'dt', descriptionSelector: 'dd' }, initialize: function(dlist, options){ this.setOptions(options); this.dlist = document.id(dlist); this.titles = this.dlist.getChildren(this.options.titleSelector); this.descriptions = this.dlist.getChildren(this.options.descriptionSelector); this.content = new Element('div').inject(this.dlist, 'after').addClass('current'); this.storageName = 'jpanetabs_'+this.dlist.id; if (this.options.useStorage) { if (Browser.Features.localstorage) { this.options.display = localStorage[this.storageName]; } else { this.options.display = Cookie.read(this.storageName); } } if (this.options.display === null || this.options.display === undefined) { this.options.display = 0; } this.options.display = this.options.display.toInt().limit(0, this.titles.length-1); for (var i = 0, l = this.titles.length; i < l; i++) { var title = this.titles[i]; var description = this.descriptions[i]; title.setStyle('cursor', 'pointer'); title.addEvent('click', this.display.bind(this, i)); description.inject(this.content); } this.display(this.options.display); if (this.options.initialize) this.options.initialize.call(this); }, hideAllBut: function(but) { for (var i = 0, l = this.titles.length; i < l; i++) { if (i != but) this.fireEvent('onBackground', [this.titles[i], this.descriptions[i]]); } }, display: function(i) { this.hideAllBut(i); this.fireEvent('onActive', [this.titles[i], this.descriptions[i]]); if (this.options.useStorage) { if (Browser.Features.localstorage) { localStorage[this.storageName] = i; } else { Cookie.write(this.storageName, i); } } } });
JavaScript
/* --- MooTools: the javascript framework web build: - http://mootools.net/core/76bf47062d6c1983d66ce47ad66aa0e0 packager build: - packager build Core/Core Core/Array Core/String Core/Number Core/Function Core/Object Core/Event Core/Browser Core/Class Core/Class.Extras Core/Slick.Parser Core/Slick.Finder Core/Element Core/Element.Style Core/Element.Event Core/Element.Delegation Core/Element.Dimensions Core/Fx Core/Fx.CSS Core/Fx.Tween Core/Fx.Morph Core/Fx.Transitions Core/Request Core/Request.HTML Core/Request.JSON Core/Cookie Core/JSON Core/DOMReady Core/Swiff ... */ /* --- name: Core description: The heart of MooTools. license: MIT-style license. copyright: Copyright (c) 2006-2012 [Valerio Proietti](http://mad4milk.net/). authors: The MooTools production team (http://mootools.net/developers/) inspiration: - Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php) - Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php) provides: [Core, MooTools, Type, typeOf, instanceOf, Native] ... */ (function(){ this.MooTools = { version: '1.4.5', build: 'ab8ea8824dc3b24b6666867a2c4ed58ebb762cf0' }; // typeOf, instanceOf var typeOf = this.typeOf = function(item){ if (item == null) return 'null'; if (item.$family != null) return item.$family(); if (item.nodeName){ if (item.nodeType == 1) return 'element'; if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace'; } else if (typeof item.length == 'number'){ if (item.callee) return 'arguments'; if ('item' in item) return 'collection'; } return typeof item; }; var instanceOf = this.instanceOf = function(item, object){ if (item == null) return false; var constructor = item.$constructor || item.constructor; while (constructor){ if (constructor === object) return true; constructor = constructor.parent; } /*<ltIE8>*/ if (!item.hasOwnProperty) return false; /*</ltIE8>*/ return item instanceof object; }; // Function overloading var Function = this.Function; var enumerables = true; for (var i in {toString: 1}) enumerables = null; if (enumerables) enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor']; Function.prototype.overloadSetter = function(usePlural){ var self = this; return function(a, b){ if (a == null) return this; if (usePlural || typeof a != 'string'){ for (var k in a) self.call(this, k, a[k]); if (enumerables) for (var i = enumerables.length; i--;){ k = enumerables[i]; if (a.hasOwnProperty(k)) self.call(this, k, a[k]); } } else { self.call(this, a, b); } return this; }; }; Function.prototype.overloadGetter = function(usePlural){ var self = this; return function(a){ var args, result; if (typeof a != 'string') args = a; else if (arguments.length > 1) args = arguments; else if (usePlural) args = [a]; if (args){ result = {}; for (var i = 0; i < args.length; i++) result[args[i]] = self.call(this, args[i]); } else { result = self.call(this, a); } return result; }; }; Function.prototype.extend = function(key, value){ this[key] = value; }.overloadSetter(); Function.prototype.implement = function(key, value){ this.prototype[key] = value; }.overloadSetter(); // From var slice = Array.prototype.slice; Function.from = function(item){ return (typeOf(item) == 'function') ? item : function(){ return item; }; }; Array.from = function(item){ if (item == null) return []; return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : slice.call(item) : [item]; }; Number.from = function(item){ var number = parseFloat(item); return isFinite(number) ? number : null; }; String.from = function(item){ return item + ''; }; // hide, protect Function.implement({ hide: function(){ this.$hidden = true; return this; }, protect: function(){ this.$protected = true; return this; } }); // Type var Type = this.Type = function(name, object){ if (name){ var lower = name.toLowerCase(); var typeCheck = function(item){ return (typeOf(item) == lower); }; Type['is' + name] = typeCheck; if (object != null){ object.prototype.$family = (function(){ return lower; }).hide(); //<1.2compat> object.type = typeCheck; //</1.2compat> } } if (object == null) return null; object.extend(this); object.$constructor = Type; object.prototype.$constructor = object; return object; }; var toString = Object.prototype.toString; Type.isEnumerable = function(item){ return (item != null && typeof item.length == 'number' && toString.call(item) != '[object Function]' ); }; var hooks = {}; var hooksOf = function(object){ var type = typeOf(object.prototype); return hooks[type] || (hooks[type] = []); }; var implement = function(name, method){ if (method && method.$hidden) return; var hooks = hooksOf(this); for (var i = 0; i < hooks.length; i++){ var hook = hooks[i]; if (typeOf(hook) == 'type') implement.call(hook, name, method); else hook.call(this, name, method); } var previous = this.prototype[name]; if (previous == null || !previous.$protected) this.prototype[name] = method; if (this[name] == null && typeOf(method) == 'function') extend.call(this, name, function(item){ return method.apply(item, slice.call(arguments, 1)); }); }; var extend = function(name, method){ if (method && method.$hidden) return; var previous = this[name]; if (previous == null || !previous.$protected) this[name] = method; }; Type.implement({ implement: implement.overloadSetter(), extend: extend.overloadSetter(), alias: function(name, existing){ implement.call(this, name, this.prototype[existing]); }.overloadSetter(), mirror: function(hook){ hooksOf(this).push(hook); return this; } }); new Type('Type', Type); // Default Types var force = function(name, object, methods){ var isType = (object != Object), prototype = object.prototype; if (isType) object = new Type(name, object); for (var i = 0, l = methods.length; i < l; i++){ var key = methods[i], generic = object[key], proto = prototype[key]; if (generic) generic.protect(); if (isType && proto) object.implement(key, proto.protect()); } if (isType){ var methodsEnumerable = prototype.propertyIsEnumerable(methods[0]); object.forEachMethod = function(fn){ if (!methodsEnumerable) for (var i = 0, l = methods.length; i < l; i++){ fn.call(prototype, prototype[methods[i]], methods[i]); } for (var key in prototype) fn.call(prototype, prototype[key], key) }; } return force; }; force('String', String, [ 'charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', 'match', 'quote', 'replace', 'search', 'slice', 'split', 'substr', 'substring', 'trim', 'toLowerCase', 'toUpperCase' ])('Array', Array, [ 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice', 'indexOf', 'lastIndexOf', 'filter', 'forEach', 'every', 'map', 'some', 'reduce', 'reduceRight' ])('Number', Number, [ 'toExponential', 'toFixed', 'toLocaleString', 'toPrecision' ])('Function', Function, [ 'apply', 'call', 'bind' ])('RegExp', RegExp, [ 'exec', 'test' ])('Object', Object, [ 'create', 'defineProperty', 'defineProperties', 'keys', 'getPrototypeOf', 'getOwnPropertyDescriptor', 'getOwnPropertyNames', 'preventExtensions', 'isExtensible', 'seal', 'isSealed', 'freeze', 'isFrozen' ])('Date', Date, ['now']); Object.extend = extend.overloadSetter(); Date.extend('now', function(){ return +(new Date); }); new Type('Boolean', Boolean); // fixes NaN returning as Number Number.prototype.$family = function(){ return isFinite(this) ? 'number' : 'null'; }.hide(); // Number.random Number.extend('random', function(min, max){ return Math.floor(Math.random() * (max - min + 1) + min); }); // forEach, each var hasOwnProperty = Object.prototype.hasOwnProperty; Object.extend('forEach', function(object, fn, bind){ for (var key in object){ if (hasOwnProperty.call(object, key)) fn.call(bind, object[key], key, object); } }); Object.each = Object.forEach; Array.implement({ forEach: function(fn, bind){ for (var i = 0, l = this.length; i < l; i++){ if (i in this) fn.call(bind, this[i], i, this); } }, each: function(fn, bind){ Array.forEach(this, fn, bind); return this; } }); // Array & Object cloning, Object merging and appending var cloneOf = function(item){ switch (typeOf(item)){ case 'array': return item.clone(); case 'object': return Object.clone(item); default: return item; } }; Array.implement('clone', function(){ var i = this.length, clone = new Array(i); while (i--) clone[i] = cloneOf(this[i]); return clone; }); var mergeOne = function(source, key, current){ switch (typeOf(current)){ case 'object': if (typeOf(source[key]) == 'object') Object.merge(source[key], current); else source[key] = Object.clone(current); break; case 'array': source[key] = current.clone(); break; default: source[key] = current; } return source; }; Object.extend({ merge: function(source, k, v){ if (typeOf(k) == 'string') return mergeOne(source, k, v); for (var i = 1, l = arguments.length; i < l; i++){ var object = arguments[i]; for (var key in object) mergeOne(source, key, object[key]); } return source; }, clone: function(object){ var clone = {}; for (var key in object) clone[key] = cloneOf(object[key]); return clone; }, append: function(original){ for (var i = 1, l = arguments.length; i < l; i++){ var extended = arguments[i] || {}; for (var key in extended) original[key] = extended[key]; } return original; } }); // Object-less types ['Object', 'WhiteSpace', 'TextNode', 'Collection', 'Arguments'].each(function(name){ new Type(name); }); // Unique ID var UID = Date.now(); String.extend('uniqueID', function(){ return (UID++).toString(36); }); //<1.2compat> var Hash = this.Hash = new Type('Hash', function(object){ if (typeOf(object) == 'hash') object = Object.clone(object.getClean()); for (var key in object) this[key] = object[key]; return this; }); Hash.implement({ forEach: function(fn, bind){ Object.forEach(this, fn, bind); }, getClean: function(){ var clean = {}; for (var key in this){ if (this.hasOwnProperty(key)) clean[key] = this[key]; } return clean; }, getLength: function(){ var length = 0; for (var key in this){ if (this.hasOwnProperty(key)) length++; } return length; } }); Hash.alias('each', 'forEach'); Object.type = Type.isObject; var Native = this.Native = function(properties){ return new Type(properties.name, properties.initialize); }; Native.type = Type.type; Native.implement = function(objects, methods){ for (var i = 0; i < objects.length; i++) objects[i].implement(methods); return Native; }; var arrayType = Array.type; Array.type = function(item){ return instanceOf(item, Array) || arrayType(item); }; this.$A = function(item){ return Array.from(item).slice(); }; this.$arguments = function(i){ return function(){ return arguments[i]; }; }; this.$chk = function(obj){ return !!(obj || obj === 0); }; this.$clear = function(timer){ clearTimeout(timer); clearInterval(timer); return null; }; this.$defined = function(obj){ return (obj != null); }; this.$each = function(iterable, fn, bind){ var type = typeOf(iterable); ((type == 'arguments' || type == 'collection' || type == 'array' || type == 'elements') ? Array : Object).each(iterable, fn, bind); }; this.$empty = function(){}; this.$extend = function(original, extended){ return Object.append(original, extended); }; this.$H = function(object){ return new Hash(object); }; this.$merge = function(){ var args = Array.slice(arguments); args.unshift({}); return Object.merge.apply(null, args); }; this.$lambda = Function.from; this.$mixin = Object.merge; this.$random = Number.random; this.$splat = Array.from; this.$time = Date.now; this.$type = function(object){ var type = typeOf(object); if (type == 'elements') return 'array'; return (type == 'null') ? false : type; }; this.$unlink = function(object){ switch (typeOf(object)){ case 'object': return Object.clone(object); case 'array': return Array.clone(object); case 'hash': return new Hash(object); default: return object; } }; //</1.2compat> })(); /* --- name: Array description: Contains Array Prototypes like each, contains, and erase. license: MIT-style license. requires: Type provides: Array ... */ Array.implement({ /*<!ES5>*/ every: function(fn, bind){ for (var i = 0, l = this.length >>> 0; i < l; i++){ if ((i in this) && !fn.call(bind, this[i], i, this)) return false; } return true; }, filter: function(fn, bind){ var results = []; for (var value, i = 0, l = this.length >>> 0; i < l; i++) if (i in this){ value = this[i]; if (fn.call(bind, value, i, this)) results.push(value); } return results; }, indexOf: function(item, from){ var length = this.length >>> 0; for (var i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++){ if (this[i] === item) return i; } return -1; }, map: function(fn, bind){ var length = this.length >>> 0, results = Array(length); for (var i = 0; i < length; i++){ if (i in this) results[i] = fn.call(bind, this[i], i, this); } return results; }, some: function(fn, bind){ for (var i = 0, l = this.length >>> 0; i < l; i++){ if ((i in this) && fn.call(bind, this[i], i, this)) return true; } return false; }, /*</!ES5>*/ clean: function(){ return this.filter(function(item){ return item != null; }); }, invoke: function(methodName){ var args = Array.slice(arguments, 1); return this.map(function(item){ return item[methodName].apply(item, args); }); }, associate: function(keys){ var obj = {}, length = Math.min(this.length, keys.length); for (var i = 0; i < length; i++) obj[keys[i]] = this[i]; return obj; }, link: function(object){ var result = {}; for (var i = 0, l = this.length; i < l; i++){ for (var key in object){ if (object[key](this[i])){ result[key] = this[i]; delete object[key]; break; } } } return result; }, contains: function(item, from){ return this.indexOf(item, from) != -1; }, append: function(array){ this.push.apply(this, array); return this; }, getLast: function(){ return (this.length) ? this[this.length - 1] : null; }, getRandom: function(){ return (this.length) ? this[Number.random(0, this.length - 1)] : null; }, include: function(item){ if (!this.contains(item)) this.push(item); return this; }, combine: function(array){ for (var i = 0, l = array.length; i < l; i++) this.include(array[i]); return this; }, erase: function(item){ for (var i = this.length; i--;){ if (this[i] === item) this.splice(i, 1); } return this; }, empty: function(){ this.length = 0; return this; }, flatten: function(){ var array = []; for (var i = 0, l = this.length; i < l; i++){ var type = typeOf(this[i]); if (type == 'null') continue; array = array.concat((type == 'array' || type == 'collection' || type == 'arguments' || instanceOf(this[i], Array)) ? Array.flatten(this[i]) : this[i]); } return array; }, pick: function(){ for (var i = 0, l = this.length; i < l; i++){ if (this[i] != null) return this[i]; } return null; }, hexToRgb: function(array){ if (this.length != 3) return null; var rgb = this.map(function(value){ if (value.length == 1) value += value; return value.toInt(16); }); return (array) ? rgb : 'rgb(' + rgb + ')'; }, rgbToHex: function(array){ if (this.length < 3) return null; if (this.length == 4 && this[3] == 0 && !array) return 'transparent'; var hex = []; for (var i = 0; i < 3; i++){ var bit = (this[i] - 0).toString(16); hex.push((bit.length == 1) ? '0' + bit : bit); } return (array) ? hex : '#' + hex.join(''); } }); //<1.2compat> Array.alias('extend', 'append'); var $pick = function(){ return Array.from(arguments).pick(); }; //</1.2compat> /* --- name: String description: Contains String Prototypes like camelCase, capitalize, test, and toInt. license: MIT-style license. requires: Type provides: String ... */ String.implement({ test: function(regex, params){ return ((typeOf(regex) == 'regexp') ? regex : new RegExp('' + regex, params)).test(this); }, contains: function(string, separator){ return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : String(this).indexOf(string) > -1; }, trim: function(){ return String(this).replace(/^\s+|\s+$/g, ''); }, clean: function(){ return String(this).replace(/\s+/g, ' ').trim(); }, camelCase: function(){ return String(this).replace(/-\D/g, function(match){ return match.charAt(1).toUpperCase(); }); }, hyphenate: function(){ return String(this).replace(/[A-Z]/g, function(match){ return ('-' + match.charAt(0).toLowerCase()); }); }, capitalize: function(){ return String(this).replace(/\b[a-z]/g, function(match){ return match.toUpperCase(); }); }, escapeRegExp: function(){ return String(this).replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1'); }, toInt: function(base){ return parseInt(this, base || 10); }, toFloat: function(){ return parseFloat(this); }, hexToRgb: function(array){ var hex = String(this).match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); return (hex) ? hex.slice(1).hexToRgb(array) : null; }, rgbToHex: function(array){ var rgb = String(this).match(/\d{1,3}/g); return (rgb) ? rgb.rgbToHex(array) : null; }, substitute: function(object, regexp){ return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){ if (match.charAt(0) == '\\') return match.slice(1); return (object[name] != null) ? object[name] : ''; }); } }); /* --- name: Number description: Contains Number Prototypes like limit, round, times, and ceil. license: MIT-style license. requires: Type provides: Number ... */ Number.implement({ limit: function(min, max){ return Math.min(max, Math.max(min, this)); }, round: function(precision){ precision = Math.pow(10, precision || 0).toFixed(precision < 0 ? -precision : 0); return Math.round(this * precision) / precision; }, times: function(fn, bind){ for (var i = 0; i < this; i++) fn.call(bind, i, this); }, toFloat: function(){ return parseFloat(this); }, toInt: function(base){ return parseInt(this, base || 10); } }); Number.alias('each', 'times'); (function(math){ var methods = {}; math.each(function(name){ if (!Number[name]) methods[name] = function(){ return Math[name].apply(null, [this].concat(Array.from(arguments))); }; }); Number.implement(methods); })(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']); /* --- name: Function description: Contains Function Prototypes like create, bind, pass, and delay. license: MIT-style license. requires: Type provides: Function ... */ Function.extend({ attempt: function(){ for (var i = 0, l = arguments.length; i < l; i++){ try { return arguments[i](); } catch (e){} } return null; } }); Function.implement({ attempt: function(args, bind){ try { return this.apply(bind, Array.from(args)); } catch (e){} return null; }, /*<!ES5-bind>*/ bind: function(that){ var self = this, args = arguments.length > 1 ? Array.slice(arguments, 1) : null, F = function(){}; var bound = function(){ var context = that, length = arguments.length; if (this instanceof bound){ F.prototype = self.prototype; context = new F; } var result = (!args && !length) ? self.call(context) : self.apply(context, args && length ? args.concat(Array.slice(arguments)) : args || arguments); return context == that ? result : context; }; return bound; }, /*</!ES5-bind>*/ pass: function(args, bind){ var self = this; if (args != null) args = Array.from(args); return function(){ return self.apply(bind, args || arguments); }; }, delay: function(delay, bind, args){ return setTimeout(this.pass((args == null ? [] : args), bind), delay); }, periodical: function(periodical, bind, args){ return setInterval(this.pass((args == null ? [] : args), bind), periodical); } }); //<1.2compat> delete Function.prototype.bind; Function.implement({ create: function(options){ var self = this; options = options || {}; return function(event){ var args = options.arguments; args = (args != null) ? Array.from(args) : Array.slice(arguments, (options.event) ? 1 : 0); if (options.event) args = [event || window.event].extend(args); var returns = function(){ return self.apply(options.bind || null, args); }; if (options.delay) return setTimeout(returns, options.delay); if (options.periodical) return setInterval(returns, options.periodical); if (options.attempt) return Function.attempt(returns); return returns(); }; }, bind: function(bind, args){ var self = this; if (args != null) args = Array.from(args); return function(){ return self.apply(bind, args || arguments); }; }, bindWithEvent: function(bind, args){ var self = this; if (args != null) args = Array.from(args); return function(event){ return self.apply(bind, (args == null) ? arguments : [event].concat(args)); }; }, run: function(args, bind){ return this.apply(bind, Array.from(args)); } }); if (Object.create == Function.prototype.create) Object.create = null; var $try = Function.attempt; //</1.2compat> /* --- name: Object description: Object generic methods license: MIT-style license. requires: Type provides: [Object, Hash] ... */ (function(){ var hasOwnProperty = Object.prototype.hasOwnProperty; Object.extend({ subset: function(object, keys){ var results = {}; for (var i = 0, l = keys.length; i < l; i++){ var k = keys[i]; if (k in object) results[k] = object[k]; } return results; }, map: function(object, fn, bind){ var results = {}; for (var key in object){ if (hasOwnProperty.call(object, key)) results[key] = fn.call(bind, object[key], key, object); } return results; }, filter: function(object, fn, bind){ var results = {}; for (var key in object){ var value = object[key]; if (hasOwnProperty.call(object, key) && fn.call(bind, value, key, object)) results[key] = value; } return results; }, every: function(object, fn, bind){ for (var key in object){ if (hasOwnProperty.call(object, key) && !fn.call(bind, object[key], key)) return false; } return true; }, some: function(object, fn, bind){ for (var key in object){ if (hasOwnProperty.call(object, key) && fn.call(bind, object[key], key)) return true; } return false; }, keys: function(object){ var keys = []; for (var key in object){ if (hasOwnProperty.call(object, key)) keys.push(key); } return keys; }, values: function(object){ var values = []; for (var key in object){ if (hasOwnProperty.call(object, key)) values.push(object[key]); } return values; }, getLength: function(object){ return Object.keys(object).length; }, keyOf: function(object, value){ for (var key in object){ if (hasOwnProperty.call(object, key) && object[key] === value) return key; } return null; }, contains: function(object, value){ return Object.keyOf(object, value) != null; }, toQueryString: function(object, base){ var queryString = []; Object.each(object, function(value, key){ if (base) key = base + '[' + key + ']'; var result; switch (typeOf(value)){ case 'object': result = Object.toQueryString(value, key); break; case 'array': var qs = {}; value.each(function(val, i){ qs[i] = val; }); result = Object.toQueryString(qs, key); break; default: result = key + '=' + encodeURIComponent(value); } if (value != null) queryString.push(result); }); return queryString.join('&'); } }); })(); //<1.2compat> Hash.implement({ has: Object.prototype.hasOwnProperty, keyOf: function(value){ return Object.keyOf(this, value); }, hasValue: function(value){ return Object.contains(this, value); }, extend: function(properties){ Hash.each(properties || {}, function(value, key){ Hash.set(this, key, value); }, this); return this; }, combine: function(properties){ Hash.each(properties || {}, function(value, key){ Hash.include(this, key, value); }, this); return this; }, erase: function(key){ if (this.hasOwnProperty(key)) delete this[key]; return this; }, get: function(key){ return (this.hasOwnProperty(key)) ? this[key] : null; }, set: function(key, value){ if (!this[key] || this.hasOwnProperty(key)) this[key] = value; return this; }, empty: function(){ Hash.each(this, function(value, key){ delete this[key]; }, this); return this; }, include: function(key, value){ if (this[key] == null) this[key] = value; return this; }, map: function(fn, bind){ return new Hash(Object.map(this, fn, bind)); }, filter: function(fn, bind){ return new Hash(Object.filter(this, fn, bind)); }, every: function(fn, bind){ return Object.every(this, fn, bind); }, some: function(fn, bind){ return Object.some(this, fn, bind); }, getKeys: function(){ return Object.keys(this); }, getValues: function(){ return Object.values(this); }, toQueryString: function(base){ return Object.toQueryString(this, base); } }); Hash.extend = Object.append; Hash.alias({indexOf: 'keyOf', contains: 'hasValue'}); //</1.2compat> /* --- name: Browser description: The Browser Object. Contains Browser initialization, Window and Document, and the Browser Hash. license: MIT-style license. requires: [Array, Function, Number, String] provides: [Browser, Window, Document] ... */ (function(){ var document = this.document; var window = document.window = this; var ua = navigator.userAgent.toLowerCase(), platform = navigator.platform.toLowerCase(), UA = ua.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/) || [null, 'unknown', 0], mode = UA[1] == 'ie' && document.documentMode; var Browser = this.Browser = { extend: Function.prototype.extend, name: (UA[1] == 'version') ? UA[3] : UA[1], version: mode || parseFloat((UA[1] == 'opera' && UA[4]) ? UA[4] : UA[2]), Platform: { name: ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || platform.match(/mac|win|linux/) || ['other'])[0] }, Features: { xpath: !!(document.evaluate), air: !!(window.runtime), query: !!(document.querySelector), json: !!(window.JSON) }, Plugins: {} }; Browser[Browser.name] = true; Browser[Browser.name + parseInt(Browser.version, 10)] = true; Browser.Platform[Browser.Platform.name] = true; // Request Browser.Request = (function(){ var XMLHTTP = function(){ return new XMLHttpRequest(); }; var MSXML2 = function(){ return new ActiveXObject('MSXML2.XMLHTTP'); }; var MSXML = function(){ return new ActiveXObject('Microsoft.XMLHTTP'); }; return Function.attempt(function(){ XMLHTTP(); return XMLHTTP; }, function(){ MSXML2(); return MSXML2; }, function(){ MSXML(); return MSXML; }); })(); Browser.Features.xhr = !!(Browser.Request); // Flash detection var version = (Function.attempt(function(){ return navigator.plugins['Shockwave Flash'].description; }, function(){ return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); }) || '0 r0').match(/\d+/g); Browser.Plugins.Flash = { version: Number(version[0] || '0.' + version[1]) || 0, build: Number(version[2]) || 0 }; // String scripts Browser.exec = function(text){ if (!text) return text; if (window.execScript){ window.execScript(text); } else { var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.text = text; document.head.appendChild(script); document.head.removeChild(script); } return text; }; String.implement('stripScripts', function(exec){ var scripts = ''; var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){ scripts += code + '\n'; return ''; }); if (exec === true) Browser.exec(scripts); else if (typeOf(exec) == 'function') exec(scripts, text); return text; }); // Window, Document Browser.extend({ Document: this.Document, Window: this.Window, Element: this.Element, Event: this.Event }); this.Window = this.$constructor = new Type('Window', function(){}); this.$family = Function.from('window').hide(); Window.mirror(function(name, method){ window[name] = method; }); this.Document = document.$constructor = new Type('Document', function(){}); document.$family = Function.from('document').hide(); Document.mirror(function(name, method){ document[name] = method; }); document.html = document.documentElement; if (!document.head) document.head = document.getElementsByTagName('head')[0]; if (document.execCommand) try { document.execCommand("BackgroundImageCache", false, true); } catch (e){} /*<ltIE9>*/ if (this.attachEvent && !this.addEventListener){ var unloadEvent = function(){ this.detachEvent('onunload', unloadEvent); document.head = document.html = document.window = null; }; this.attachEvent('onunload', unloadEvent); } // IE fails on collections and <select>.options (refers to <select>) var arrayFrom = Array.from; try { arrayFrom(document.html.childNodes); } catch(e){ Array.from = function(item){ if (typeof item != 'string' && Type.isEnumerable(item) && typeOf(item) != 'array'){ var i = item.length, array = new Array(i); while (i--) array[i] = item[i]; return array; } return arrayFrom(item); }; var prototype = Array.prototype, slice = prototype.slice; ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice'].each(function(name){ var method = prototype[name]; Array[name] = function(item){ return method.apply(Array.from(item), slice.call(arguments, 1)); }; }); } /*</ltIE9>*/ //<1.2compat> if (Browser.Platform.ios) Browser.Platform.ipod = true; Browser.Engine = {}; var setEngine = function(name, version){ Browser.Engine.name = name; Browser.Engine[name + version] = true; Browser.Engine.version = version; }; if (Browser.ie){ Browser.Engine.trident = true; switch (Browser.version){ case 6: setEngine('trident', 4); break; case 7: setEngine('trident', 5); break; case 8: setEngine('trident', 6); } } if (Browser.firefox){ Browser.Engine.gecko = true; if (Browser.version >= 3) setEngine('gecko', 19); else setEngine('gecko', 18); } if (Browser.safari || Browser.chrome){ Browser.Engine.webkit = true; switch (Browser.version){ case 2: setEngine('webkit', 419); break; case 3: setEngine('webkit', 420); break; case 4: setEngine('webkit', 525); } } if (Browser.opera){ Browser.Engine.presto = true; if (Browser.version >= 9.6) setEngine('presto', 960); else if (Browser.version >= 9.5) setEngine('presto', 950); else setEngine('presto', 925); } if (Browser.name == 'unknown'){ switch ((ua.match(/(?:webkit|khtml|gecko)/) || [])[0]){ case 'webkit': case 'khtml': Browser.Engine.webkit = true; break; case 'gecko': Browser.Engine.gecko = true; } } this.$exec = Browser.exec; //</1.2compat> })(); /* --- name: Event description: Contains the Event Type, to make the event object cross-browser. license: MIT-style license. requires: [Window, Document, Array, Function, String, Object] provides: Event ... */ (function() { var _keys = {}; var DOMEvent = this.DOMEvent = new Type('DOMEvent', function(event, win){ if (!win) win = window; event = event || win.event; if (event.$extended) return event; this.event = event; this.$extended = true; this.shift = event.shiftKey; this.control = event.ctrlKey; this.alt = event.altKey; this.meta = event.metaKey; var type = this.type = event.type; var target = event.target || event.srcElement; while (target && target.nodeType == 3) target = target.parentNode; this.target = document.id(target); if (type.indexOf('key') == 0){ var code = this.code = (event.which || event.keyCode); this.key = _keys[code]/*<1.3compat>*/ || Object.keyOf(Event.Keys, code)/*</1.3compat>*/; if (type == 'keydown'){ if (code > 111 && code < 124) this.key = 'f' + (code - 111); else if (code > 95 && code < 106) this.key = code - 96; } if (this.key == null) this.key = String.fromCharCode(code).toLowerCase(); } else if (type == 'click' || type == 'dblclick' || type == 'contextmenu' || type == 'DOMMouseScroll' || type.indexOf('mouse') == 0){ var doc = win.document; doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; this.page = { x: (event.pageX != null) ? event.pageX : event.clientX + doc.scrollLeft, y: (event.pageY != null) ? event.pageY : event.clientY + doc.scrollTop }; this.client = { x: (event.pageX != null) ? event.pageX - win.pageXOffset : event.clientX, y: (event.pageY != null) ? event.pageY - win.pageYOffset : event.clientY }; if (type == 'DOMMouseScroll' || type == 'mousewheel') this.wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3; this.rightClick = (event.which == 3 || event.button == 2); if (type == 'mouseover' || type == 'mouseout'){ var related = event.relatedTarget || event[(type == 'mouseover' ? 'from' : 'to') + 'Element']; while (related && related.nodeType == 3) related = related.parentNode; this.relatedTarget = document.id(related); } } else if (type.indexOf('touch') == 0 || type.indexOf('gesture') == 0){ this.rotation = event.rotation; this.scale = event.scale; this.targetTouches = event.targetTouches; this.changedTouches = event.changedTouches; var touches = this.touches = event.touches; if (touches && touches[0]){ var touch = touches[0]; this.page = {x: touch.pageX, y: touch.pageY}; this.client = {x: touch.clientX, y: touch.clientY}; } } if (!this.client) this.client = {}; if (!this.page) this.page = {}; }); DOMEvent.implement({ stop: function(){ return this.preventDefault().stopPropagation(); }, stopPropagation: function(){ if (this.event.stopPropagation) this.event.stopPropagation(); else this.event.cancelBubble = true; return this; }, preventDefault: function(){ if (this.event.preventDefault) this.event.preventDefault(); else this.event.returnValue = false; return this; } }); DOMEvent.defineKey = function(code, key){ _keys[code] = key; return this; }; DOMEvent.defineKeys = DOMEvent.defineKey.overloadSetter(true); DOMEvent.defineKeys({ '38': 'up', '40': 'down', '37': 'left', '39': 'right', '27': 'esc', '32': 'space', '8': 'backspace', '9': 'tab', '46': 'delete', '13': 'enter' }); })(); /*<1.3compat>*/ var Event = DOMEvent; Event.Keys = {}; /*</1.3compat>*/ /*<1.2compat>*/ Event.Keys = new Hash(Event.Keys); /*</1.2compat>*/ /* --- name: Class description: Contains the Class Function for easily creating, extending, and implementing reusable Classes. license: MIT-style license. requires: [Array, String, Function, Number] provides: Class ... */ (function(){ var Class = this.Class = new Type('Class', function(params){ if (instanceOf(params, Function)) params = {initialize: params}; var newClass = function(){ reset(this); if (newClass.$prototyping) return this; this.$caller = null; var value = (this.initialize) ? this.initialize.apply(this, arguments) : this; this.$caller = this.caller = null; return value; }.extend(this).implement(params); newClass.$constructor = Class; newClass.prototype.$constructor = newClass; newClass.prototype.parent = parent; return newClass; }); var parent = function(){ if (!this.$caller) throw new Error('The method "parent" cannot be called.'); var name = this.$caller.$name, parent = this.$caller.$owner.parent, previous = (parent) ? parent.prototype[name] : null; if (!previous) throw new Error('The method "' + name + '" has no parent.'); return previous.apply(this, arguments); }; var reset = function(object){ for (var key in object){ var value = object[key]; switch (typeOf(value)){ case 'object': var F = function(){}; F.prototype = value; object[key] = reset(new F); break; case 'array': object[key] = value.clone(); break; } } return object; }; var wrap = function(self, key, method){ if (method.$origin) method = method.$origin; var wrapper = function(){ if (method.$protected && this.$caller == null) throw new Error('The method "' + key + '" cannot be called.'); var caller = this.caller, current = this.$caller; this.caller = current; this.$caller = wrapper; var result = method.apply(this, arguments); this.$caller = current; this.caller = caller; return result; }.extend({$owner: self, $origin: method, $name: key}); return wrapper; }; var implement = function(key, value, retain){ if (Class.Mutators.hasOwnProperty(key)){ value = Class.Mutators[key].call(this, value); if (value == null) return this; } if (typeOf(value) == 'function'){ if (value.$hidden) return this; this.prototype[key] = (retain) ? value : wrap(this, key, value); } else { Object.merge(this.prototype, key, value); } return this; }; var getInstance = function(klass){ klass.$prototyping = true; var proto = new klass; delete klass.$prototyping; return proto; }; Class.implement('implement', implement.overloadSetter()); Class.Mutators = { Extends: function(parent){ this.parent = parent; this.prototype = getInstance(parent); }, Implements: function(items){ Array.from(items).each(function(item){ var instance = new item; for (var key in instance) implement.call(this, key, instance[key], true); }, this); } }; })(); /* --- name: Class.Extras description: Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks. license: MIT-style license. requires: Class provides: [Class.Extras, Chain, Events, Options] ... */ (function(){ this.Chain = new Class({ $chain: [], chain: function(){ this.$chain.append(Array.flatten(arguments)); return this; }, callChain: function(){ return (this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false; }, clearChain: function(){ this.$chain.empty(); return this; } }); var removeOn = function(string){ return string.replace(/^on([A-Z])/, function(full, first){ return first.toLowerCase(); }); }; this.Events = new Class({ $events: {}, addEvent: function(type, fn, internal){ type = removeOn(type); /*<1.2compat>*/ if (fn == $empty) return this; /*</1.2compat>*/ this.$events[type] = (this.$events[type] || []).include(fn); if (internal) fn.internal = true; return this; }, addEvents: function(events){ for (var type in events) this.addEvent(type, events[type]); return this; }, fireEvent: function(type, args, delay){ type = removeOn(type); var events = this.$events[type]; if (!events) return this; args = Array.from(args); events.each(function(fn){ if (delay) fn.delay(delay, this, args); else fn.apply(this, args); }, this); return this; }, removeEvent: function(type, fn){ type = removeOn(type); var events = this.$events[type]; if (events && !fn.internal){ var index = events.indexOf(fn); if (index != -1) delete events[index]; } return this; }, removeEvents: function(events){ var type; if (typeOf(events) == 'object'){ for (type in events) this.removeEvent(type, events[type]); return this; } if (events) events = removeOn(events); for (type in this.$events){ if (events && events != type) continue; var fns = this.$events[type]; for (var i = fns.length; i--;) if (i in fns){ this.removeEvent(type, fns[i]); } } return this; } }); this.Options = new Class({ setOptions: function(){ var options = this.options = Object.merge.apply(null, [{}, this.options].append(arguments)); if (this.addEvent) for (var option in options){ if (typeOf(options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue; this.addEvent(option, options[option]); delete options[option]; } return this; } }); })(); /* --- name: Slick.Parser description: Standalone CSS3 Selector parser provides: Slick.Parser ... */ ;(function(){ var parsed, separatorIndex, combinatorIndex, reversed, cache = {}, reverseCache = {}, reUnescape = /\\/g; var parse = function(expression, isReversed){ if (expression == null) return null; if (expression.Slick === true) return expression; expression = ('' + expression).replace(/^\s+|\s+$/g, ''); reversed = !!isReversed; var currentCache = (reversed) ? reverseCache : cache; if (currentCache[expression]) return currentCache[expression]; parsed = { Slick: true, expressions: [], raw: expression, reverse: function(){ return parse(this.raw, true); } }; separatorIndex = -1; while (expression != (expression = expression.replace(regexp, parser))); parsed.length = parsed.expressions.length; return currentCache[parsed.raw] = (reversed) ? reverse(parsed) : parsed; }; var reverseCombinator = function(combinator){ if (combinator === '!') return ' '; else if (combinator === ' ') return '!'; else if ((/^!/).test(combinator)) return combinator.replace(/^!/, ''); else return '!' + combinator; }; var reverse = function(expression){ var expressions = expression.expressions; for (var i = 0; i < expressions.length; i++){ var exp = expressions[i]; var last = {parts: [], tag: '*', combinator: reverseCombinator(exp[0].combinator)}; for (var j = 0; j < exp.length; j++){ var cexp = exp[j]; if (!cexp.reverseCombinator) cexp.reverseCombinator = ' '; cexp.combinator = cexp.reverseCombinator; delete cexp.reverseCombinator; } exp.reverse().push(last); } return expression; }; var escapeRegExp = function(string){// Credit: XRegExp 0.6.1 (c) 2007-2008 Steven Levithan <http://stevenlevithan.com/regex/xregexp/> MIT License return string.replace(/[-[\]{}()*+?.\\^$|,#\s]/g, function(match){ return '\\' + match; }); }; var regexp = new RegExp( /* #!/usr/bin/env ruby puts "\t\t" + DATA.read.gsub(/\(\?x\)|\s+#.*$|\s+|\\$|\\n/,'') __END__ "(?x)^(?:\ \\s* ( , ) \\s* # Separator \n\ | \\s* ( <combinator>+ ) \\s* # Combinator \n\ | ( \\s+ ) # CombinatorChildren \n\ | ( <unicode>+ | \\* ) # Tag \n\ | \\# ( <unicode>+ ) # ID \n\ | \\. ( <unicode>+ ) # ClassName \n\ | # Attribute \n\ \\[ \ \\s* (<unicode1>+) (?: \ \\s* ([*^$!~|]?=) (?: \ \\s* (?:\ ([\"']?)(.*?)\\9 \ )\ ) \ )? \\s* \ \\](?!\\]) \n\ | :+ ( <unicode>+ )(?:\ \\( (?:\ (?:([\"'])([^\\12]*)\\12)|((?:\\([^)]+\\)|[^()]*)+)\ ) \\)\ )?\ )" */ "^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)" .replace(/<combinator>/, '[' + escapeRegExp(">+~`!@$%^&={}\\;</") + ']') .replace(/<unicode>/g, '(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])') .replace(/<unicode1>/g, '(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])') ); function parser( rawMatch, separator, combinator, combinatorChildren, tagName, id, className, attributeKey, attributeOperator, attributeQuote, attributeValue, pseudoMarker, pseudoClass, pseudoQuote, pseudoClassQuotedValue, pseudoClassValue ){ if (separator || separatorIndex === -1){ parsed.expressions[++separatorIndex] = []; combinatorIndex = -1; if (separator) return ''; } if (combinator || combinatorChildren || combinatorIndex === -1){ combinator = combinator || ' '; var currentSeparator = parsed.expressions[separatorIndex]; if (reversed && currentSeparator[combinatorIndex]) currentSeparator[combinatorIndex].reverseCombinator = reverseCombinator(combinator); currentSeparator[++combinatorIndex] = {combinator: combinator, tag: '*'}; } var currentParsed = parsed.expressions[separatorIndex][combinatorIndex]; if (tagName){ currentParsed.tag = tagName.replace(reUnescape, ''); } else if (id){ currentParsed.id = id.replace(reUnescape, ''); } else if (className){ className = className.replace(reUnescape, ''); if (!currentParsed.classList) currentParsed.classList = []; if (!currentParsed.classes) currentParsed.classes = []; currentParsed.classList.push(className); currentParsed.classes.push({ value: className, regexp: new RegExp('(^|\\s)' + escapeRegExp(className) + '(\\s|$)') }); } else if (pseudoClass){ pseudoClassValue = pseudoClassValue || pseudoClassQuotedValue; pseudoClassValue = pseudoClassValue ? pseudoClassValue.replace(reUnescape, '') : null; if (!currentParsed.pseudos) currentParsed.pseudos = []; currentParsed.pseudos.push({ key: pseudoClass.replace(reUnescape, ''), value: pseudoClassValue, type: pseudoMarker.length == 1 ? 'class' : 'element' }); } else if (attributeKey){ attributeKey = attributeKey.replace(reUnescape, ''); attributeValue = (attributeValue || '').replace(reUnescape, ''); var test, regexp; switch (attributeOperator){ case '^=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) ); break; case '$=' : regexp = new RegExp( escapeRegExp(attributeValue) +'$' ); break; case '~=' : regexp = new RegExp( '(^|\\s)'+ escapeRegExp(attributeValue) +'(\\s|$)' ); break; case '|=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) +'(-|$)' ); break; case '=' : test = function(value){ return attributeValue == value; }; break; case '*=' : test = function(value){ return value && value.indexOf(attributeValue) > -1; }; break; case '!=' : test = function(value){ return attributeValue != value; }; break; default : test = function(value){ return !!value; }; } if (attributeValue == '' && (/^[*$^]=$/).test(attributeOperator)) test = function(){ return false; }; if (!test) test = function(value){ return value && regexp.test(value); }; if (!currentParsed.attributes) currentParsed.attributes = []; currentParsed.attributes.push({ key: attributeKey, operator: attributeOperator, value: attributeValue, test: test }); } return ''; }; // Slick NS var Slick = (this.Slick || {}); Slick.parse = function(expression){ return parse(expression); }; Slick.escapeRegExp = escapeRegExp; if (!this.Slick) this.Slick = Slick; }).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this); /* --- name: Slick.Finder description: The new, superfast css selector engine. provides: Slick.Finder requires: Slick.Parser ... */ ;(function(){ var local = {}, featuresCache = {}, toString = Object.prototype.toString; // Feature / Bug detection local.isNativeCode = function(fn){ return (/\{\s*\[native code\]\s*\}/).test('' + fn); }; local.isXML = function(document){ return (!!document.xmlVersion) || (!!document.xml) || (toString.call(document) == '[object XMLDocument]') || (document.nodeType == 9 && document.documentElement.nodeName != 'HTML'); }; local.setDocument = function(document){ // convert elements / window arguments to document. if document cannot be extrapolated, the function returns. var nodeType = document.nodeType; if (nodeType == 9); // document else if (nodeType) document = document.ownerDocument; // node else if (document.navigator) document = document.document; // window else return; // check if it's the old document if (this.document === document) return; this.document = document; // check if we have done feature detection on this document before var root = document.documentElement, rootUid = this.getUIDXML(root), features = featuresCache[rootUid], feature; if (features){ for (feature in features){ this[feature] = features[feature]; } return; } features = featuresCache[rootUid] = {}; features.root = root; features.isXMLDocument = this.isXML(document); features.brokenStarGEBTN = features.starSelectsClosedQSA = features.idGetsName = features.brokenMixedCaseQSA = features.brokenGEBCN = features.brokenCheckedQSA = features.brokenEmptyAttributeQSA = features.isHTMLDocument = features.nativeMatchesSelector = false; var starSelectsClosed, starSelectsComments, brokenSecondClassNameGEBCN, cachedGetElementsByClassName, brokenFormAttributeGetter; var selected, id = 'slick_uniqueid'; var testNode = document.createElement('div'); var testRoot = document.body || document.getElementsByTagName('body')[0] || root; testRoot.appendChild(testNode); // on non-HTML documents innerHTML and getElementsById doesnt work properly try { testNode.innerHTML = '<a id="'+id+'"></a>'; features.isHTMLDocument = !!document.getElementById(id); } catch(e){}; if (features.isHTMLDocument){ testNode.style.display = 'none'; // IE returns comment nodes for getElementsByTagName('*') for some documents testNode.appendChild(document.createComment('')); starSelectsComments = (testNode.getElementsByTagName('*').length > 1); // IE returns closed nodes (EG:"</foo>") for getElementsByTagName('*') for some documents try { testNode.innerHTML = 'foo</foo>'; selected = testNode.getElementsByTagName('*'); starSelectsClosed = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/'); } catch(e){}; features.brokenStarGEBTN = starSelectsComments || starSelectsClosed; // IE returns elements with the name instead of just id for getElementsById for some documents try { testNode.innerHTML = '<a name="'+ id +'"></a><b id="'+ id +'"></b>'; features.idGetsName = document.getElementById(id) === testNode.firstChild; } catch(e){}; if (testNode.getElementsByClassName){ // Safari 3.2 getElementsByClassName caches results try { testNode.innerHTML = '<a class="f"></a><a class="b"></a>'; testNode.getElementsByClassName('b').length; testNode.firstChild.className = 'b'; cachedGetElementsByClassName = (testNode.getElementsByClassName('b').length != 2); } catch(e){}; // Opera 9.6 getElementsByClassName doesnt detects the class if its not the first one try { testNode.innerHTML = '<a class="a"></a><a class="f b a"></a>'; brokenSecondClassNameGEBCN = (testNode.getElementsByClassName('a').length != 2); } catch(e){}; features.brokenGEBCN = cachedGetElementsByClassName || brokenSecondClassNameGEBCN; } if (testNode.querySelectorAll){ // IE 8 returns closed nodes (EG:"</foo>") for querySelectorAll('*') for some documents try { testNode.innerHTML = 'foo</foo>'; selected = testNode.querySelectorAll('*'); features.starSelectsClosedQSA = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/'); } catch(e){}; // Safari 3.2 querySelectorAll doesnt work with mixedcase on quirksmode try { testNode.innerHTML = '<a class="MiX"></a>'; features.brokenMixedCaseQSA = !testNode.querySelectorAll('.MiX').length; } catch(e){}; // Webkit and Opera dont return selected options on querySelectorAll try { testNode.innerHTML = '<select><option selected="selected">a</option></select>'; features.brokenCheckedQSA = (testNode.querySelectorAll(':checked').length == 0); } catch(e){}; // IE returns incorrect results for attr[*^$]="" selectors on querySelectorAll try { testNode.innerHTML = '<a class=""></a>'; features.brokenEmptyAttributeQSA = (testNode.querySelectorAll('[class*=""]').length != 0); } catch(e){}; } // IE6-7, if a form has an input of id x, form.getAttribute(x) returns a reference to the input try { testNode.innerHTML = '<form action="s"><input id="action"/></form>'; brokenFormAttributeGetter = (testNode.firstChild.getAttribute('action') != 's'); } catch(e){}; // native matchesSelector function features.nativeMatchesSelector = root.matchesSelector || /*root.msMatchesSelector ||*/ root.mozMatchesSelector || root.webkitMatchesSelector; if (features.nativeMatchesSelector) try { // if matchesSelector trows errors on incorrect sintaxes we can use it features.nativeMatchesSelector.call(root, ':slick'); features.nativeMatchesSelector = null; } catch(e){}; } try { root.slick_expando = 1; delete root.slick_expando; features.getUID = this.getUIDHTML; } catch(e) { features.getUID = this.getUIDXML; } testRoot.removeChild(testNode); testNode = selected = testRoot = null; // getAttribute features.getAttribute = (features.isHTMLDocument && brokenFormAttributeGetter) ? function(node, name){ var method = this.attributeGetters[name]; if (method) return method.call(node); var attributeNode = node.getAttributeNode(name); return (attributeNode) ? attributeNode.nodeValue : null; } : function(node, name){ var method = this.attributeGetters[name]; return (method) ? method.call(node) : node.getAttribute(name); }; // hasAttribute features.hasAttribute = (root && this.isNativeCode(root.hasAttribute)) ? function(node, attribute) { return node.hasAttribute(attribute); } : function(node, attribute) { node = node.getAttributeNode(attribute); return !!(node && (node.specified || node.nodeValue)); }; // contains // FIXME: Add specs: local.contains should be different for xml and html documents? var nativeRootContains = root && this.isNativeCode(root.contains), nativeDocumentContains = document && this.isNativeCode(document.contains); features.contains = (nativeRootContains && nativeDocumentContains) ? function(context, node){ return context.contains(node); } : (nativeRootContains && !nativeDocumentContains) ? function(context, node){ // IE8 does not have .contains on document. return context === node || ((context === document) ? document.documentElement : context).contains(node); } : (root && root.compareDocumentPosition) ? function(context, node){ return context === node || !!(context.compareDocumentPosition(node) & 16); } : function(context, node){ if (node) do { if (node === context) return true; } while ((node = node.parentNode)); return false; }; // document order sorting // credits to Sizzle (http://sizzlejs.com/) features.documentSorter = (root.compareDocumentPosition) ? function(a, b){ if (!a.compareDocumentPosition || !b.compareDocumentPosition) return 0; return a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; } : ('sourceIndex' in root) ? function(a, b){ if (!a.sourceIndex || !b.sourceIndex) return 0; return a.sourceIndex - b.sourceIndex; } : (document.createRange) ? function(a, b){ if (!a.ownerDocument || !b.ownerDocument) return 0; var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.setStart(a, 0); aRange.setEnd(a, 0); bRange.setStart(b, 0); bRange.setEnd(b, 0); return aRange.compareBoundaryPoints(Range.START_TO_END, bRange); } : null ; root = null; for (feature in features){ this[feature] = features[feature]; } }; // Main Method var reSimpleSelector = /^([#.]?)((?:[\w-]+|\*))$/, reEmptyAttribute = /\[.+[*$^]=(?:""|'')?\]/, qsaFailExpCache = {}; local.search = function(context, expression, append, first){ var found = this.found = (first) ? null : (append || []); if (!context) return found; else if (context.navigator) context = context.document; // Convert the node from a window to a document else if (!context.nodeType) return found; // setup var parsed, i, uniques = this.uniques = {}, hasOthers = !!(append && append.length), contextIsDocument = (context.nodeType == 9); if (this.document !== (contextIsDocument ? context : context.ownerDocument)) this.setDocument(context); // avoid duplicating items already in the append array if (hasOthers) for (i = found.length; i--;) uniques[this.getUID(found[i])] = true; // expression checks if (typeof expression == 'string'){ // expression is a string /*<simple-selectors-override>*/ var simpleSelector = expression.match(reSimpleSelector); simpleSelectors: if (simpleSelector) { var symbol = simpleSelector[1], name = simpleSelector[2], node, nodes; if (!symbol){ if (name == '*' && this.brokenStarGEBTN) break simpleSelectors; nodes = context.getElementsByTagName(name); if (first) return nodes[0] || null; for (i = 0; node = nodes[i++];){ if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } } else if (symbol == '#'){ if (!this.isHTMLDocument || !contextIsDocument) break simpleSelectors; node = context.getElementById(name); if (!node) return found; if (this.idGetsName && node.getAttributeNode('id').nodeValue != name) break simpleSelectors; if (first) return node || null; if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } else if (symbol == '.'){ if (!this.isHTMLDocument || ((!context.getElementsByClassName || this.brokenGEBCN) && context.querySelectorAll)) break simpleSelectors; if (context.getElementsByClassName && !this.brokenGEBCN){ nodes = context.getElementsByClassName(name); if (first) return nodes[0] || null; for (i = 0; node = nodes[i++];){ if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } } else { var matchClass = new RegExp('(^|\\s)'+ Slick.escapeRegExp(name) +'(\\s|$)'); nodes = context.getElementsByTagName('*'); for (i = 0; node = nodes[i++];){ className = node.className; if (!(className && matchClass.test(className))) continue; if (first) return node; if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } } } if (hasOthers) this.sort(found); return (first) ? null : found; } /*</simple-selectors-override>*/ /*<query-selector-override>*/ querySelector: if (context.querySelectorAll) { if (!this.isHTMLDocument || qsaFailExpCache[expression] //TODO: only skip when expression is actually mixed case || this.brokenMixedCaseQSA || (this.brokenCheckedQSA && expression.indexOf(':checked') > -1) || (this.brokenEmptyAttributeQSA && reEmptyAttribute.test(expression)) || (!contextIsDocument //Abort when !contextIsDocument and... // there are multiple expressions in the selector // since we currently only fix non-document rooted QSA for single expression selectors && expression.indexOf(',') > -1 ) || Slick.disableQSA ) break querySelector; var _expression = expression, _context = context; if (!contextIsDocument){ // non-document rooted QSA // credits to Andrew Dupont var currentId = _context.getAttribute('id'), slickid = 'slickid__'; _context.setAttribute('id', slickid); _expression = '#' + slickid + ' ' + _expression; context = _context.parentNode; } try { if (first) return context.querySelector(_expression) || null; else nodes = context.querySelectorAll(_expression); } catch(e) { qsaFailExpCache[expression] = 1; break querySelector; } finally { if (!contextIsDocument){ if (currentId) _context.setAttribute('id', currentId); else _context.removeAttribute('id'); context = _context; } } if (this.starSelectsClosedQSA) for (i = 0; node = nodes[i++];){ if (node.nodeName > '@' && !(hasOthers && uniques[this.getUID(node)])) found.push(node); } else for (i = 0; node = nodes[i++];){ if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } if (hasOthers) this.sort(found); return found; } /*</query-selector-override>*/ parsed = this.Slick.parse(expression); if (!parsed.length) return found; } else if (expression == null){ // there is no expression return found; } else if (expression.Slick){ // expression is a parsed Slick object parsed = expression; } else if (this.contains(context.documentElement || context, expression)){ // expression is a node (found) ? found.push(expression) : found = expression; return found; } else { // other junk return found; } /*<pseudo-selectors>*//*<nth-pseudo-selectors>*/ // cache elements for the nth selectors this.posNTH = {}; this.posNTHLast = {}; this.posNTHType = {}; this.posNTHTypeLast = {}; /*</nth-pseudo-selectors>*//*</pseudo-selectors>*/ // if append is null and there is only a single selector with one expression use pushArray, else use pushUID this.push = (!hasOthers && (first || (parsed.length == 1 && parsed.expressions[0].length == 1))) ? this.pushArray : this.pushUID; if (found == null) found = []; // default engine var j, m, n; var combinator, tag, id, classList, classes, attributes, pseudos; var currentItems, currentExpression, currentBit, lastBit, expressions = parsed.expressions; search: for (i = 0; (currentExpression = expressions[i]); i++) for (j = 0; (currentBit = currentExpression[j]); j++){ combinator = 'combinator:' + currentBit.combinator; if (!this[combinator]) continue search; tag = (this.isXMLDocument) ? currentBit.tag : currentBit.tag.toUpperCase(); id = currentBit.id; classList = currentBit.classList; classes = currentBit.classes; attributes = currentBit.attributes; pseudos = currentBit.pseudos; lastBit = (j === (currentExpression.length - 1)); this.bitUniques = {}; if (lastBit){ this.uniques = uniques; this.found = found; } else { this.uniques = {}; this.found = []; } if (j === 0){ this[combinator](context, tag, id, classes, attributes, pseudos, classList); if (first && lastBit && found.length) break search; } else { if (first && lastBit) for (m = 0, n = currentItems.length; m < n; m++){ this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList); if (found.length) break search; } else for (m = 0, n = currentItems.length; m < n; m++) this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList); } currentItems = this.found; } // should sort if there are nodes in append and if you pass multiple expressions. if (hasOthers || (parsed.expressions.length > 1)) this.sort(found); return (first) ? (found[0] || null) : found; }; // Utils local.uidx = 1; local.uidk = 'slick-uniqueid'; local.getUIDXML = function(node){ var uid = node.getAttribute(this.uidk); if (!uid){ uid = this.uidx++; node.setAttribute(this.uidk, uid); } return uid; }; local.getUIDHTML = function(node){ return node.uniqueNumber || (node.uniqueNumber = this.uidx++); }; // sort based on the setDocument documentSorter method. local.sort = function(results){ if (!this.documentSorter) return results; results.sort(this.documentSorter); return results; }; /*<pseudo-selectors>*//*<nth-pseudo-selectors>*/ local.cacheNTH = {}; local.matchNTH = /^([+-]?\d*)?([a-z]+)?([+-]\d+)?$/; local.parseNTHArgument = function(argument){ var parsed = argument.match(this.matchNTH); if (!parsed) return false; var special = parsed[2] || false; var a = parsed[1] || 1; if (a == '-') a = -1; var b = +parsed[3] || 0; parsed = (special == 'n') ? {a: a, b: b} : (special == 'odd') ? {a: 2, b: 1} : (special == 'even') ? {a: 2, b: 0} : {a: 0, b: a}; return (this.cacheNTH[argument] = parsed); }; local.createNTHPseudo = function(child, sibling, positions, ofType){ return function(node, argument){ var uid = this.getUID(node); if (!this[positions][uid]){ var parent = node.parentNode; if (!parent) return false; var el = parent[child], count = 1; if (ofType){ var nodeName = node.nodeName; do { if (el.nodeName != nodeName) continue; this[positions][this.getUID(el)] = count++; } while ((el = el[sibling])); } else { do { if (el.nodeType != 1) continue; this[positions][this.getUID(el)] = count++; } while ((el = el[sibling])); } } argument = argument || 'n'; var parsed = this.cacheNTH[argument] || this.parseNTHArgument(argument); if (!parsed) return false; var a = parsed.a, b = parsed.b, pos = this[positions][uid]; if (a == 0) return b == pos; if (a > 0){ if (pos < b) return false; } else { if (b < pos) return false; } return ((pos - b) % a) == 0; }; }; /*</nth-pseudo-selectors>*//*</pseudo-selectors>*/ local.pushArray = function(node, tag, id, classes, attributes, pseudos){ if (this.matchSelector(node, tag, id, classes, attributes, pseudos)) this.found.push(node); }; local.pushUID = function(node, tag, id, classes, attributes, pseudos){ var uid = this.getUID(node); if (!this.uniques[uid] && this.matchSelector(node, tag, id, classes, attributes, pseudos)){ this.uniques[uid] = true; this.found.push(node); } }; local.matchNode = function(node, selector){ if (this.isHTMLDocument && this.nativeMatchesSelector){ try { return this.nativeMatchesSelector.call(node, selector.replace(/\[([^=]+)=\s*([^'"\]]+?)\s*\]/g, '[$1="$2"]')); } catch(matchError) {} } var parsed = this.Slick.parse(selector); if (!parsed) return true; // simple (single) selectors var expressions = parsed.expressions, simpleExpCounter = 0, i; for (i = 0; (currentExpression = expressions[i]); i++){ if (currentExpression.length == 1){ var exp = currentExpression[0]; if (this.matchSelector(node, (this.isXMLDocument) ? exp.tag : exp.tag.toUpperCase(), exp.id, exp.classes, exp.attributes, exp.pseudos)) return true; simpleExpCounter++; } } if (simpleExpCounter == parsed.length) return false; var nodes = this.search(this.document, parsed), item; for (i = 0; item = nodes[i++];){ if (item === node) return true; } return false; }; local.matchPseudo = function(node, name, argument){ var pseudoName = 'pseudo:' + name; if (this[pseudoName]) return this[pseudoName](node, argument); var attribute = this.getAttribute(node, name); return (argument) ? argument == attribute : !!attribute; }; local.matchSelector = function(node, tag, id, classes, attributes, pseudos){ if (tag){ var nodeName = (this.isXMLDocument) ? node.nodeName : node.nodeName.toUpperCase(); if (tag == '*'){ if (nodeName < '@') return false; // Fix for comment nodes and closed nodes } else { if (nodeName != tag) return false; } } if (id && node.getAttribute('id') != id) return false; var i, part, cls; if (classes) for (i = classes.length; i--;){ cls = this.getAttribute(node, 'class'); if (!(cls && classes[i].regexp.test(cls))) return false; } if (attributes) for (i = attributes.length; i--;){ part = attributes[i]; if (part.operator ? !part.test(this.getAttribute(node, part.key)) : !this.hasAttribute(node, part.key)) return false; } if (pseudos) for (i = pseudos.length; i--;){ part = pseudos[i]; if (!this.matchPseudo(node, part.key, part.value)) return false; } return true; }; var combinators = { ' ': function(node, tag, id, classes, attributes, pseudos, classList){ // all child nodes, any level var i, item, children; if (this.isHTMLDocument){ getById: if (id){ item = this.document.getElementById(id); if ((!item && node.all) || (this.idGetsName && item && item.getAttributeNode('id').nodeValue != id)){ // all[id] returns all the elements with that name or id inside node // if theres just one it will return the element, else it will be a collection children = node.all[id]; if (!children) return; if (!children[0]) children = [children]; for (i = 0; item = children[i++];){ var idNode = item.getAttributeNode('id'); if (idNode && idNode.nodeValue == id){ this.push(item, tag, null, classes, attributes, pseudos); break; } } return; } if (!item){ // if the context is in the dom we return, else we will try GEBTN, breaking the getById label if (this.contains(this.root, node)) return; else break getById; } else if (this.document !== node && !this.contains(node, item)) return; this.push(item, tag, null, classes, attributes, pseudos); return; } getByClass: if (classes && node.getElementsByClassName && !this.brokenGEBCN){ children = node.getElementsByClassName(classList.join(' ')); if (!(children && children.length)) break getByClass; for (i = 0; item = children[i++];) this.push(item, tag, id, null, attributes, pseudos); return; } } getByTag: { children = node.getElementsByTagName(tag); if (!(children && children.length)) break getByTag; if (!this.brokenStarGEBTN) tag = null; for (i = 0; item = children[i++];) this.push(item, tag, id, classes, attributes, pseudos); } }, '>': function(node, tag, id, classes, attributes, pseudos){ // direct children if ((node = node.firstChild)) do { if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos); } while ((node = node.nextSibling)); }, '+': function(node, tag, id, classes, attributes, pseudos){ // next sibling while ((node = node.nextSibling)) if (node.nodeType == 1){ this.push(node, tag, id, classes, attributes, pseudos); break; } }, '^': function(node, tag, id, classes, attributes, pseudos){ // first child node = node.firstChild; if (node){ if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos); else this['combinator:+'](node, tag, id, classes, attributes, pseudos); } }, '~': function(node, tag, id, classes, attributes, pseudos){ // next siblings while ((node = node.nextSibling)){ if (node.nodeType != 1) continue; var uid = this.getUID(node); if (this.bitUniques[uid]) break; this.bitUniques[uid] = true; this.push(node, tag, id, classes, attributes, pseudos); } }, '++': function(node, tag, id, classes, attributes, pseudos){ // next sibling and previous sibling this['combinator:+'](node, tag, id, classes, attributes, pseudos); this['combinator:!+'](node, tag, id, classes, attributes, pseudos); }, '~~': function(node, tag, id, classes, attributes, pseudos){ // next siblings and previous siblings this['combinator:~'](node, tag, id, classes, attributes, pseudos); this['combinator:!~'](node, tag, id, classes, attributes, pseudos); }, '!': function(node, tag, id, classes, attributes, pseudos){ // all parent nodes up to document while ((node = node.parentNode)) if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos); }, '!>': function(node, tag, id, classes, attributes, pseudos){ // direct parent (one level) node = node.parentNode; if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos); }, '!+': function(node, tag, id, classes, attributes, pseudos){ // previous sibling while ((node = node.previousSibling)) if (node.nodeType == 1){ this.push(node, tag, id, classes, attributes, pseudos); break; } }, '!^': function(node, tag, id, classes, attributes, pseudos){ // last child node = node.lastChild; if (node){ if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos); else this['combinator:!+'](node, tag, id, classes, attributes, pseudos); } }, '!~': function(node, tag, id, classes, attributes, pseudos){ // previous siblings while ((node = node.previousSibling)){ if (node.nodeType != 1) continue; var uid = this.getUID(node); if (this.bitUniques[uid]) break; this.bitUniques[uid] = true; this.push(node, tag, id, classes, attributes, pseudos); } } }; for (var c in combinators) local['combinator:' + c] = combinators[c]; var pseudos = { /*<pseudo-selectors>*/ 'empty': function(node){ var child = node.firstChild; return !(child && child.nodeType == 1) && !(node.innerText || node.textContent || '').length; }, 'not': function(node, expression){ return !this.matchNode(node, expression); }, 'contains': function(node, text){ return (node.innerText || node.textContent || '').indexOf(text) > -1; }, 'first-child': function(node){ while ((node = node.previousSibling)) if (node.nodeType == 1) return false; return true; }, 'last-child': function(node){ while ((node = node.nextSibling)) if (node.nodeType == 1) return false; return true; }, 'only-child': function(node){ var prev = node; while ((prev = prev.previousSibling)) if (prev.nodeType == 1) return false; var next = node; while ((next = next.nextSibling)) if (next.nodeType == 1) return false; return true; }, /*<nth-pseudo-selectors>*/ 'nth-child': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTH'), 'nth-last-child': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHLast'), 'nth-of-type': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTHType', true), 'nth-last-of-type': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHTypeLast', true), 'index': function(node, index){ return this['pseudo:nth-child'](node, '' + (index + 1)); }, 'even': function(node){ return this['pseudo:nth-child'](node, '2n'); }, 'odd': function(node){ return this['pseudo:nth-child'](node, '2n+1'); }, /*</nth-pseudo-selectors>*/ /*<of-type-pseudo-selectors>*/ 'first-of-type': function(node){ var nodeName = node.nodeName; while ((node = node.previousSibling)) if (node.nodeName == nodeName) return false; return true; }, 'last-of-type': function(node){ var nodeName = node.nodeName; while ((node = node.nextSibling)) if (node.nodeName == nodeName) return false; return true; }, 'only-of-type': function(node){ var prev = node, nodeName = node.nodeName; while ((prev = prev.previousSibling)) if (prev.nodeName == nodeName) return false; var next = node; while ((next = next.nextSibling)) if (next.nodeName == nodeName) return false; return true; }, /*</of-type-pseudo-selectors>*/ // custom pseudos 'enabled': function(node){ return !node.disabled; }, 'disabled': function(node){ return node.disabled; }, 'checked': function(node){ return node.checked || node.selected; }, 'focus': function(node){ return this.isHTMLDocument && this.document.activeElement === node && (node.href || node.type || this.hasAttribute(node, 'tabindex')); }, 'root': function(node){ return (node === this.root); }, 'selected': function(node){ return node.selected; } /*</pseudo-selectors>*/ }; for (var p in pseudos) local['pseudo:' + p] = pseudos[p]; // attributes methods var attributeGetters = local.attributeGetters = { 'for': function(){ return ('htmlFor' in this) ? this.htmlFor : this.getAttribute('for'); }, 'href': function(){ return ('href' in this) ? this.getAttribute('href', 2) : this.getAttribute('href'); }, 'style': function(){ return (this.style) ? this.style.cssText : this.getAttribute('style'); }, 'tabindex': function(){ var attributeNode = this.getAttributeNode('tabindex'); return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null; }, 'type': function(){ return this.getAttribute('type'); }, 'maxlength': function(){ var attributeNode = this.getAttributeNode('maxLength'); return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null; } }; attributeGetters.MAXLENGTH = attributeGetters.maxLength = attributeGetters.maxlength; // Slick var Slick = local.Slick = (this.Slick || {}); Slick.version = '1.1.7'; // Slick finder Slick.search = function(context, expression, append){ return local.search(context, expression, append); }; Slick.find = function(context, expression){ return local.search(context, expression, null, true); }; // Slick containment checker Slick.contains = function(container, node){ local.setDocument(container); return local.contains(container, node); }; // Slick attribute getter Slick.getAttribute = function(node, name){ local.setDocument(node); return local.getAttribute(node, name); }; Slick.hasAttribute = function(node, name){ local.setDocument(node); return local.hasAttribute(node, name); }; // Slick matcher Slick.match = function(node, selector){ if (!(node && selector)) return false; if (!selector || selector === node) return true; local.setDocument(node); return local.matchNode(node, selector); }; // Slick attribute accessor Slick.defineAttributeGetter = function(name, fn){ local.attributeGetters[name] = fn; return this; }; Slick.lookupAttributeGetter = function(name){ return local.attributeGetters[name]; }; // Slick pseudo accessor Slick.definePseudo = function(name, fn){ local['pseudo:' + name] = function(node, argument){ return fn.call(node, argument); }; return this; }; Slick.lookupPseudo = function(name){ var pseudo = local['pseudo:' + name]; if (pseudo) return function(argument){ return pseudo.call(this, argument); }; return null; }; // Slick overrides accessor Slick.override = function(regexp, fn){ local.override(regexp, fn); return this; }; Slick.isXML = local.isXML; Slick.uidOf = function(node){ return local.getUIDHTML(node); }; if (!this.Slick) this.Slick = Slick; }).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this); /* --- name: Element description: One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, time-saver methods to let you easily work with HTML Elements. license: MIT-style license. requires: [Window, Document, Array, String, Function, Object, Number, Slick.Parser, Slick.Finder] provides: [Element, Elements, $, $$, Iframe, Selectors] ... */ var Element = function(tag, props){ var konstructor = Element.Constructors[tag]; if (konstructor) return konstructor(props); if (typeof tag != 'string') return document.id(tag).set(props); if (!props) props = {}; if (!(/^[\w-]+$/).test(tag)){ var parsed = Slick.parse(tag).expressions[0][0]; tag = (parsed.tag == '*') ? 'div' : parsed.tag; if (parsed.id && props.id == null) props.id = parsed.id; var attributes = parsed.attributes; if (attributes) for (var attr, i = 0, l = attributes.length; i < l; i++){ attr = attributes[i]; if (props[attr.key] != null) continue; if (attr.value != null && attr.operator == '=') props[attr.key] = attr.value; else if (!attr.value && !attr.operator) props[attr.key] = true; } if (parsed.classList && props['class'] == null) props['class'] = parsed.classList.join(' '); } return document.newElement(tag, props); }; if (Browser.Element){ Element.prototype = Browser.Element.prototype; // IE8 and IE9 require the wrapping. Element.prototype._fireEvent = (function(fireEvent){ return function(type, event){ return fireEvent.call(this, type, event); }; })(Element.prototype.fireEvent); } new Type('Element', Element).mirror(function(name){ if (Array.prototype[name]) return; var obj = {}; obj[name] = function(){ var results = [], args = arguments, elements = true; for (var i = 0, l = this.length; i < l; i++){ var element = this[i], result = results[i] = element[name].apply(element, args); elements = (elements && typeOf(result) == 'element'); } return (elements) ? new Elements(results) : results; }; Elements.implement(obj); }); if (!Browser.Element){ Element.parent = Object; Element.Prototype = { '$constructor': Element, '$family': Function.from('element').hide() }; Element.mirror(function(name, method){ Element.Prototype[name] = method; }); } Element.Constructors = {}; //<1.2compat> Element.Constructors = new Hash; //</1.2compat> var IFrame = new Type('IFrame', function(){ var params = Array.link(arguments, { properties: Type.isObject, iframe: function(obj){ return (obj != null); } }); var props = params.properties || {}, iframe; if (params.iframe) iframe = document.id(params.iframe); var onload = props.onload || function(){}; delete props.onload; props.id = props.name = [props.id, props.name, iframe ? (iframe.id || iframe.name) : 'IFrame_' + String.uniqueID()].pick(); iframe = new Element(iframe || 'iframe', props); var onLoad = function(){ onload.call(iframe.contentWindow); }; if (window.frames[props.id]) onLoad(); else iframe.addListener('load', onLoad); return iframe; }); var Elements = this.Elements = function(nodes){ if (nodes && nodes.length){ var uniques = {}, node; for (var i = 0; node = nodes[i++];){ var uid = Slick.uidOf(node); if (!uniques[uid]){ uniques[uid] = true; this.push(node); } } } }; Elements.prototype = {length: 0}; Elements.parent = Array; new Type('Elements', Elements).implement({ filter: function(filter, bind){ if (!filter) return this; return new Elements(Array.filter(this, (typeOf(filter) == 'string') ? function(item){ return item.match(filter); } : filter, bind)); }.protect(), push: function(){ var length = this.length; for (var i = 0, l = arguments.length; i < l; i++){ var item = document.id(arguments[i]); if (item) this[length++] = item; } return (this.length = length); }.protect(), unshift: function(){ var items = []; for (var i = 0, l = arguments.length; i < l; i++){ var item = document.id(arguments[i]); if (item) items.push(item); } return Array.prototype.unshift.apply(this, items); }.protect(), concat: function(){ var newElements = new Elements(this); for (var i = 0, l = arguments.length; i < l; i++){ var item = arguments[i]; if (Type.isEnumerable(item)) newElements.append(item); else newElements.push(item); } return newElements; }.protect(), append: function(collection){ for (var i = 0, l = collection.length; i < l; i++) this.push(collection[i]); return this; }.protect(), empty: function(){ while (this.length) delete this[--this.length]; return this; }.protect() }); //<1.2compat> Elements.alias('extend', 'append'); //</1.2compat> (function(){ // FF, IE var splice = Array.prototype.splice, object = {'0': 0, '1': 1, length: 2}; splice.call(object, 1, 1); if (object[1] == 1) Elements.implement('splice', function(){ var length = this.length; var result = splice.apply(this, arguments); while (length >= this.length) delete this[length--]; return result; }.protect()); Array.forEachMethod(function(method, name){ Elements.implement(name, method); }); Array.mirror(Elements); /*<ltIE8>*/ var createElementAcceptsHTML; try { createElementAcceptsHTML = (document.createElement('<input name=x>').name == 'x'); } catch (e){} var escapeQuotes = function(html){ return ('' + html).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); }; /*</ltIE8>*/ Document.implement({ newElement: function(tag, props){ if (props && props.checked != null) props.defaultChecked = props.checked; /*<ltIE8>*/// Fix for readonly name and type properties in IE < 8 if (createElementAcceptsHTML && props){ tag = '<' + tag; if (props.name) tag += ' name="' + escapeQuotes(props.name) + '"'; if (props.type) tag += ' type="' + escapeQuotes(props.type) + '"'; tag += '>'; delete props.name; delete props.type; } /*</ltIE8>*/ return this.id(this.createElement(tag)).set(props); } }); })(); (function(){ Slick.uidOf(window); Slick.uidOf(document); Document.implement({ newTextNode: function(text){ return this.createTextNode(text); }, getDocument: function(){ return this; }, getWindow: function(){ return this.window; }, id: (function(){ var types = { string: function(id, nocash, doc){ id = Slick.find(doc, '#' + id.replace(/(\W)/g, '\\$1')); return (id) ? types.element(id, nocash) : null; }, element: function(el, nocash){ Slick.uidOf(el); if (!nocash && !el.$family && !(/^(?:object|embed)$/i).test(el.tagName)){ var fireEvent = el.fireEvent; // wrapping needed in IE7, or else crash el._fireEvent = function(type, event){ return fireEvent(type, event); }; Object.append(el, Element.Prototype); } return el; }, object: function(obj, nocash, doc){ if (obj.toElement) return types.element(obj.toElement(doc), nocash); return null; } }; types.textnode = types.whitespace = types.window = types.document = function(zero){ return zero; }; return function(el, nocash, doc){ if (el && el.$family && el.uniqueNumber) return el; var type = typeOf(el); return (types[type]) ? types[type](el, nocash, doc || document) : null; }; })() }); if (window.$ == null) Window.implement('$', function(el, nc){ return document.id(el, nc, this.document); }); Window.implement({ getDocument: function(){ return this.document; }, getWindow: function(){ return this; } }); [Document, Element].invoke('implement', { getElements: function(expression){ return Slick.search(this, expression, new Elements); }, getElement: function(expression){ return document.id(Slick.find(this, expression)); } }); var contains = {contains: function(element){ return Slick.contains(this, element); }}; if (!document.contains) Document.implement(contains); if (!document.createElement('div').contains) Element.implement(contains); //<1.2compat> Element.implement('hasChild', function(element){ return this !== element && this.contains(element); }); (function(search, find, match){ this.Selectors = {}; var pseudos = this.Selectors.Pseudo = new Hash(); var addSlickPseudos = function(){ for (var name in pseudos) if (pseudos.hasOwnProperty(name)){ Slick.definePseudo(name, pseudos[name]); delete pseudos[name]; } }; Slick.search = function(context, expression, append){ addSlickPseudos(); return search.call(this, context, expression, append); }; Slick.find = function(context, expression){ addSlickPseudos(); return find.call(this, context, expression); }; Slick.match = function(node, selector){ addSlickPseudos(); return match.call(this, node, selector); }; })(Slick.search, Slick.find, Slick.match); //</1.2compat> // tree walking var injectCombinator = function(expression, combinator){ if (!expression) return combinator; expression = Object.clone(Slick.parse(expression)); var expressions = expression.expressions; for (var i = expressions.length; i--;) expressions[i][0].combinator = combinator; return expression; }; Object.forEach({ getNext: '~', getPrevious: '!~', getParent: '!' }, function(combinator, method){ Element.implement(method, function(expression){ return this.getElement(injectCombinator(expression, combinator)); }); }); Object.forEach({ getAllNext: '~', getAllPrevious: '!~', getSiblings: '~~', getChildren: '>', getParents: '!' }, function(combinator, method){ Element.implement(method, function(expression){ return this.getElements(injectCombinator(expression, combinator)); }); }); Element.implement({ getFirst: function(expression){ return document.id(Slick.search(this, injectCombinator(expression, '>'))[0]); }, getLast: function(expression){ return document.id(Slick.search(this, injectCombinator(expression, '>')).getLast()); }, getWindow: function(){ return this.ownerDocument.window; }, getDocument: function(){ return this.ownerDocument; }, getElementById: function(id){ return document.id(Slick.find(this, '#' + ('' + id).replace(/(\W)/g, '\\$1'))); }, match: function(expression){ return !expression || Slick.match(this, expression); } }); //<1.2compat> if (window.$$ == null) Window.implement('$$', function(selector){ var elements = new Elements; if (arguments.length == 1 && typeof selector == 'string') return Slick.search(this.document, selector, elements); var args = Array.flatten(arguments); for (var i = 0, l = args.length; i < l; i++){ var item = args[i]; switch (typeOf(item)){ case 'element': elements.push(item); break; case 'string': Slick.search(this.document, item, elements); } } return elements; }); //</1.2compat> if (window.$$ == null) Window.implement('$$', function(selector){ if (arguments.length == 1){ if (typeof selector == 'string') return Slick.search(this.document, selector, new Elements); else if (Type.isEnumerable(selector)) return new Elements(selector); } return new Elements(arguments); }); // Inserters var inserters = { before: function(context, element){ var parent = element.parentNode; if (parent) parent.insertBefore(context, element); }, after: function(context, element){ var parent = element.parentNode; if (parent) parent.insertBefore(context, element.nextSibling); }, bottom: function(context, element){ element.appendChild(context); }, top: function(context, element){ element.insertBefore(context, element.firstChild); } }; inserters.inside = inserters.bottom; //<1.2compat> Object.each(inserters, function(inserter, where){ where = where.capitalize(); var methods = {}; methods['inject' + where] = function(el){ inserter(this, document.id(el, true)); return this; }; methods['grab' + where] = function(el){ inserter(document.id(el, true), this); return this; }; Element.implement(methods); }); //</1.2compat> // getProperty / setProperty var propertyGetters = {}, propertySetters = {}; // properties var properties = {}; Array.forEach([ 'type', 'value', 'defaultValue', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan', 'frameBorder', 'rowSpan', 'tabIndex', 'useMap' ], function(property){ properties[property.toLowerCase()] = property; }); properties.html = 'innerHTML'; properties.text = (document.createElement('div').textContent == null) ? 'innerText': 'textContent'; Object.forEach(properties, function(real, key){ propertySetters[key] = function(node, value){ node[real] = value; }; propertyGetters[key] = function(node){ return node[real]; }; }); // Booleans var bools = [ 'compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked', 'disabled', 'readOnly', 'multiple', 'selected', 'noresize', 'defer', 'defaultChecked', 'autofocus', 'controls', 'autoplay', 'loop' ]; var booleans = {}; Array.forEach(bools, function(bool){ var lower = bool.toLowerCase(); booleans[lower] = bool; propertySetters[lower] = function(node, value){ node[bool] = !!value; }; propertyGetters[lower] = function(node){ return !!node[bool]; }; }); // Special cases Object.append(propertySetters, { 'class': function(node, value){ ('className' in node) ? node.className = (value || '') : node.setAttribute('class', value); }, 'for': function(node, value){ ('htmlFor' in node) ? node.htmlFor = value : node.setAttribute('for', value); }, 'style': function(node, value){ (node.style) ? node.style.cssText = value : node.setAttribute('style', value); }, 'value': function(node, value){ node.value = (value != null) ? value : ''; } }); propertyGetters['class'] = function(node){ return ('className' in node) ? node.className || null : node.getAttribute('class'); }; /* <webkit> */ var el = document.createElement('button'); // IE sets type as readonly and throws try { el.type = 'button'; } catch(e){} if (el.type != 'button') propertySetters.type = function(node, value){ node.setAttribute('type', value); }; el = null; /* </webkit> */ /*<IE>*/ var input = document.createElement('input'); input.value = 't'; input.type = 'submit'; if (input.value != 't') propertySetters.type = function(node, type){ var value = node.value; node.type = type; node.value = value; }; input = null; /*</IE>*/ /* getProperty, setProperty */ /* <ltIE9> */ var pollutesGetAttribute = (function(div){ div.random = 'attribute'; return (div.getAttribute('random') == 'attribute'); })(document.createElement('div')); /* <ltIE9> */ Element.implement({ setProperty: function(name, value){ var setter = propertySetters[name.toLowerCase()]; if (setter){ setter(this, value); } else { /* <ltIE9> */ if (pollutesGetAttribute) var attributeWhiteList = this.retrieve('$attributeWhiteList', {}); /* </ltIE9> */ if (value == null){ this.removeAttribute(name); /* <ltIE9> */ if (pollutesGetAttribute) delete attributeWhiteList[name]; /* </ltIE9> */ } else { this.setAttribute(name, '' + value); /* <ltIE9> */ if (pollutesGetAttribute) attributeWhiteList[name] = true; /* </ltIE9> */ } } return this; }, setProperties: function(attributes){ for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]); return this; }, getProperty: function(name){ var getter = propertyGetters[name.toLowerCase()]; if (getter) return getter(this); /* <ltIE9> */ if (pollutesGetAttribute){ var attr = this.getAttributeNode(name), attributeWhiteList = this.retrieve('$attributeWhiteList', {}); if (!attr) return null; if (attr.expando && !attributeWhiteList[name]){ var outer = this.outerHTML; // segment by the opening tag and find mention of attribute name if (outer.substr(0, outer.search(/\/?['"]?>(?![^<]*<['"])/)).indexOf(name) < 0) return null; attributeWhiteList[name] = true; } } /* </ltIE9> */ var result = Slick.getAttribute(this, name); return (!result && !Slick.hasAttribute(this, name)) ? null : result; }, getProperties: function(){ var args = Array.from(arguments); return args.map(this.getProperty, this).associate(args); }, removeProperty: function(name){ return this.setProperty(name, null); }, removeProperties: function(){ Array.each(arguments, this.removeProperty, this); return this; }, set: function(prop, value){ var property = Element.Properties[prop]; (property && property.set) ? property.set.call(this, value) : this.setProperty(prop, value); }.overloadSetter(), get: function(prop){ var property = Element.Properties[prop]; return (property && property.get) ? property.get.apply(this) : this.getProperty(prop); }.overloadGetter(), erase: function(prop){ var property = Element.Properties[prop]; (property && property.erase) ? property.erase.apply(this) : this.removeProperty(prop); return this; }, hasClass: function(className){ return this.className.clean().contains(className, ' '); }, addClass: function(className){ if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean(); return this; }, removeClass: function(className){ this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1'); return this; }, toggleClass: function(className, force){ if (force == null) force = !this.hasClass(className); return (force) ? this.addClass(className) : this.removeClass(className); }, adopt: function(){ var parent = this, fragment, elements = Array.flatten(arguments), length = elements.length; if (length > 1) parent = fragment = document.createDocumentFragment(); for (var i = 0; i < length; i++){ var element = document.id(elements[i], true); if (element) parent.appendChild(element); } if (fragment) this.appendChild(fragment); return this; }, appendText: function(text, where){ return this.grab(this.getDocument().newTextNode(text), where); }, grab: function(el, where){ inserters[where || 'bottom'](document.id(el, true), this); return this; }, inject: function(el, where){ inserters[where || 'bottom'](this, document.id(el, true)); return this; }, replaces: function(el){ el = document.id(el, true); el.parentNode.replaceChild(this, el); return this; }, wraps: function(el, where){ el = document.id(el, true); return this.replaces(el).grab(el, where); }, getSelected: function(){ this.selectedIndex; // Safari 3.2.1 return new Elements(Array.from(this.options).filter(function(option){ return option.selected; })); }, toQueryString: function(){ var queryString = []; this.getElements('input, select, textarea').each(function(el){ var type = el.type; if (!el.name || el.disabled || type == 'submit' || type == 'reset' || type == 'file' || type == 'image') return; var value = (el.get('tag') == 'select') ? el.getSelected().map(function(opt){ // IE return document.id(opt).get('value'); }) : ((type == 'radio' || type == 'checkbox') && !el.checked) ? null : el.get('value'); Array.from(value).each(function(val){ if (typeof val != 'undefined') queryString.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(val)); }); }); return queryString.join('&'); } }); var collected = {}, storage = {}; var get = function(uid){ return (storage[uid] || (storage[uid] = {})); }; var clean = function(item){ var uid = item.uniqueNumber; if (item.removeEvents) item.removeEvents(); if (item.clearAttributes) item.clearAttributes(); if (uid != null){ delete collected[uid]; delete storage[uid]; } return item; }; var formProps = {input: 'checked', option: 'selected', textarea: 'value'}; Element.implement({ destroy: function(){ var children = clean(this).getElementsByTagName('*'); Array.each(children, clean); Element.dispose(this); return null; }, empty: function(){ Array.from(this.childNodes).each(Element.dispose); return this; }, dispose: function(){ return (this.parentNode) ? this.parentNode.removeChild(this) : this; }, clone: function(contents, keepid){ contents = contents !== false; var clone = this.cloneNode(contents), ce = [clone], te = [this], i; if (contents){ ce.append(Array.from(clone.getElementsByTagName('*'))); te.append(Array.from(this.getElementsByTagName('*'))); } for (i = ce.length; i--;){ var node = ce[i], element = te[i]; if (!keepid) node.removeAttribute('id'); /*<ltIE9>*/ if (node.clearAttributes){ node.clearAttributes(); node.mergeAttributes(element); node.removeAttribute('uniqueNumber'); if (node.options){ var no = node.options, eo = element.options; for (var j = no.length; j--;) no[j].selected = eo[j].selected; } } /*</ltIE9>*/ var prop = formProps[element.tagName.toLowerCase()]; if (prop && element[prop]) node[prop] = element[prop]; } /*<ltIE9>*/ if (Browser.ie){ var co = clone.getElementsByTagName('object'), to = this.getElementsByTagName('object'); for (i = co.length; i--;) co[i].outerHTML = to[i].outerHTML; } /*</ltIE9>*/ return document.id(clone); } }); [Element, Window, Document].invoke('implement', { addListener: function(type, fn){ if (type == 'unload'){ var old = fn, self = this; fn = function(){ self.removeListener('unload', fn); old(); }; } else { collected[Slick.uidOf(this)] = this; } if (this.addEventListener) this.addEventListener(type, fn, !!arguments[2]); else this.attachEvent('on' + type, fn); return this; }, removeListener: function(type, fn){ if (this.removeEventListener) this.removeEventListener(type, fn, !!arguments[2]); else this.detachEvent('on' + type, fn); return this; }, retrieve: function(property, dflt){ var storage = get(Slick.uidOf(this)), prop = storage[property]; if (dflt != null && prop == null) prop = storage[property] = dflt; return prop != null ? prop : null; }, store: function(property, value){ var storage = get(Slick.uidOf(this)); storage[property] = value; return this; }, eliminate: function(property){ var storage = get(Slick.uidOf(this)); delete storage[property]; return this; } }); /*<ltIE9>*/ if (window.attachEvent && !window.addEventListener) window.addListener('unload', function(){ Object.each(collected, clean); if (window.CollectGarbage) CollectGarbage(); }); /*</ltIE9>*/ Element.Properties = {}; //<1.2compat> Element.Properties = new Hash; //</1.2compat> Element.Properties.style = { set: function(style){ this.style.cssText = style; }, get: function(){ return this.style.cssText; }, erase: function(){ this.style.cssText = ''; } }; Element.Properties.tag = { get: function(){ return this.tagName.toLowerCase(); } }; Element.Properties.html = { set: function(html){ if (html == null) html = ''; else if (typeOf(html) == 'array') html = html.join(''); this.innerHTML = html; }, erase: function(){ this.innerHTML = ''; } }; /*<ltIE9>*/ // technique by jdbarlett - http://jdbartlett.com/innershiv/ var div = document.createElement('div'); div.innerHTML = '<nav></nav>'; var supportsHTML5Elements = (div.childNodes.length == 1); if (!supportsHTML5Elements){ var tags = 'abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.split(' '), fragment = document.createDocumentFragment(), l = tags.length; while (l--) fragment.createElement(tags[l]); } div = null; /*</ltIE9>*/ /*<IE>*/ var supportsTableInnerHTML = Function.attempt(function(){ var table = document.createElement('table'); table.innerHTML = '<tr><td></td></tr>'; return true; }); /*<ltFF4>*/ var tr = document.createElement('tr'), html = '<td></td>'; tr.innerHTML = html; var supportsTRInnerHTML = (tr.innerHTML == html); tr = null; /*</ltFF4>*/ if (!supportsTableInnerHTML || !supportsTRInnerHTML || !supportsHTML5Elements){ Element.Properties.html.set = (function(set){ var translations = { table: [1, '<table>', '</table>'], select: [1, '<select>', '</select>'], tbody: [2, '<table><tbody>', '</tbody></table>'], tr: [3, '<table><tbody><tr>', '</tr></tbody></table>'] }; translations.thead = translations.tfoot = translations.tbody; return function(html){ var wrap = translations[this.get('tag')]; if (!wrap && !supportsHTML5Elements) wrap = [0, '', '']; if (!wrap) return set.call(this, html); var level = wrap[0], wrapper = document.createElement('div'), target = wrapper; if (!supportsHTML5Elements) fragment.appendChild(wrapper); wrapper.innerHTML = [wrap[1], html, wrap[2]].flatten().join(''); while (level--) target = target.firstChild; this.empty().adopt(target.childNodes); if (!supportsHTML5Elements) fragment.removeChild(wrapper); wrapper = null; }; })(Element.Properties.html.set); } /*</IE>*/ /*<ltIE9>*/ var testForm = document.createElement('form'); testForm.innerHTML = '<select><option>s</option></select>'; if (testForm.firstChild.value != 's') Element.Properties.value = { set: function(value){ var tag = this.get('tag'); if (tag != 'select') return this.setProperty('value', value); var options = this.getElements('option'); for (var i = 0; i < options.length; i++){ var option = options[i], attr = option.getAttributeNode('value'), optionValue = (attr && attr.specified) ? option.value : option.get('text'); if (optionValue == value) return option.selected = true; } }, get: function(){ var option = this, tag = option.get('tag'); if (tag != 'select' && tag != 'option') return this.getProperty('value'); if (tag == 'select' && !(option = option.getSelected()[0])) return ''; var attr = option.getAttributeNode('value'); return (attr && attr.specified) ? option.value : option.get('text'); } }; testForm = null; /*</ltIE9>*/ /*<IE>*/ if (document.createElement('div').getAttributeNode('id')) Element.Properties.id = { set: function(id){ this.id = this.getAttributeNode('id').value = id; }, get: function(){ return this.id || null; }, erase: function(){ this.id = this.getAttributeNode('id').value = ''; } }; /*</IE>*/ })(); /* --- name: Element.Style description: Contains methods for interacting with the styles of Elements in a fashionable way. license: MIT-style license. requires: Element provides: Element.Style ... */ (function(){ var html = document.html; //<ltIE9> // Check for oldIE, which does not remove styles when they're set to null var el = document.createElement('div'); el.style.color = 'red'; el.style.color = null; var doesNotRemoveStyles = el.style.color == 'red'; el = null; //</ltIE9> Element.Properties.styles = {set: function(styles){ this.setStyles(styles); }}; var hasOpacity = (html.style.opacity != null), hasFilter = (html.style.filter != null), reAlpha = /alpha\(opacity=([\d.]+)\)/i; var setVisibility = function(element, opacity){ element.store('$opacity', opacity); element.style.visibility = opacity > 0 || opacity == null ? 'visible' : 'hidden'; }; var setOpacity = (hasOpacity ? function(element, opacity){ element.style.opacity = opacity; } : (hasFilter ? function(element, opacity){ var style = element.style; if (!element.currentStyle || !element.currentStyle.hasLayout) style.zoom = 1; if (opacity == null || opacity == 1) opacity = ''; else opacity = 'alpha(opacity=' + (opacity * 100).limit(0, 100).round() + ')'; var filter = style.filter || element.getComputedStyle('filter') || ''; style.filter = reAlpha.test(filter) ? filter.replace(reAlpha, opacity) : filter + opacity; if (!style.filter) style.removeAttribute('filter'); } : setVisibility)); var getOpacity = (hasOpacity ? function(element){ var opacity = element.style.opacity || element.getComputedStyle('opacity'); return (opacity == '') ? 1 : opacity.toFloat(); } : (hasFilter ? function(element){ var filter = (element.style.filter || element.getComputedStyle('filter')), opacity; if (filter) opacity = filter.match(reAlpha); return (opacity == null || filter == null) ? 1 : (opacity[1] / 100); } : function(element){ var opacity = element.retrieve('$opacity'); if (opacity == null) opacity = (element.style.visibility == 'hidden' ? 0 : 1); return opacity; })); var floatName = (html.style.cssFloat == null) ? 'styleFloat' : 'cssFloat'; Element.implement({ getComputedStyle: function(property){ if (this.currentStyle) return this.currentStyle[property.camelCase()]; var defaultView = Element.getDocument(this).defaultView, computed = defaultView ? defaultView.getComputedStyle(this, null) : null; return (computed) ? computed.getPropertyValue((property == floatName) ? 'float' : property.hyphenate()) : null; }, setStyle: function(property, value){ if (property == 'opacity'){ if (value != null) value = parseFloat(value); setOpacity(this, value); return this; } property = (property == 'float' ? floatName : property).camelCase(); if (typeOf(value) != 'string'){ var map = (Element.Styles[property] || '@').split(' '); value = Array.from(value).map(function(val, i){ if (!map[i]) return ''; return (typeOf(val) == 'number') ? map[i].replace('@', Math.round(val)) : val; }).join(' '); } else if (value == String(Number(value))){ value = Math.round(value); } this.style[property] = value; //<ltIE9> if ((value == '' || value == null) && doesNotRemoveStyles && this.style.removeAttribute){ this.style.removeAttribute(property); } //</ltIE9> return this; }, getStyle: function(property){ if (property == 'opacity') return getOpacity(this); property = (property == 'float' ? floatName : property).camelCase(); var result = this.style[property]; if (!result || property == 'zIndex'){ result = []; for (var style in Element.ShortStyles){ if (property != style) continue; for (var s in Element.ShortStyles[style]) result.push(this.getStyle(s)); return result.join(' '); } result = this.getComputedStyle(property); } if (result){ result = String(result); var color = result.match(/rgba?\([\d\s,]+\)/); if (color) result = result.replace(color[0], color[0].rgbToHex()); } if (Browser.opera || Browser.ie){ if ((/^(height|width)$/).test(property) && !(/px$/.test(result))){ var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'], size = 0; values.each(function(value){ size += this.getStyle('border-' + value + '-width').toInt() + this.getStyle('padding-' + value).toInt(); }, this); return this['offset' + property.capitalize()] - size + 'px'; } if (Browser.ie && (/^border(.+)Width|margin|padding/).test(property) && isNaN(parseFloat(result))){ return '0px'; } } return result; }, setStyles: function(styles){ for (var style in styles) this.setStyle(style, styles[style]); return this; }, getStyles: function(){ var result = {}; Array.flatten(arguments).each(function(key){ result[key] = this.getStyle(key); }, this); return result; } }); Element.Styles = { left: '@px', top: '@px', bottom: '@px', right: '@px', width: '@px', height: '@px', maxWidth: '@px', maxHeight: '@px', minWidth: '@px', minHeight: '@px', backgroundColor: 'rgb(@, @, @)', backgroundPosition: '@px @px', color: 'rgb(@, @, @)', fontSize: '@px', letterSpacing: '@px', lineHeight: '@px', clip: 'rect(@px @px @px @px)', margin: '@px @px @px @px', padding: '@px @px @px @px', border: '@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)', borderWidth: '@px @px @px @px', borderStyle: '@ @ @ @', borderColor: 'rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)', zIndex: '@', 'zoom': '@', fontWeight: '@', textIndent: '@px', opacity: '@' }; //<1.3compat> Element.implement({ setOpacity: function(value){ setOpacity(this, value); return this; }, getOpacity: function(){ return getOpacity(this); } }); Element.Properties.opacity = { set: function(opacity){ setOpacity(this, opacity); setVisibility(this, opacity); }, get: function(){ return getOpacity(this); } }; //</1.3compat> //<1.2compat> Element.Styles = new Hash(Element.Styles); //</1.2compat> Element.ShortStyles = {margin: {}, padding: {}, border: {}, borderWidth: {}, borderStyle: {}, borderColor: {}}; ['Top', 'Right', 'Bottom', 'Left'].each(function(direction){ var Short = Element.ShortStyles; var All = Element.Styles; ['margin', 'padding'].each(function(style){ var sd = style + direction; Short[style][sd] = All[sd] = '@px'; }); var bd = 'border' + direction; Short.border[bd] = All[bd] = '@px @ rgb(@, @, @)'; var bdw = bd + 'Width', bds = bd + 'Style', bdc = bd + 'Color'; Short[bd] = {}; Short.borderWidth[bdw] = Short[bd][bdw] = All[bdw] = '@px'; Short.borderStyle[bds] = Short[bd][bds] = All[bds] = '@'; Short.borderColor[bdc] = Short[bd][bdc] = All[bdc] = 'rgb(@, @, @)'; }); })(); /* --- name: Element.Event description: Contains Element methods for dealing with events. This file also includes mouseenter and mouseleave custom Element Events, if necessary. license: MIT-style license. requires: [Element, Event] provides: Element.Event ... */ (function(){ Element.Properties.events = {set: function(events){ this.addEvents(events); }}; [Element, Window, Document].invoke('implement', { addEvent: function(type, fn){ var events = this.retrieve('events', {}); if (!events[type]) events[type] = {keys: [], values: []}; if (events[type].keys.contains(fn)) return this; events[type].keys.push(fn); var realType = type, custom = Element.Events[type], condition = fn, self = this; if (custom){ if (custom.onAdd) custom.onAdd.call(this, fn, type); if (custom.condition){ condition = function(event){ if (custom.condition.call(this, event, type)) return fn.call(this, event); return true; }; } if (custom.base) realType = Function.from(custom.base).call(this, type); } var defn = function(){ return fn.call(self); }; var nativeEvent = Element.NativeEvents[realType]; if (nativeEvent){ if (nativeEvent == 2){ defn = function(event){ event = new DOMEvent(event, self.getWindow()); if (condition.call(self, event) === false) event.stop(); }; } this.addListener(realType, defn, arguments[2]); } events[type].values.push(defn); return this; }, removeEvent: function(type, fn){ var events = this.retrieve('events'); if (!events || !events[type]) return this; var list = events[type]; var index = list.keys.indexOf(fn); if (index == -1) return this; var value = list.values[index]; delete list.keys[index]; delete list.values[index]; var custom = Element.Events[type]; if (custom){ if (custom.onRemove) custom.onRemove.call(this, fn, type); if (custom.base) type = Function.from(custom.base).call(this, type); } return (Element.NativeEvents[type]) ? this.removeListener(type, value, arguments[2]) : this; }, addEvents: function(events){ for (var event in events) this.addEvent(event, events[event]); return this; }, removeEvents: function(events){ var type; if (typeOf(events) == 'object'){ for (type in events) this.removeEvent(type, events[type]); return this; } var attached = this.retrieve('events'); if (!attached) return this; if (!events){ for (type in attached) this.removeEvents(type); this.eliminate('events'); } else if (attached[events]){ attached[events].keys.each(function(fn){ this.removeEvent(events, fn); }, this); delete attached[events]; } return this; }, fireEvent: function(type, args, delay){ var events = this.retrieve('events'); if (!events || !events[type]) return this; args = Array.from(args); events[type].keys.each(function(fn){ if (delay) fn.delay(delay, this, args); else fn.apply(this, args); }, this); return this; }, cloneEvents: function(from, type){ from = document.id(from); var events = from.retrieve('events'); if (!events) return this; if (!type){ for (var eventType in events) this.cloneEvents(from, eventType); } else if (events[type]){ events[type].keys.each(function(fn){ this.addEvent(type, fn); }, this); } return this; } }); Element.NativeEvents = { click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons mousewheel: 2, DOMMouseScroll: 2, //mouse wheel mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement keydown: 2, keypress: 2, keyup: 2, //keyboard orientationchange: 2, // mobile touchstart: 2, touchmove: 2, touchend: 2, touchcancel: 2, // touch gesturestart: 2, gesturechange: 2, gestureend: 2, // gesture focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, paste: 2, input: 2, //form elements load: 2, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window error: 1, abort: 1, scroll: 1 //misc }; Element.Events = {mousewheel: { base: (Browser.firefox) ? 'DOMMouseScroll' : 'mousewheel' }}; if ('onmouseenter' in document.documentElement){ Element.NativeEvents.mouseenter = Element.NativeEvents.mouseleave = 2; } else { var check = function(event){ var related = event.relatedTarget; if (related == null) return true; if (!related) return false; return (related != this && related.prefix != 'xul' && typeOf(this) != 'document' && !this.contains(related)); }; Element.Events.mouseenter = { base: 'mouseover', condition: check }; Element.Events.mouseleave = { base: 'mouseout', condition: check }; } /*<ltIE9>*/ if (!window.addEventListener){ Element.NativeEvents.propertychange = 2; Element.Events.change = { base: function(){ var type = this.type; return (this.get('tag') == 'input' && (type == 'radio' || type == 'checkbox')) ? 'propertychange' : 'change' }, condition: function(event){ return this.type != 'radio' || (event.event.propertyName == 'checked' && this.checked); } } } /*</ltIE9>*/ //<1.2compat> Element.Events = new Hash(Element.Events); //</1.2compat> })(); /* --- name: Element.Delegation description: Extends the Element native object to include the delegate method for more efficient event management. license: MIT-style license. requires: [Element.Event] provides: [Element.Delegation] ... */ (function(){ var eventListenerSupport = !!window.addEventListener; Element.NativeEvents.focusin = Element.NativeEvents.focusout = 2; var bubbleUp = function(self, match, fn, event, target){ while (target && target != self){ if (match(target, event)) return fn.call(target, event, target); target = document.id(target.parentNode); } }; var map = { mouseenter: { base: 'mouseover' }, mouseleave: { base: 'mouseout' }, focus: { base: 'focus' + (eventListenerSupport ? '' : 'in'), capture: true }, blur: { base: eventListenerSupport ? 'blur' : 'focusout', capture: true } }; /*<ltIE9>*/ var _key = '$delegation:'; var formObserver = function(type){ return { base: 'focusin', remove: function(self, uid){ var list = self.retrieve(_key + type + 'listeners', {})[uid]; if (list && list.forms) for (var i = list.forms.length; i--;){ list.forms[i].removeEvent(type, list.fns[i]); } }, listen: function(self, match, fn, event, target, uid){ var form = (target.get('tag') == 'form') ? target : event.target.getParent('form'); if (!form) return; var listeners = self.retrieve(_key + type + 'listeners', {}), listener = listeners[uid] || {forms: [], fns: []}, forms = listener.forms, fns = listener.fns; if (forms.indexOf(form) != -1) return; forms.push(form); var _fn = function(event){ bubbleUp(self, match, fn, event, target); }; form.addEvent(type, _fn); fns.push(_fn); listeners[uid] = listener; self.store(_key + type + 'listeners', listeners); } }; }; var inputObserver = function(type){ return { base: 'focusin', listen: function(self, match, fn, event, target){ var events = {blur: function(){ this.removeEvents(events); }}; events[type] = function(event){ bubbleUp(self, match, fn, event, target); }; event.target.addEvents(events); } }; }; if (!eventListenerSupport) Object.append(map, { submit: formObserver('submit'), reset: formObserver('reset'), change: inputObserver('change'), select: inputObserver('select') }); /*</ltIE9>*/ var proto = Element.prototype, addEvent = proto.addEvent, removeEvent = proto.removeEvent; var relay = function(old, method){ return function(type, fn, useCapture){ if (type.indexOf(':relay') == -1) return old.call(this, type, fn, useCapture); var parsed = Slick.parse(type).expressions[0][0]; if (parsed.pseudos[0].key != 'relay') return old.call(this, type, fn, useCapture); var newType = parsed.tag; parsed.pseudos.slice(1).each(function(pseudo){ newType += ':' + pseudo.key + (pseudo.value ? '(' + pseudo.value + ')' : ''); }); old.call(this, type, fn); return method.call(this, newType, parsed.pseudos[0].value, fn); }; }; var delegation = { addEvent: function(type, match, fn){ var storage = this.retrieve('$delegates', {}), stored = storage[type]; if (stored) for (var _uid in stored){ if (stored[_uid].fn == fn && stored[_uid].match == match) return this; } var _type = type, _match = match, _fn = fn, _map = map[type] || {}; type = _map.base || _type; match = function(target){ return Slick.match(target, _match); }; var elementEvent = Element.Events[_type]; if (elementEvent && elementEvent.condition){ var __match = match, condition = elementEvent.condition; match = function(target, event){ return __match(target, event) && condition.call(target, event, type); }; } var self = this, uid = String.uniqueID(); var delegator = _map.listen ? function(event, target){ if (!target && event && event.target) target = event.target; if (target) _map.listen(self, match, fn, event, target, uid); } : function(event, target){ if (!target && event && event.target) target = event.target; if (target) bubbleUp(self, match, fn, event, target); }; if (!stored) stored = {}; stored[uid] = { match: _match, fn: _fn, delegator: delegator }; storage[_type] = stored; return addEvent.call(this, type, delegator, _map.capture); }, removeEvent: function(type, match, fn, _uid){ var storage = this.retrieve('$delegates', {}), stored = storage[type]; if (!stored) return this; if (_uid){ var _type = type, delegator = stored[_uid].delegator, _map = map[type] || {}; type = _map.base || _type; if (_map.remove) _map.remove(this, _uid); delete stored[_uid]; storage[_type] = stored; return removeEvent.call(this, type, delegator); } var __uid, s; if (fn) for (__uid in stored){ s = stored[__uid]; if (s.match == match && s.fn == fn) return delegation.removeEvent.call(this, type, match, fn, __uid); } else for (__uid in stored){ s = stored[__uid]; if (s.match == match) delegation.removeEvent.call(this, type, match, s.fn, __uid); } return this; } }; [Element, Window, Document].invoke('implement', { addEvent: relay(addEvent, delegation.addEvent), removeEvent: relay(removeEvent, delegation.removeEvent) }); })(); /* --- name: Element.Dimensions description: Contains methods to work with size, scroll, or positioning of Elements and the window object. license: MIT-style license. credits: - Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html). - Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html). requires: [Element, Element.Style] provides: [Element.Dimensions] ... */ (function(){ var element = document.createElement('div'), child = document.createElement('div'); element.style.height = '0'; element.appendChild(child); var brokenOffsetParent = (child.offsetParent === element); element = child = null; var isOffset = function(el){ return styleString(el, 'position') != 'static' || isBody(el); }; var isOffsetStatic = function(el){ return isOffset(el) || (/^(?:table|td|th)$/i).test(el.tagName); }; Element.implement({ scrollTo: function(x, y){ if (isBody(this)){ this.getWindow().scrollTo(x, y); } else { this.scrollLeft = x; this.scrollTop = y; } return this; }, getSize: function(){ if (isBody(this)) return this.getWindow().getSize(); return {x: this.offsetWidth, y: this.offsetHeight}; }, getScrollSize: function(){ if (isBody(this)) return this.getWindow().getScrollSize(); return {x: this.scrollWidth, y: this.scrollHeight}; }, getScroll: function(){ if (isBody(this)) return this.getWindow().getScroll(); return {x: this.scrollLeft, y: this.scrollTop}; }, getScrolls: function(){ var element = this.parentNode, position = {x: 0, y: 0}; while (element && !isBody(element)){ position.x += element.scrollLeft; position.y += element.scrollTop; element = element.parentNode; } return position; }, getOffsetParent: brokenOffsetParent ? function(){ var element = this; if (isBody(element) || styleString(element, 'position') == 'fixed') return null; var isOffsetCheck = (styleString(element, 'position') == 'static') ? isOffsetStatic : isOffset; while ((element = element.parentNode)){ if (isOffsetCheck(element)) return element; } return null; } : function(){ var element = this; if (isBody(element) || styleString(element, 'position') == 'fixed') return null; try { return element.offsetParent; } catch(e) {} return null; }, getOffsets: function(){ if (this.getBoundingClientRect && !Browser.Platform.ios){ var bound = this.getBoundingClientRect(), html = document.id(this.getDocument().documentElement), htmlScroll = html.getScroll(), elemScrolls = this.getScrolls(), isFixed = (styleString(this, 'position') == 'fixed'); return { x: bound.left.toInt() + elemScrolls.x + ((isFixed) ? 0 : htmlScroll.x) - html.clientLeft, y: bound.top.toInt() + elemScrolls.y + ((isFixed) ? 0 : htmlScroll.y) - html.clientTop }; } var element = this, position = {x: 0, y: 0}; if (isBody(this)) return position; while (element && !isBody(element)){ position.x += element.offsetLeft; position.y += element.offsetTop; if (Browser.firefox){ if (!borderBox(element)){ position.x += leftBorder(element); position.y += topBorder(element); } var parent = element.parentNode; if (parent && styleString(parent, 'overflow') != 'visible'){ position.x += leftBorder(parent); position.y += topBorder(parent); } } else if (element != this && Browser.safari){ position.x += leftBorder(element); position.y += topBorder(element); } element = element.offsetParent; } if (Browser.firefox && !borderBox(this)){ position.x -= leftBorder(this); position.y -= topBorder(this); } return position; }, getPosition: function(relative){ var offset = this.getOffsets(), scroll = this.getScrolls(); var position = { x: offset.x - scroll.x, y: offset.y - scroll.y }; if (relative && (relative = document.id(relative))){ var relativePosition = relative.getPosition(); return {x: position.x - relativePosition.x - leftBorder(relative), y: position.y - relativePosition.y - topBorder(relative)}; } return position; }, getCoordinates: function(element){ if (isBody(this)) return this.getWindow().getCoordinates(); var position = this.getPosition(element), size = this.getSize(); var obj = { left: position.x, top: position.y, width: size.x, height: size.y }; obj.right = obj.left + obj.width; obj.bottom = obj.top + obj.height; return obj; }, computePosition: function(obj){ return { left: obj.x - styleNumber(this, 'margin-left'), top: obj.y - styleNumber(this, 'margin-top') }; }, setPosition: function(obj){ return this.setStyles(this.computePosition(obj)); } }); [Document, Window].invoke('implement', { getSize: function(){ var doc = getCompatElement(this); return {x: doc.clientWidth, y: doc.clientHeight}; }, getScroll: function(){ var win = this.getWindow(), doc = getCompatElement(this); return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop}; }, getScrollSize: function(){ var doc = getCompatElement(this), min = this.getSize(), body = this.getDocument().body; return {x: Math.max(doc.scrollWidth, body.scrollWidth, min.x), y: Math.max(doc.scrollHeight, body.scrollHeight, min.y)}; }, getPosition: function(){ return {x: 0, y: 0}; }, getCoordinates: function(){ var size = this.getSize(); return {top: 0, left: 0, bottom: size.y, right: size.x, height: size.y, width: size.x}; } }); // private methods var styleString = Element.getComputedStyle; function styleNumber(element, style){ return styleString(element, style).toInt() || 0; } function borderBox(element){ return styleString(element, '-moz-box-sizing') == 'border-box'; } function topBorder(element){ return styleNumber(element, 'border-top-width'); } function leftBorder(element){ return styleNumber(element, 'border-left-width'); } function isBody(element){ return (/^(?:body|html)$/i).test(element.tagName); } function getCompatElement(element){ var doc = element.getDocument(); return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; } })(); //aliases Element.alias({position: 'setPosition'}); //compatability [Window, Document, Element].invoke('implement', { getHeight: function(){ return this.getSize().y; }, getWidth: function(){ return this.getSize().x; }, getScrollTop: function(){ return this.getScroll().y; }, getScrollLeft: function(){ return this.getScroll().x; }, getScrollHeight: function(){ return this.getScrollSize().y; }, getScrollWidth: function(){ return this.getScrollSize().x; }, getTop: function(){ return this.getPosition().y; }, getLeft: function(){ return this.getPosition().x; } }); /* --- name: Fx description: Contains the basic animation logic to be extended by all other Fx Classes. license: MIT-style license. requires: [Chain, Events, Options] provides: Fx ... */ (function(){ var Fx = this.Fx = new Class({ Implements: [Chain, Events, Options], options: { /* onStart: nil, onCancel: nil, onComplete: nil, */ fps: 60, unit: false, duration: 500, frames: null, frameSkip: true, link: 'ignore' }, initialize: function(options){ this.subject = this.subject || this; this.setOptions(options); }, getTransition: function(){ return function(p){ return -(Math.cos(Math.PI * p) - 1) / 2; }; }, step: function(now){ if (this.options.frameSkip){ var diff = (this.time != null) ? (now - this.time) : 0, frames = diff / this.frameInterval; this.time = now; this.frame += frames; } else { this.frame++; } if (this.frame < this.frames){ var delta = this.transition(this.frame / this.frames); this.set(this.compute(this.from, this.to, delta)); } else { this.frame = this.frames; this.set(this.compute(this.from, this.to, 1)); this.stop(); } }, set: function(now){ return now; }, compute: function(from, to, delta){ return Fx.compute(from, to, delta); }, check: function(){ if (!this.isRunning()) return true; switch (this.options.link){ case 'cancel': this.cancel(); return true; case 'chain': this.chain(this.caller.pass(arguments, this)); return false; } return false; }, start: function(from, to){ if (!this.check(from, to)) return this; this.from = from; this.to = to; this.frame = (this.options.frameSkip) ? 0 : -1; this.time = null; this.transition = this.getTransition(); var frames = this.options.frames, fps = this.options.fps, duration = this.options.duration; this.duration = Fx.Durations[duration] || duration.toInt(); this.frameInterval = 1000 / fps; this.frames = frames || Math.round(this.duration / this.frameInterval); this.fireEvent('start', this.subject); pushInstance.call(this, fps); return this; }, stop: function(){ if (this.isRunning()){ this.time = null; pullInstance.call(this, this.options.fps); if (this.frames == this.frame){ this.fireEvent('complete', this.subject); if (!this.callChain()) this.fireEvent('chainComplete', this.subject); } else { this.fireEvent('stop', this.subject); } } return this; }, cancel: function(){ if (this.isRunning()){ this.time = null; pullInstance.call(this, this.options.fps); this.frame = this.frames; this.fireEvent('cancel', this.subject).clearChain(); } return this; }, pause: function(){ if (this.isRunning()){ this.time = null; pullInstance.call(this, this.options.fps); } return this; }, resume: function(){ if ((this.frame < this.frames) && !this.isRunning()) pushInstance.call(this, this.options.fps); return this; }, isRunning: function(){ var list = instances[this.options.fps]; return list && list.contains(this); } }); Fx.compute = function(from, to, delta){ return (to - from) * delta + from; }; Fx.Durations = {'short': 250, 'normal': 500, 'long': 1000}; // global timers var instances = {}, timers = {}; var loop = function(){ var now = Date.now(); for (var i = this.length; i--;){ var instance = this[i]; if (instance) instance.step(now); } }; var pushInstance = function(fps){ var list = instances[fps] || (instances[fps] = []); list.push(this); if (!timers[fps]) timers[fps] = loop.periodical(Math.round(1000 / fps), list); }; var pullInstance = function(fps){ var list = instances[fps]; if (list){ list.erase(this); if (!list.length && timers[fps]){ delete instances[fps]; timers[fps] = clearInterval(timers[fps]); } } }; })(); /* --- name: Fx.CSS description: Contains the CSS animation logic. Used by Fx.Tween, Fx.Morph, Fx.Elements. license: MIT-style license. requires: [Fx, Element.Style] provides: Fx.CSS ... */ Fx.CSS = new Class({ Extends: Fx, //prepares the base from/to object prepare: function(element, property, values){ values = Array.from(values); var from = values[0], to = values[1]; if (to == null){ to = from; from = element.getStyle(property); var unit = this.options.unit; // adapted from: https://github.com/ryanmorr/fx/blob/master/fx.js#L299 if (unit && from.slice(-unit.length) != unit && parseFloat(from) != 0){ element.setStyle(property, to + unit); var value = element.getComputedStyle(property); // IE and Opera support pixelLeft or pixelWidth if (!(/px$/.test(value))){ value = element.style[('pixel-' + property).camelCase()]; if (value == null){ // adapted from Dean Edwards' http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 var left = element.style.left; element.style.left = to + unit; value = element.style.pixelLeft; element.style.left = left; } } from = (to || 1) / (parseFloat(value) || 1) * (parseFloat(from) || 0); element.setStyle(property, from + unit); } } return {from: this.parse(from), to: this.parse(to)}; }, //parses a value into an array parse: function(value){ value = Function.from(value)(); value = (typeof value == 'string') ? value.split(' ') : Array.from(value); return value.map(function(val){ val = String(val); var found = false; Object.each(Fx.CSS.Parsers, function(parser, key){ if (found) return; var parsed = parser.parse(val); if (parsed || parsed === 0) found = {value: parsed, parser: parser}; }); found = found || {value: val, parser: Fx.CSS.Parsers.String}; return found; }); }, //computes by a from and to prepared objects, using their parsers. compute: function(from, to, delta){ var computed = []; (Math.min(from.length, to.length)).times(function(i){ computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser}); }); computed.$family = Function.from('fx:css:value'); return computed; }, //serves the value as settable serve: function(value, unit){ if (typeOf(value) != 'fx:css:value') value = this.parse(value); var returned = []; value.each(function(bit){ returned = returned.concat(bit.parser.serve(bit.value, unit)); }); return returned; }, //renders the change to an element render: function(element, property, value, unit){ element.setStyle(property, this.serve(value, unit)); }, //searches inside the page css to find the values for a selector search: function(selector){ if (Fx.CSS.Cache[selector]) return Fx.CSS.Cache[selector]; var to = {}, selectorTest = new RegExp('^' + selector.escapeRegExp() + '$'); Array.each(document.styleSheets, function(sheet, j){ var href = sheet.href; if (href && href.contains('://') && !href.contains(document.domain)) return; var rules = sheet.rules || sheet.cssRules; Array.each(rules, function(rule, i){ if (!rule.style) return; var selectorText = (rule.selectorText) ? rule.selectorText.replace(/^\w+/, function(m){ return m.toLowerCase(); }) : null; if (!selectorText || !selectorTest.test(selectorText)) return; Object.each(Element.Styles, function(value, style){ if (!rule.style[style] || Element.ShortStyles[style]) return; value = String(rule.style[style]); to[style] = ((/^rgb/).test(value)) ? value.rgbToHex() : value; }); }); }); return Fx.CSS.Cache[selector] = to; } }); Fx.CSS.Cache = {}; Fx.CSS.Parsers = { Color: { parse: function(value){ if (value.match(/^#[0-9a-f]{3,6}$/i)) return value.hexToRgb(true); return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value[1], value[2], value[3]] : false; }, compute: function(from, to, delta){ return from.map(function(value, i){ return Math.round(Fx.compute(from[i], to[i], delta)); }); }, serve: function(value){ return value.map(Number); } }, Number: { parse: parseFloat, compute: Fx.compute, serve: function(value, unit){ return (unit) ? value + unit : value; } }, String: { parse: Function.from(false), compute: function(zero, one){ return one; }, serve: function(zero){ return zero; } } }; //<1.2compat> Fx.CSS.Parsers = new Hash(Fx.CSS.Parsers); //</1.2compat> /* --- name: Fx.Tween description: Formerly Fx.Style, effect to transition any CSS property for an element. license: MIT-style license. requires: Fx.CSS provides: [Fx.Tween, Element.fade, Element.highlight] ... */ Fx.Tween = new Class({ Extends: Fx.CSS, initialize: function(element, options){ this.element = this.subject = document.id(element); this.parent(options); }, set: function(property, now){ if (arguments.length == 1){ now = property; property = this.property || this.options.property; } this.render(this.element, property, now, this.options.unit); return this; }, start: function(property, from, to){ if (!this.check(property, from, to)) return this; var args = Array.flatten(arguments); this.property = this.options.property || args.shift(); var parsed = this.prepare(this.element, this.property, args); return this.parent(parsed.from, parsed.to); } }); Element.Properties.tween = { set: function(options){ this.get('tween').cancel().setOptions(options); return this; }, get: function(){ var tween = this.retrieve('tween'); if (!tween){ tween = new Fx.Tween(this, {link: 'cancel'}); this.store('tween', tween); } return tween; } }; Element.implement({ tween: function(property, from, to){ this.get('tween').start(property, from, to); return this; }, fade: function(how){ var fade = this.get('tween'), method, args = ['opacity'].append(arguments), toggle; if (args[1] == null) args[1] = 'toggle'; switch (args[1]){ case 'in': method = 'start'; args[1] = 1; break; case 'out': method = 'start'; args[1] = 0; break; case 'show': method = 'set'; args[1] = 1; break; case 'hide': method = 'set'; args[1] = 0; break; case 'toggle': var flag = this.retrieve('fade:flag', this.getStyle('opacity') == 1); method = 'start'; args[1] = flag ? 0 : 1; this.store('fade:flag', !flag); toggle = true; break; default: method = 'start'; } if (!toggle) this.eliminate('fade:flag'); fade[method].apply(fade, args); var to = args[args.length - 1]; if (method == 'set' || to != 0) this.setStyle('visibility', to == 0 ? 'hidden' : 'visible'); else fade.chain(function(){ this.element.setStyle('visibility', 'hidden'); this.callChain(); }); return this; }, highlight: function(start, end){ if (!end){ end = this.retrieve('highlight:original', this.getStyle('background-color')); end = (end == 'transparent') ? '#fff' : end; } var tween = this.get('tween'); tween.start('background-color', start || '#ffff88', end).chain(function(){ this.setStyle('background-color', this.retrieve('highlight:original')); tween.callChain(); }.bind(this)); return this; } }); /* --- name: Fx.Morph description: Formerly Fx.Styles, effect to transition any number of CSS properties for an element using an object of rules, or CSS based selector rules. license: MIT-style license. requires: Fx.CSS provides: Fx.Morph ... */ Fx.Morph = new Class({ Extends: Fx.CSS, initialize: function(element, options){ this.element = this.subject = document.id(element); this.parent(options); }, set: function(now){ if (typeof now == 'string') now = this.search(now); for (var p in now) this.render(this.element, p, now[p], this.options.unit); return this; }, compute: function(from, to, delta){ var now = {}; for (var p in from) now[p] = this.parent(from[p], to[p], delta); return now; }, start: function(properties){ if (!this.check(properties)) return this; if (typeof properties == 'string') properties = this.search(properties); var from = {}, to = {}; for (var p in properties){ var parsed = this.prepare(this.element, p, properties[p]); from[p] = parsed.from; to[p] = parsed.to; } return this.parent(from, to); } }); Element.Properties.morph = { set: function(options){ this.get('morph').cancel().setOptions(options); return this; }, get: function(){ var morph = this.retrieve('morph'); if (!morph){ morph = new Fx.Morph(this, {link: 'cancel'}); this.store('morph', morph); } return morph; } }; Element.implement({ morph: function(props){ this.get('morph').start(props); return this; } }); /* --- name: Fx.Transitions description: Contains a set of advanced transitions to be used with any of the Fx Classes. license: MIT-style license. credits: - Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified and optimized to be used with MooTools. requires: Fx provides: Fx.Transitions ... */ Fx.implement({ getTransition: function(){ var trans = this.options.transition || Fx.Transitions.Sine.easeInOut; if (typeof trans == 'string'){ var data = trans.split(':'); trans = Fx.Transitions; trans = trans[data[0]] || trans[data[0].capitalize()]; if (data[1]) trans = trans['ease' + data[1].capitalize() + (data[2] ? data[2].capitalize() : '')]; } return trans; } }); Fx.Transition = function(transition, params){ params = Array.from(params); var easeIn = function(pos){ return transition(pos, params); }; return Object.append(easeIn, { easeIn: easeIn, easeOut: function(pos){ return 1 - transition(1 - pos, params); }, easeInOut: function(pos){ return (pos <= 0.5 ? transition(2 * pos, params) : (2 - transition(2 * (1 - pos), params))) / 2; } }); }; Fx.Transitions = { linear: function(zero){ return zero; } }; //<1.2compat> Fx.Transitions = new Hash(Fx.Transitions); //</1.2compat> Fx.Transitions.extend = function(transitions){ for (var transition in transitions) Fx.Transitions[transition] = new Fx.Transition(transitions[transition]); }; Fx.Transitions.extend({ Pow: function(p, x){ return Math.pow(p, x && x[0] || 6); }, Expo: function(p){ return Math.pow(2, 8 * (p - 1)); }, Circ: function(p){ return 1 - Math.sin(Math.acos(p)); }, Sine: function(p){ return 1 - Math.cos(p * Math.PI / 2); }, Back: function(p, x){ x = x && x[0] || 1.618; return Math.pow(p, 2) * ((x + 1) * p - x); }, Bounce: function(p){ var value; for (var a = 0, b = 1; 1; a += b, b /= 2){ if (p >= (7 - 4 * a) / 11){ value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2); break; } } return value; }, Elastic: function(p, x){ return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x && x[0] || 1) / 3); } }); ['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){ Fx.Transitions[transition] = new Fx.Transition(function(p){ return Math.pow(p, i + 2); }); }); /* --- name: Request description: Powerful all purpose Request Class. Uses XMLHTTPRequest. license: MIT-style license. requires: [Object, Element, Chain, Events, Options, Browser] provides: Request ... */ (function(){ var empty = function(){}, progressSupport = ('onprogress' in new Browser.Request); var Request = this.Request = new Class({ Implements: [Chain, Events, Options], options: {/* onRequest: function(){}, onLoadstart: function(event, xhr){}, onProgress: function(event, xhr){}, onComplete: function(){}, onCancel: function(){}, onSuccess: function(responseText, responseXML){}, onFailure: function(xhr){}, onException: function(headerName, value){}, onTimeout: function(){}, user: '', password: '',*/ url: '', data: '', headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' }, async: true, format: false, method: 'post', link: 'ignore', isSuccess: null, emulation: true, urlEncoded: true, encoding: 'utf-8', evalScripts: false, evalResponse: false, timeout: 0, noCache: false }, initialize: function(options){ this.xhr = new Browser.Request(); this.setOptions(options); this.headers = this.options.headers; }, onStateChange: function(){ var xhr = this.xhr; if (xhr.readyState != 4 || !this.running) return; this.running = false; this.status = 0; Function.attempt(function(){ var status = xhr.status; this.status = (status == 1223) ? 204 : status; }.bind(this)); xhr.onreadystatechange = empty; if (progressSupport) xhr.onprogress = xhr.onloadstart = empty; clearTimeout(this.timer); this.response = {text: this.xhr.responseText || '', xml: this.xhr.responseXML}; if (this.options.isSuccess.call(this, this.status)) this.success(this.response.text, this.response.xml); else this.failure(); }, isSuccess: function(){ var status = this.status; return (status >= 200 && status < 300); }, isRunning: function(){ return !!this.running; }, processScripts: function(text){ if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return Browser.exec(text); return text.stripScripts(this.options.evalScripts); }, success: function(text, xml){ this.onSuccess(this.processScripts(text), xml); }, onSuccess: function(){ this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain(); }, failure: function(){ this.onFailure(); }, onFailure: function(){ this.fireEvent('complete').fireEvent('failure', this.xhr); }, loadstart: function(event){ this.fireEvent('loadstart', [event, this.xhr]); }, progress: function(event){ this.fireEvent('progress', [event, this.xhr]); }, timeout: function(){ this.fireEvent('timeout', this.xhr); }, setHeader: function(name, value){ this.headers[name] = value; return this; }, getHeader: function(name){ return Function.attempt(function(){ return this.xhr.getResponseHeader(name); }.bind(this)); }, check: function(){ if (!this.running) return true; switch (this.options.link){ case 'cancel': this.cancel(); return true; case 'chain': this.chain(this.caller.pass(arguments, this)); return false; } return false; }, send: function(options){ if (!this.check(options)) return this; this.options.isSuccess = this.options.isSuccess || this.isSuccess; this.running = true; var type = typeOf(options); if (type == 'string' || type == 'element') options = {data: options}; var old = this.options; options = Object.append({data: old.data, url: old.url, method: old.method}, options); var data = options.data, url = String(options.url), method = options.method.toLowerCase(); switch (typeOf(data)){ case 'element': data = document.id(data).toQueryString(); break; case 'object': case 'hash': data = Object.toQueryString(data); } if (this.options.format){ var format = 'format=' + this.options.format; data = (data) ? format + '&' + data : format; } if (this.options.emulation && !['get', 'post'].contains(method)){ var _method = '_method=' + method; data = (data) ? _method + '&' + data : _method; method = 'post'; } if (this.options.urlEncoded && ['post', 'put'].contains(method)){ var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : ''; this.headers['Content-type'] = 'application/x-www-form-urlencoded' + encoding; } if (!url) url = document.location.pathname; var trimPosition = url.lastIndexOf('/'); if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition); if (this.options.noCache) url += (url.contains('?') ? '&' : '?') + String.uniqueID(); if (data && method == 'get'){ url += (url.contains('?') ? '&' : '?') + data; data = null; } var xhr = this.xhr; if (progressSupport){ xhr.onloadstart = this.loadstart.bind(this); xhr.onprogress = this.progress.bind(this); } xhr.open(method.toUpperCase(), url, this.options.async, this.options.user, this.options.password); if (this.options.user && 'withCredentials' in xhr) xhr.withCredentials = true; xhr.onreadystatechange = this.onStateChange.bind(this); Object.each(this.headers, function(value, key){ try { xhr.setRequestHeader(key, value); } catch (e){ this.fireEvent('exception', [key, value]); } }, this); this.fireEvent('request'); xhr.send(data); if (!this.options.async) this.onStateChange(); else if (this.options.timeout) this.timer = this.timeout.delay(this.options.timeout, this); return this; }, cancel: function(){ if (!this.running) return this; this.running = false; var xhr = this.xhr; xhr.abort(); clearTimeout(this.timer); xhr.onreadystatechange = empty; if (progressSupport) xhr.onprogress = xhr.onloadstart = empty; this.xhr = new Browser.Request(); this.fireEvent('cancel'); return this; } }); var methods = {}; ['get', 'post', 'put', 'delete', 'GET', 'POST', 'PUT', 'DELETE'].each(function(method){ methods[method] = function(data){ var object = { method: method }; if (data != null) object.data = data; return this.send(object); }; }); Request.implement(methods); Element.Properties.send = { set: function(options){ var send = this.get('send').cancel(); send.setOptions(options); return this; }, get: function(){ var send = this.retrieve('send'); if (!send){ send = new Request({ data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action') }); this.store('send', send); } return send; } }; Element.implement({ send: function(url){ var sender = this.get('send'); sender.send({data: this, url: url || sender.options.url}); return this; } }); })(); /* --- name: Request.HTML description: Extends the basic Request Class with additional methods for interacting with HTML responses. license: MIT-style license. requires: [Element, Request] provides: Request.HTML ... */ Request.HTML = new Class({ Extends: Request, options: { update: false, append: false, evalScripts: true, filter: false, headers: { Accept: 'text/html, application/xml, text/xml, */*' } }, success: function(text){ var options = this.options, response = this.response; response.html = text.stripScripts(function(script){ response.javascript = script; }); var match = response.html.match(/<body[^>]*>([\s\S]*?)<\/body>/i); if (match) response.html = match[1]; var temp = new Element('div').set('html', response.html); response.tree = temp.childNodes; response.elements = temp.getElements(options.filter || '*'); if (options.filter) response.tree = response.elements; if (options.update){ var update = document.id(options.update).empty(); if (options.filter) update.adopt(response.elements); else update.set('html', response.html); } else if (options.append){ var append = document.id(options.append); if (options.filter) response.elements.reverse().inject(append); else append.adopt(temp.getChildren()); } if (options.evalScripts) Browser.exec(response.javascript); this.onSuccess(response.tree, response.elements, response.html, response.javascript); } }); Element.Properties.load = { set: function(options){ var load = this.get('load').cancel(); load.setOptions(options); return this; }, get: function(){ var load = this.retrieve('load'); if (!load){ load = new Request.HTML({data: this, link: 'cancel', update: this, method: 'get'}); this.store('load', load); } return load; } }; Element.implement({ load: function(){ this.get('load').send(Array.link(arguments, {data: Type.isObject, url: Type.isString})); return this; } }); /* --- name: JSON description: JSON encoder and decoder. license: MIT-style license. SeeAlso: <http://www.json.org/> requires: [Array, String, Number, Function] provides: JSON ... */ if (typeof JSON == 'undefined') this.JSON = {}; //<1.2compat> JSON = new Hash({ stringify: JSON.stringify, parse: JSON.parse }); //</1.2compat> (function(){ var special = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'}; var escape = function(chr){ return special[chr] || '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4); }; JSON.validate = function(string){ string = string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''); return (/^[\],:{}\s]*$/).test(string); }; JSON.encode = JSON.stringify ? function(obj){ return JSON.stringify(obj); } : function(obj){ if (obj && obj.toJSON) obj = obj.toJSON(); switch (typeOf(obj)){ case 'string': return '"' + obj.replace(/[\x00-\x1f\\"]/g, escape) + '"'; case 'array': return '[' + obj.map(JSON.encode).clean() + ']'; case 'object': case 'hash': var string = []; Object.each(obj, function(value, key){ var json = JSON.encode(value); if (json) string.push(JSON.encode(key) + ':' + json); }); return '{' + string + '}'; case 'number': case 'boolean': return '' + obj; case 'null': return 'null'; } return null; }; JSON.decode = function(string, secure){ if (!string || typeOf(string) != 'string') return null; if (secure || JSON.secure){ if (JSON.parse) return JSON.parse(string); if (!JSON.validate(string)) throw new Error('JSON could not decode the input; security is enabled and the value is not secure.'); } return eval('(' + string + ')'); }; })(); /* --- name: Request.JSON description: Extends the basic Request Class with additional methods for sending and receiving JSON data. license: MIT-style license. requires: [Request, JSON] provides: Request.JSON ... */ Request.JSON = new Class({ Extends: Request, options: { /*onError: function(text, error){},*/ secure: true }, initialize: function(options){ this.parent(options); Object.append(this.headers, { 'Accept': 'application/json', 'X-Request': 'JSON' }); }, success: function(text){ var json; try { json = this.response.json = JSON.decode(text, this.options.secure); } catch (error){ this.fireEvent('error', [text, error]); return; } if (json == null) this.onFailure(); else this.onSuccess(json, text); } }); /* --- name: Cookie description: Class for creating, reading, and deleting browser Cookies. license: MIT-style license. credits: - Based on the functions by Peter-Paul Koch (http://quirksmode.org). requires: [Options, Browser] provides: Cookie ... */ var Cookie = new Class({ Implements: Options, options: { path: '/', domain: false, duration: false, secure: false, document: document, encode: true }, initialize: function(key, options){ this.key = key; this.setOptions(options); }, write: function(value){ if (this.options.encode) value = encodeURIComponent(value); if (this.options.domain) value += '; domain=' + this.options.domain; if (this.options.path) value += '; path=' + this.options.path; if (this.options.duration){ var date = new Date(); date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000); value += '; expires=' + date.toGMTString(); } if (this.options.secure) value += '; secure'; this.options.document.cookie = this.key + '=' + value; return this; }, read: function(){ var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)'); return (value) ? decodeURIComponent(value[1]) : null; }, dispose: function(){ new Cookie(this.key, Object.merge({}, this.options, {duration: -1})).write(''); return this; } }); Cookie.write = function(key, value, options){ return new Cookie(key, options).write(value); }; Cookie.read = function(key){ return new Cookie(key).read(); }; Cookie.dispose = function(key, options){ return new Cookie(key, options).dispose(); }; /* --- name: DOMReady description: Contains the custom event domready. license: MIT-style license. requires: [Browser, Element, Element.Event] provides: [DOMReady, DomReady] ... */ (function(window, document){ var ready, loaded, checks = [], shouldPoll, timer, testElement = document.createElement('div'); var domready = function(){ clearTimeout(timer); if (ready) return; Browser.loaded = ready = true; document.removeListener('DOMContentLoaded', domready).removeListener('readystatechange', check); document.fireEvent('domready'); window.fireEvent('domready'); }; var check = function(){ for (var i = checks.length; i--;) if (checks[i]()){ domready(); return true; } return false; }; var poll = function(){ clearTimeout(timer); if (!check()) timer = setTimeout(poll, 10); }; document.addListener('DOMContentLoaded', domready); /*<ltIE8>*/ // doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/ // testElement.doScroll() throws when the DOM is not ready, only in the top window var doScrollWorks = function(){ try { testElement.doScroll(); return true; } catch (e){} return false; }; // If doScroll works already, it can't be used to determine domready // e.g. in an iframe if (testElement.doScroll && !doScrollWorks()){ checks.push(doScrollWorks); shouldPoll = true; } /*</ltIE8>*/ if (document.readyState) checks.push(function(){ var state = document.readyState; return (state == 'loaded' || state == 'complete'); }); if ('onreadystatechange' in document) document.addListener('readystatechange', check); else shouldPoll = true; if (shouldPoll) poll(); Element.Events.domready = { onAdd: function(fn){ if (ready) fn.call(this); } }; // Make sure that domready fires before load Element.Events.load = { base: 'load', onAdd: function(fn){ if (loaded && this == window) fn.call(this); }, condition: function(){ if (this == window){ domready(); delete Element.Events.load; } return true; } }; // This is based on the custom load event window.addEvent('load', function(){ loaded = true; }); })(window, document); /* --- name: Swiff description: Wrapper for embedding SWF movies. Supports External Interface Communication. license: MIT-style license. credits: - Flash detection & Internet Explorer + Flash Player 9 fix inspired by SWFObject. requires: [Options, Object, Element] provides: Swiff ... */ (function(){ var Swiff = this.Swiff = new Class({ Implements: Options, options: { id: null, height: 1, width: 1, container: null, properties: {}, params: { quality: 'high', allowScriptAccess: 'always', wMode: 'window', swLiveConnect: true }, callBacks: {}, vars: {} }, toElement: function(){ return this.object; }, initialize: function(path, options){ this.instance = 'Swiff_' + String.uniqueID(); this.setOptions(options); options = this.options; var id = this.id = options.id || this.instance; var container = document.id(options.container); Swiff.CallBacks[this.instance] = {}; var params = options.params, vars = options.vars, callBacks = options.callBacks; var properties = Object.append({height: options.height, width: options.width}, options.properties); var self = this; for (var callBack in callBacks){ Swiff.CallBacks[this.instance][callBack] = (function(option){ return function(){ return option.apply(self.object, arguments); }; })(callBacks[callBack]); vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack; } params.flashVars = Object.toQueryString(vars); if (Browser.ie){ properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'; params.movie = path; } else { properties.type = 'application/x-shockwave-flash'; } properties.data = path; var build = '<object id="' + id + '"'; for (var property in properties) build += ' ' + property + '="' + properties[property] + '"'; build += '>'; for (var param in params){ if (params[param]) build += '<param name="' + param + '" value="' + params[param] + '" />'; } build += '</object>'; this.object = ((container) ? container.empty() : new Element('div')).set('html', build).firstChild; }, replaces: function(element){ element = document.id(element, true); element.parentNode.replaceChild(this.toElement(), element); return this; }, inject: function(element){ document.id(element, true).appendChild(this.toElement()); return this; }, remote: function(){ return Swiff.remote.apply(Swiff, [this.toElement()].append(arguments)); } }); Swiff.CallBacks = {}; Swiff.remote = function(obj, fn){ var rs = obj.CallFunction('<invoke name="' + fn + '" returntype="javascript">' + __flash__argumentsToXML(arguments, 2) + '</invoke>'); return eval(rs); }; })();
JavaScript
/** * @package Joomla.JavaScript * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // Only define the Joomla namespace if not defined. if (typeof(Joomla) === 'undefined') { var Joomla = {}; } Joomla.Highlighter = new Class({ Implements: Options, options: { autoUnhighlight: true, caseSensitive: false, startElement: false, endElement: false, elements: new Array(), className: 'highlight', onlyWords: true, tag: 'span' }, initialize: function (options) { this.setOptions(options); this.getElements(this.options.startElement, this.options.endElement); this.words = []; }, highlight: function (words) { if (words.constructor === String) { words = [words]; } if (this.options.autoUnhighlight) { this.unhighlight(words); } var pattern = this.options.onlyWords ? '\b' + pattern + '\b' : '(' + words.join('\\b|\\b') + ')'; var regex = new RegExp(pattern, this.options.caseSensitive ? '' : 'i'); this.options.elements.each(function (el) { this.recurse(el, regex, this.options.className); }, this); return this; }, unhighlight: function (words) { if (words.constructor === String) { words = [words]; } words.each(function (word) { word = (this.options.caseSensitive ? word : word.toUpperCase()); if (this.words[word]) { var elements = $$(this.words[word]); elements.setProperty('class', ''); elements.each(function (el) { var tn = document.createTextNode(el.getText()); el.getParent().replaceChild(tn, el); }); } }, this); return this; }, recurse: function (node, regex, klass) { if (node.nodeType === 3) { var match = node.data.match(regex); if (match) { var highlight = new Element(this.options.tag); highlight.addClass(klass); var wordNode = node.splitText(match.index); wordNode.splitText(match[0].length); var wordClone = wordNode.cloneNode(true); highlight.appendChild(wordClone); wordNode.parentNode.replaceChild(highlight, wordNode); highlight.setProperty('rel', highlight.get('text')); var comparer = highlight.get('text'); if (!this.options.caseSensitive) { comparer = highlight.get('text').toUpperCase(); } if (!this.words[comparer]) { this.words[comparer] = []; } this.words[comparer].push(highlight); return 1; } } else if ((node.nodeType === 1 && node.childNodes) && !/(script|style|textarea|iframe)/i.test(node.tagName) && !(node.tagName === this.options.tag.toUpperCase() && node.className === klass)) { for (var i = 0; i < node.childNodes.length; i++) { i += this.recurse(node.childNodes[i], regex, klass); } } return 0; }, getElements: function (start, end) { var next = start.getNext(); if (next.id != end.id) { this.options.elements.include(next); this.getElements(next, end); } } });
JavaScript
/** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * JavaScript behavior to allow shift select in administrator grids */ (function() { Joomla = Joomla || {}; Joomla.JMultiSelect = new Class({ initialize : function(table) { this.table = document.id(table); if (this.table) { this.boxes = this.table.getElements('input[type=checkbox]'); this.boxes.addEvent('click', function(e){ this.doselect(e); }.bind(this)); } }, doselect: function(e) { var current = document.id(e.target); if (e.shift && typeOf(this.last) !== 'null') { var checked = current.getProperty('checked') ? 'checked' : ''; var range = [this.boxes.indexOf(current), this.boxes.indexOf(this.last)].sort(function(a, b) { //Shorthand to make sort() sort numerical instead of lexicographic return a-b; }); for (var i=range[0]; i <= range[1]; i++) { this.boxes[i].setProperty('checked', checked); } } this.last = current; } }); })();
JavaScript
/** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ Object.append(Browser.Features, { inputemail: (function() { var i = document.createElement("input"); i.setAttribute("type", "email"); return i.type !== "text"; })() }); /** * Unobtrusive Form Validation library * * Inspired by: Chris Campbell <www.particletree.com> * * @package Joomla.Framework * @subpackage Forms * @since 1.5 */ var JFormValidator = new Class({ initialize: function() { // Initialize variables this.handlers = Object(); this.custom = Object(); // Default handlers this.setHandler('username', function (value) { regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i"); return !regex.test(value); } ); this.setHandler('password', function (value) { regex=/^\S[\S ]{2,98}\S$/; return regex.test(value); } ); this.setHandler('numeric', function (value) { regex=/^(\d|-)?(\d|,)*\.?\d*$/; return regex.test(value); } ); this.setHandler('email', function (value) { regex=/^[a-zA-Z0-9._-]+(\+[a-zA-Z0-9._-]+)*@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/; return regex.test(value); } ); // Attach to forms with class 'form-validate' var forms = $$('form.form-validate'); forms.each(function(form){ this.attachToForm(form); }, this); }, setHandler: function(name, fn, en) { en = (en == '') ? true : en; this.handlers[name] = { enabled: en, exec: fn }; }, attachToForm: function(form) { // Iterate through the form object and attach the validate method to all input fields. form.getElements('input,textarea,select,button').each(function(el){ if (el.hasClass('required')) { el.set('aria-required', 'true'); el.set('required', 'required'); } if ((document.id(el).get('tag') == 'input' || document.id(el).get('tag') == 'button') && document.id(el).get('type') == 'submit') { if (el.hasClass('validate')) { el.onclick = function(){return document.formvalidator.isValid(this.form);}; } } else { el.addEvent('blur', function(){return document.formvalidator.validate(this);}); if (el.hasClass('validate-email') && Browser.Features.inputemail) { el.type = 'email'; } } }); }, validate: function(el) { el = document.id(el); // Ignore the element if its currently disabled, because are not submitted for the http-request. For those case return always true. if(el.get('disabled')) { this.handleResponse(true, el); return true; } // If the field is required make sure it has a value if (el.hasClass('required')) { if (el.get('tag')=='fieldset' && (el.hasClass('radio') || el.hasClass('checkboxes'))) { for(var i=0;;i++) { if (document.id(el.get('id')+i)) { if (document.id(el.get('id')+i).checked) { break; } } else { this.handleResponse(false, el); return false; } } } else if (!(el.get('value'))) { this.handleResponse(false, el); return false; } } // Only validate the field if the validate class is set var handler = (el.className && el.className.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? el.className.match(/validate-([a-zA-Z0-9\_\-]+)/)[1] : ""; if (handler == '') { this.handleResponse(true, el); return true; } // Check the additional validation types if ((handler) && (handler != 'none') && (this.handlers[handler]) && el.get('value')) { // Execute the validation handler and return result if (this.handlers[handler].exec(el.get('value')) != true) { this.handleResponse(false, el); return false; } } // Return validation state this.handleResponse(true, el); return true; }, isValid: function(form) { var valid = true; // Validate form fields var elements = form.getElements('fieldset').concat(Array.from(form.elements)); for (var i=0;i < elements.length; i++) { if (this.validate(elements[i]) == false) { valid = false; } } // Run custom form validators if present new Hash(this.custom).each(function(validator){ if (validator.exec() != true) { valid = false; } }); return valid; }, handleResponse: function(state, el) { // Find the label object for the given field if it exists if (!(el.labelref)) { var labels = $$('label'); labels.each(function(label){ if (label.get('for') == el.get('id')) { el.labelref = label; } }); } // Set the element and its label (if exists) invalid state if (state == false) { el.addClass('invalid'); el.set('aria-invalid', 'true'); if (el.labelref) { document.id(el.labelref).addClass('invalid'); document.id(el.labelref).set('aria-invalid', 'true'); } } else { el.removeClass('invalid'); el.set('aria-invalid', 'false'); if (el.labelref) { document.id(el.labelref).removeClass('invalid'); document.id(el.labelref).set('aria-invalid', 'false'); } } } }); document.formvalidator = null; window.addEvent('domready', function(){ document.formvalidator = new JFormValidator(); });
JavaScript
/** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * Switcher behavior * * @package Joomla * @since 1.5 */ var JSwitcher = new Class({ Implements: [Options, Events], togglers: null, elements: null, current: null, options : { onShow: function(){}, onHide: function(){}, cookieName: 'switcher', togglerSelector: 'a', elementSelector: 'div.tab', elementPrefix: 'page-' }, initialize: function(toggler, element, options) { this.setOptions(options); this.togglers = document.id(toggler).getElements(this.options.togglerSelector); this.elements = document.id(element).getElements(this.options.elementSelector); if ((this.togglers.length == 0) || (this.togglers.length != this.elements.length)) { return; } this.hideAll(); this.togglers.each(function(el) { el.addEvent('click', this.display.bind(this, el.id)); }.bind(this)); var first = [Cookie.read(this.options.cookieName), this.togglers[0].id].pick(); this.display(first); }, display: function(togglerID) { var toggler = document.id(togglerID); var element = document.id(this.options.elementPrefix+togglerID); if (toggler == null || element == null || toggler == this.current) { return this; } if (this.current != null) { this.hide(document.id(this.options.elementPrefix+this.current)); document.id(this.current).removeClass('active'); } this.show(element); toggler.addClass('active'); this.current = toggler.id; Cookie.write(this.options.cookieName, this.current); }, hide: function(element) { this.fireEvent('hide', element); element.setStyle('display', 'none'); }, hideAll: function() { this.elements.setStyle('display', 'none'); this.togglers.removeClass('active'); }, show: function (element) { this.fireEvent('show', element); element.setStyle('display', 'block'); } });
JavaScript
/* Copyright Mihai Bazon, 2002-2005 | www.bazon.net/mishoo * ----------------------------------------------------------- * * The DHTML Calendar, version 1.0 "It is happening again" * * Details and latest version at: * www.dynarch.com/projects/calendar * * This script is developed by Dynarch.com. Visit us at www.dynarch.com. * * This script is distributed under the GNU Lesser General Public License. * Read the entire license text here: http://www.gnu.org/licenses/lgpl.html */ /** The Calendar object constructor. */ Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) { // member variables this.activeDiv = null; this.currentDateEl = null; this.getDateStatus = null; this.getDateToolTip = null; this.getDateText = null; this.timeout = null; this.onSelected = onSelected || null; this.onClose = onClose || null; this.dragging = false; this.hidden = false; this.minYear = 1970; this.maxYear = 2050; this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"]; this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"]; this.isPopup = true; this.weekNumbers = true; this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD; // 0 for Sunday, 1 for Monday, etc. this.showsOtherMonths = false; this.dateStr = dateStr; this.ar_days = null; this.showsTime = false; this.time24 = true; this.yearStep = 2; this.hiliteToday = true; this.multiple = null; // HTML elements this.table = null; this.element = null; this.tbody = null; this.firstdayname = null; // Combo boxes this.monthsCombo = null; this.yearsCombo = null; this.hilitedMonth = null; this.activeMonth = null; this.hilitedYear = null; this.activeYear = null; // Information this.dateClicked = false; // one-time initializations if (typeof Calendar._SDN == "undefined") { // table of short day names if (typeof Calendar._SDN_len == "undefined") Calendar._SDN_len = 3; var ar = new Array(); for (var i = 8; i > 0;) { ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len); } Calendar._SDN = ar; // table of short month names if (typeof Calendar._SMN_len == "undefined") Calendar._SMN_len = 3; ar = new Array(); for (var i = 12; i > 0;) { ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len); } Calendar._SMN = ar; } }; // ** constants /// "static", needed for event handlers. Calendar._C = null; /// detect a special case of "web browser" Calendar.is_ie = ( /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) ); Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) ); /// detect Opera browser Calendar.is_opera = /opera/i.test(navigator.userAgent); /// detect KHTML-based browsers Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent); // BEGIN: UTILITY FUNCTIONS; beware that these might be moved into a separate // library, at some point. Calendar.getAbsolutePos = function(el) { var SL = 0, ST = 0; var is_div = /^div$/i.test(el.tagName); if (is_div && el.scrollLeft) SL = el.scrollLeft; if (is_div && el.scrollTop) ST = el.scrollTop; var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST }; if (el.offsetParent) { var tmp = this.getAbsolutePos(el.offsetParent); r.x += tmp.x; r.y += tmp.y; } return r; }; Calendar.isRelated = function (el, evt) { var related = evt.relatedTarget; if (!related) { var type = evt.type; if (type == "mouseover") { related = evt.fromElement; } else if (type == "mouseout") { related = evt.toElement; } } while (related) { if (related == el) { return true; } related = related.parentNode; } return false; }; Calendar.removeClass = function(el, className) { if (!(el && el.className)) { return; } var cls = el.className.split(" "); var ar = new Array(); for (var i = cls.length; i > 0;) { if (cls[--i] != className) { ar[ar.length] = cls[i]; } } el.className = ar.join(" "); }; Calendar.addClass = function(el, className) { Calendar.removeClass(el, className); el.className += " " + className; }; // FIXME: the following 2 functions totally suck, are useless and should be replaced immediately. Calendar.getElement = function(ev) { var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget; while (f.nodeType != 1 || /^div$/i.test(f.tagName)) f = f.parentNode; return f; }; Calendar.getTargetElement = function(ev) { var f = Calendar.is_ie ? window.event.srcElement : ev.target; while (f.nodeType != 1) f = f.parentNode; return f; }; Calendar.stopEvent = function(ev) { ev || (ev = window.event); if (Calendar.is_ie) { ev.cancelBubble = true; ev.returnValue = false; } else { ev.preventDefault(); ev.stopPropagation(); } return false; }; Calendar.addEvent = function(el, evname, func) { if (el.attachEvent) { // IE el.attachEvent("on" + evname, func); } else if (el.addEventListener) { // Gecko / W3C el.addEventListener(evname, func, true); } else { el["on" + evname] = func; } }; Calendar.removeEvent = function(el, evname, func) { if (el.detachEvent) { // IE el.detachEvent("on" + evname, func); } else if (el.removeEventListener) { // Gecko / W3C el.removeEventListener(evname, func, true); } else { el["on" + evname] = null; } }; Calendar.createElement = function(type, parent) { var el = null; if (document.createElementNS) { // use the XHTML namespace; IE won't normally get here unless // _they_ "fix" the DOM2 implementation. el = document.createElementNS("http://www.w3.org/1999/xhtml", type); } else { el = document.createElement(type); } if (typeof parent != "undefined") { parent.appendChild(el); } return el; }; // END: UTILITY FUNCTIONS // BEGIN: CALENDAR STATIC FUNCTIONS /** Internal -- adds a set of events to make some element behave like a button. */ Calendar._add_evs = function(el) { with (Calendar) { addEvent(el, "mouseover", dayMouseOver); addEvent(el, "mousedown", dayMouseDown); addEvent(el, "mouseout", dayMouseOut); if (is_ie) { addEvent(el, "dblclick", dayMouseDblClick); el.setAttribute("unselectable", true); } } }; Calendar.findMonth = function(el) { if (typeof el.month != "undefined") { return el; } else if (typeof el.parentNode.month != "undefined") { return el.parentNode; } return null; }; Calendar.findYear = function(el) { if (typeof el.year != "undefined") { return el; } else if (typeof el.parentNode.year != "undefined") { return el.parentNode; } return null; }; Calendar.showMonthsCombo = function () { var cal = Calendar._C; if (!cal) { return false; } var cal = cal; var cd = cal.activeDiv; var mc = cal.monthsCombo; if (cal.hilitedMonth) { Calendar.removeClass(cal.hilitedMonth, "hilite"); } if (cal.activeMonth) { Calendar.removeClass(cal.activeMonth, "active"); } var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()]; Calendar.addClass(mon, "active"); cal.activeMonth = mon; var s = mc.style; s.display = "block"; if (cd.navtype < 0) s.left = cd.offsetLeft + "px"; else { var mcw = mc.offsetWidth; if (typeof mcw == "undefined") // Konqueror brain-dead techniques mcw = 50; s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px"; } s.top = (cd.offsetTop + cd.offsetHeight) + "px"; }; Calendar.showYearsCombo = function (fwd) { var cal = Calendar._C; if (!cal) { return false; } var cal = cal; var cd = cal.activeDiv; var yc = cal.yearsCombo; if (cal.hilitedYear) { Calendar.removeClass(cal.hilitedYear, "hilite"); } if (cal.activeYear) { Calendar.removeClass(cal.activeYear, "active"); } cal.activeYear = null; var Y = cal.date.getFullYear() + (fwd ? 1 : -1); var yr = yc.firstChild; var show = false; for (var i = 12; i > 0; --i) { if (Y >= cal.minYear && Y <= cal.maxYear) { yr.innerHTML = Y; yr.year = Y; yr.style.display = "block"; show = true; } else { yr.style.display = "none"; } yr = yr.nextSibling; Y += fwd ? cal.yearStep : -cal.yearStep; } if (show) { var s = yc.style; s.display = "block"; if (cd.navtype < 0) s.left = cd.offsetLeft + "px"; else { var ycw = yc.offsetWidth; if (typeof ycw == "undefined") // Konqueror brain-dead techniques ycw = 50; s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px"; } s.top = (cd.offsetTop + cd.offsetHeight) + "px"; } }; // event handlers Calendar.tableMouseUp = function(ev) { var cal = Calendar._C; if (!cal) { return false; } if (cal.timeout) { clearTimeout(cal.timeout); } var el = cal.activeDiv; if (!el) { return false; } var target = Calendar.getTargetElement(ev); ev || (ev = window.event); Calendar.removeClass(el, "active"); if (target == el || target.parentNode == el) { Calendar.cellClick(el, ev); } var mon = Calendar.findMonth(target); var date = null; if (mon) { date = new Date(cal.date); if (mon.month != date.getMonth()) { date.setMonth(mon.month); cal.setDate(date); cal.dateClicked = false; cal.callHandler(); } } else { var year = Calendar.findYear(target); if (year) { date = new Date(cal.date); if (year.year != date.getFullYear()) { date.setFullYear(year.year); cal.setDate(date); cal.dateClicked = false; cal.callHandler(); } } } with (Calendar) { removeEvent(document, "mouseup", tableMouseUp); removeEvent(document, "mouseover", tableMouseOver); removeEvent(document, "mousemove", tableMouseOver); cal._hideCombos(); _C = null; return stopEvent(ev); } }; Calendar.tableMouseOver = function (ev) { var cal = Calendar._C; if (!cal) { return; } var el = cal.activeDiv; var target = Calendar.getTargetElement(ev); if (target == el || target.parentNode == el) { Calendar.addClass(el, "hilite active"); Calendar.addClass(el.parentNode, "rowhilite"); } else { if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2))) Calendar.removeClass(el, "active"); Calendar.removeClass(el, "hilite"); Calendar.removeClass(el.parentNode, "rowhilite"); } ev || (ev = window.event); if (el.navtype == 50 && target != el) { var pos = Calendar.getAbsolutePos(el); var w = el.offsetWidth; var x = ev.clientX; var dx; var decrease = true; if (x > pos.x + w) { dx = x - pos.x - w; decrease = false; } else dx = pos.x - x; if (dx < 0) dx = 0; var range = el._range; var current = el._current; var count = Math.floor(dx / 10) % range.length; for (var i = range.length; --i >= 0;) if (range[i] == current) break; while (count-- > 0) if (decrease) { if (--i < 0) i = range.length - 1; } else if ( ++i >= range.length ) i = 0; var newval = range[i]; el.innerHTML = newval; cal.onUpdateTime(); } var mon = Calendar.findMonth(target); if (mon) { if (mon.month != cal.date.getMonth()) { if (cal.hilitedMonth) { Calendar.removeClass(cal.hilitedMonth, "hilite"); } Calendar.addClass(mon, "hilite"); cal.hilitedMonth = mon; } else if (cal.hilitedMonth) { Calendar.removeClass(cal.hilitedMonth, "hilite"); } } else { if (cal.hilitedMonth) { Calendar.removeClass(cal.hilitedMonth, "hilite"); } var year = Calendar.findYear(target); if (year) { if (year.year != cal.date.getFullYear()) { if (cal.hilitedYear) { Calendar.removeClass(cal.hilitedYear, "hilite"); } Calendar.addClass(year, "hilite"); cal.hilitedYear = year; } else if (cal.hilitedYear) { Calendar.removeClass(cal.hilitedYear, "hilite"); } } else if (cal.hilitedYear) { Calendar.removeClass(cal.hilitedYear, "hilite"); } } return Calendar.stopEvent(ev); }; Calendar.tableMouseDown = function (ev) { if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) { return Calendar.stopEvent(ev); } }; Calendar.calDragIt = function (ev) { var cal = Calendar._C; if (!(cal && cal.dragging)) { return false; } var posX; var posY; if (Calendar.is_ie) { posY = window.event.clientY + document.body.scrollTop; posX = window.event.clientX + document.body.scrollLeft; } else { posX = ev.pageX; posY = ev.pageY; } cal.hideShowCovered(); var st = cal.element.style; st.left = (posX - cal.xOffs) + "px"; st.top = (posY - cal.yOffs) + "px"; return Calendar.stopEvent(ev); }; Calendar.calDragEnd = function (ev) { var cal = Calendar._C; if (!cal) { return false; } cal.dragging = false; with (Calendar) { removeEvent(document, "mousemove", calDragIt); removeEvent(document, "mouseup", calDragEnd); tableMouseUp(ev); } cal.hideShowCovered(); }; Calendar.dayMouseDown = function(ev) { var el = Calendar.getElement(ev); if (el.disabled) { return false; } var cal = el.calendar; cal.activeDiv = el; Calendar._C = cal; if (el.navtype != 300) with (Calendar) { if (el.navtype == 50) { el._current = el.innerHTML; addEvent(document, "mousemove", tableMouseOver); } else addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver); addClass(el, "hilite active"); addEvent(document, "mouseup", tableMouseUp); } else if (cal.isPopup) { cal._dragStart(ev); } if (el.navtype == -1 || el.navtype == 1) { if (cal.timeout) clearTimeout(cal.timeout); cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250); } else if (el.navtype == -2 || el.navtype == 2) { if (cal.timeout) clearTimeout(cal.timeout); cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250); } else { cal.timeout = null; } return Calendar.stopEvent(ev); }; Calendar.dayMouseDblClick = function(ev) { Calendar.cellClick(Calendar.getElement(ev), ev || window.event); if (Calendar.is_ie) { document.selection.empty(); } }; Calendar.dayMouseOver = function(ev) { var el = Calendar.getElement(ev); if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) { return false; } if (el.ttip) { if (el.ttip.substr(0, 1) == "_") { el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1); } el.calendar.tooltips.innerHTML = el.ttip; } if (el.navtype != 300) { Calendar.addClass(el, "hilite"); if (el.caldate) { Calendar.addClass(el.parentNode, "rowhilite"); var cal = el.calendar; if (cal && cal.getDateToolTip) { var d = el.caldate; window.status = d; el.title = cal.getDateToolTip(d, d.getFullYear(), d.getMonth(), d.getDate()); } } } return Calendar.stopEvent(ev); }; Calendar.dayMouseOut = function(ev) { with (Calendar) { var el = getElement(ev); if (isRelated(el, ev) || _C || el.disabled) return false; removeClass(el, "hilite"); if (el.caldate) removeClass(el.parentNode, "rowhilite"); if (el.calendar) el.calendar.tooltips.innerHTML = _TT["SEL_DATE"]; // return stopEvent(ev); } }; /** * A generic "click" handler :) handles all types of buttons defined in this * calendar. */ Calendar.cellClick = function(el, ev) { var cal = el.calendar; var closing = false; var newdate = false; var date = null; if (typeof el.navtype == "undefined") { if (cal.currentDateEl) { Calendar.removeClass(cal.currentDateEl, "selected"); Calendar.addClass(el, "selected"); closing = (cal.currentDateEl == el); if (!closing) { cal.currentDateEl = el; } } cal.date.setDateOnly(el.caldate); date = cal.date; var other_month = !(cal.dateClicked = !el.otherMonth); if (!other_month && !cal.currentDateEl && cal.multiple) cal._toggleMultipleDate(new Date(date)); else newdate = !el.disabled; // a date was clicked if (other_month) cal._init(cal.firstDayOfWeek, date); } else { if (el.navtype == 200) { Calendar.removeClass(el, "hilite"); cal.callCloseHandler(); return; } date = new Date(cal.date); if (el.navtype == 0) date.setDateOnly(new Date()); // TODAY // unless "today" was clicked, we assume no date was clicked so // the selected handler will know not to close the calenar when // in single-click mode. // cal.dateClicked = (el.navtype == 0); cal.dateClicked = false; var year = date.getFullYear(); var mon = date.getMonth(); function setMonth(m) { var day = date.getDate(); var max = date.getMonthDays(m); if (day > max) { date.setDate(max); } date.setMonth(m); }; switch (el.navtype) { case 400: Calendar.removeClass(el, "hilite"); var text = Calendar._TT["ABOUT"]; if (typeof text != "undefined") { text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : ""; } else { // FIXME: this should be removed as soon as lang files get updated! text = "Help and about box text is not translated into this language.\n" + "If you know this language and you feel generous please update\n" + "the corresponding file in \"lang\" subdir to match calendar-en.js\n" + "and send it back to <mihai_bazon@yahoo.com> to get it into the distribution ;-)\n\n" + "Thank you!\n" + "http://dynarch.com/mishoo/calendar.epl\n"; } alert(text); return; case -2: if (year > cal.minYear) { date.setFullYear(year - 1); } break; case -1: if (mon > 0) { setMonth(mon - 1); } else if (year-- > cal.minYear) { date.setFullYear(year); setMonth(11); } break; case 1: if (mon < 11) { setMonth(mon + 1); } else if (year < cal.maxYear) { date.setFullYear(year + 1); setMonth(0); } break; case 2: if (year < cal.maxYear) { date.setFullYear(year + 1); } break; case 100: cal.setFirstDayOfWeek(el.fdow); return; case 50: var range = el._range; var current = el.innerHTML; for (var i = range.length; --i >= 0;) if (range[i] == current) break; if (ev && ev.shiftKey) { if (--i < 0) i = range.length - 1; } else if ( ++i >= range.length ) i = 0; var newval = range[i]; el.innerHTML = newval; cal.onUpdateTime(); return; case 0: // TODAY will bring us here if ((typeof cal.getDateStatus == "function") && cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) { return false; } break; } if (!date.equalsTo(cal.date)) { cal.setDate(date); newdate = true; } else if (el.navtype == 0) newdate = closing = true; } if (newdate) { ev && cal.callHandler(); } if (closing) { Calendar.removeClass(el, "hilite"); ev && cal.callCloseHandler(); } }; // END: CALENDAR STATIC FUNCTIONS // BEGIN: CALENDAR OBJECT FUNCTIONS /** * This function creates the calendar inside the given parent. If _par is * null than it creates a popup calendar inside the BODY element. If _par is * an element, be it BODY, then it creates a non-popup calendar (still * hidden). Some properties need to be set before calling this function. */ Calendar.prototype.create = function (_par) { var parent = null; if (! _par) { // default parent is the document body, in which case we create // a popup calendar. parent = document.getElementsByTagName("body")[0]; this.isPopup = true; } else { parent = _par; this.isPopup = false; } this.date = this.dateStr ? new Date(this.dateStr) : new Date(); var table = Calendar.createElement("table"); this.table = table; table.cellSpacing = 0; table.cellPadding = 0; table.calendar = this; Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown); var div = Calendar.createElement("div"); this.element = div; div.className = "calendar"; if (this.isPopup) { div.style.position = "absolute"; div.style.display = "none"; } div.appendChild(table); var thead = Calendar.createElement("thead", table); var cell = null; var row = null; var cal = this; var hh = function (text, cs, navtype) { cell = Calendar.createElement("td", row); cell.colSpan = cs; cell.className = "button"; if (navtype != 0 && Math.abs(navtype) <= 2) cell.className += " nav"; Calendar._add_evs(cell); cell.calendar = cal; cell.navtype = navtype; cell.innerHTML = "<div unselectable='on'>" + text + "</div>"; return cell; }; row = Calendar.createElement("tr", thead); var title_length = 6; (this.isPopup) && --title_length; (this.weekNumbers) && ++title_length; hh("?", 1, 400).ttip = Calendar._TT["INFO"]; this.title = hh("", title_length, 300); this.title.className = "title"; if (this.isPopup) { this.title.ttip = Calendar._TT["DRAG_TO_MOVE"]; this.title.style.cursor = "move"; hh("&#x00d7;", 1, 200).ttip = Calendar._TT["CLOSE"]; } row = Calendar.createElement("tr", thead); row.className = "headrow"; this._nav_py = hh("&#x00ab;", 1, -2); this._nav_py.ttip = Calendar._TT["PREV_YEAR"]; this._nav_pm = hh("&#x2039;", 1, -1); this._nav_pm.ttip = Calendar._TT["PREV_MONTH"]; this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0); this._nav_now.ttip = Calendar._TT["GO_TODAY"]; this._nav_nm = hh("&#x203a;", 1, 1); this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"]; this._nav_ny = hh("&#x00bb;", 1, 2); this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"]; // day names row = Calendar.createElement("tr", thead); row.className = "daynames"; if (this.weekNumbers) { cell = Calendar.createElement("td", row); cell.className = "name wn"; cell.innerHTML = Calendar._TT["WK"]; } for (var i = 7; i > 0; --i) { cell = Calendar.createElement("td", row); if (!i) { cell.navtype = 100; cell.calendar = this; Calendar._add_evs(cell); } } this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild; this._displayWeekdays(); var tbody = Calendar.createElement("tbody", table); this.tbody = tbody; for (i = 6; i > 0; --i) { row = Calendar.createElement("tr", tbody); if (this.weekNumbers) { cell = Calendar.createElement("td", row); } for (var j = 7; j > 0; --j) { cell = Calendar.createElement("td", row); cell.calendar = this; Calendar._add_evs(cell); } } if (this.showsTime) { row = Calendar.createElement("tr", tbody); row.className = "time"; cell = Calendar.createElement("td", row); cell.className = "time"; cell.colSpan = 2; cell.innerHTML = Calendar._TT["TIME"] || "&#160;"; cell = Calendar.createElement("td", row); cell.className = "time"; cell.colSpan = this.weekNumbers ? 4 : 3; (function(){ function makeTimePart(className, init, range_start, range_end) { var part = Calendar.createElement("span", cell); part.className = className; part.innerHTML = init; part.calendar = cal; part.ttip = Calendar._TT["TIME_PART"]; part.navtype = 50; part._range = []; if (typeof range_start != "number") part._range = range_start; else { for (var i = range_start; i <= range_end; ++i) { var txt; if (i < 10 && range_end >= 10) txt = '0' + i; else txt = '' + i; part._range[part._range.length] = txt; } } Calendar._add_evs(part); return part; }; var hrs = cal.date.getHours(); var mins = cal.date.getMinutes(); var t12 = !cal.time24; var pm = (hrs > 12); if (t12 && pm) hrs -= 12; var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23); var span = Calendar.createElement("span", cell); span.innerHTML = ":"; span.className = "colon"; var M = makeTimePart("minute", mins, 0, 59); var AP = null; cell = Calendar.createElement("td", row); cell.className = "time"; cell.colSpan = 2; if (t12) AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]); else cell.innerHTML = "&#160;"; cal.onSetTime = function() { var pm, hrs = this.date.getHours(), mins = this.date.getMinutes(); if (t12) { pm = (hrs >= 12); if (pm) hrs -= 12; if (hrs == 0) hrs = 12; AP.innerHTML = pm ? "pm" : "am"; } H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs; M.innerHTML = (mins < 10) ? ("0" + mins) : mins; }; cal.onUpdateTime = function() { var date = this.date; var h = parseInt(H.innerHTML, 10); if (t12) { if (/pm/i.test(AP.innerHTML) && h < 12) h += 12; else if (/am/i.test(AP.innerHTML) && h == 12) h = 0; } var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); date.setHours(h); date.setMinutes(parseInt(M.innerHTML, 10)); date.setFullYear(y); date.setMonth(m); date.setDate(d); this.dateClicked = false; this.callHandler(); }; })(); } else { this.onSetTime = this.onUpdateTime = function() {}; } var tfoot = Calendar.createElement("tfoot", table); row = Calendar.createElement("tr", tfoot); row.className = "footrow"; cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300); cell.className = "ttip"; if (this.isPopup) { cell.ttip = Calendar._TT["DRAG_TO_MOVE"]; cell.style.cursor = "move"; } this.tooltips = cell; div = Calendar.createElement("div", this.element); this.monthsCombo = div; div.className = "combo"; for (i = 0; i < Calendar._MN.length; ++i) { var mn = Calendar.createElement("div"); mn.className = Calendar.is_ie ? "label-IEfix" : "label"; mn.month = i; mn.innerHTML = Calendar._SMN[i]; div.appendChild(mn); } div = Calendar.createElement("div", this.element); this.yearsCombo = div; div.className = "combo"; for (i = 12; i > 0; --i) { var yr = Calendar.createElement("div"); yr.className = Calendar.is_ie ? "label-IEfix" : "label"; div.appendChild(yr); } this._init(this.firstDayOfWeek, this.date); parent.appendChild(this.element); }; /** keyboard navigation, only for popup calendars */ Calendar._keyEvent = function(ev) { var cal = window._dynarch_popupCalendar; if (!cal || cal.multiple) return false; (Calendar.is_ie) && (ev = window.event); var act = (Calendar.is_ie || ev.type == "keypress"), K = ev.keyCode; if (ev.ctrlKey) { switch (K) { case 37: // KEY left act && Calendar.cellClick(cal._nav_pm); break; case 38: // KEY up act && Calendar.cellClick(cal._nav_py); break; case 39: // KEY right act && Calendar.cellClick(cal._nav_nm); break; case 40: // KEY down act && Calendar.cellClick(cal._nav_ny); break; default: return false; } } else switch (K) { case 32: // KEY space (now) Calendar.cellClick(cal._nav_now); break; case 27: // KEY esc act && cal.callCloseHandler(); break; case 37: // KEY left case 38: // KEY up case 39: // KEY right case 40: // KEY down if (act) { var prev, x, y, ne, el, step; prev = K == 37 || K == 38; step = (K == 37 || K == 39) ? 1 : 7; function setVars() { el = cal.currentDateEl; var p = el.pos; x = p & 15; y = p >> 4; ne = cal.ar_days[y][x]; };setVars(); function prevMonth() { var date = new Date(cal.date); date.setDate(date.getDate() - step); cal.setDate(date); }; function nextMonth() { var date = new Date(cal.date); date.setDate(date.getDate() + step); cal.setDate(date); }; while (1) { switch (K) { case 37: // KEY left if (--x >= 0) ne = cal.ar_days[y][x]; else { x = 6; K = 38; continue; } break; case 38: // KEY up if (--y >= 0) ne = cal.ar_days[y][x]; else { prevMonth(); setVars(); } break; case 39: // KEY right if (++x < 7) ne = cal.ar_days[y][x]; else { x = 0; K = 40; continue; } break; case 40: // KEY down if (++y < cal.ar_days.length) ne = cal.ar_days[y][x]; else { nextMonth(); setVars(); } break; } break; } if (ne) { if (!ne.disabled) Calendar.cellClick(ne); else if (prev) prevMonth(); else nextMonth(); } } break; case 13: // KEY enter if (act) Calendar.cellClick(cal.currentDateEl, ev); break; default: return false; } return Calendar.stopEvent(ev); }; /** * (RE)Initializes the calendar to the given date and firstDayOfWeek */ Calendar.prototype._init = function (firstDayOfWeek, date) { var today = new Date(), TY = today.getFullYear(), TM = today.getMonth(), TD = today.getDate(); this.table.style.visibility = "hidden"; var year = date.getFullYear(); if (year < this.minYear) { year = this.minYear; date.setFullYear(year); } else if (year > this.maxYear) { year = this.maxYear; date.setFullYear(year); } this.firstDayOfWeek = firstDayOfWeek; this.date = new Date(date); var month = date.getMonth(); var mday = date.getDate(); var no_days = date.getMonthDays(); // calendar voodoo for computing the first day that would actually be // displayed in the calendar, even if it's from the previous month. // WARNING: this is magic. ;-) date.setDate(1); var day1 = (date.getDay() - this.firstDayOfWeek) % 7; if (day1 < 0) day1 += 7; date.setDate(-day1); date.setDate(date.getDate() + 1); var row = this.tbody.firstChild; var MN = Calendar._SMN[month]; var ar_days = this.ar_days = new Array(); var weekend = Calendar._TT["WEEKEND"]; var dates = this.multiple ? (this.datesCells = {}) : null; for (var i = 0; i < 6; ++i, row = row.nextSibling) { var cell = row.firstChild; if (this.weekNumbers) { cell.className = "day wn"; cell.innerHTML = date.getWeekNumber(); cell = cell.nextSibling; } row.className = "daysrow"; var hasdays = false, iday, dpos = ar_days[i] = []; for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) { iday = date.getDate(); var wday = date.getDay(); cell.className = "day"; cell.pos = i << 4 | j; dpos[j] = cell; var current_month = (date.getMonth() == month); if (!current_month) { if (this.showsOtherMonths) { cell.className += " othermonth"; cell.otherMonth = true; } else { cell.className = "emptycell"; cell.innerHTML = "&#160;"; cell.disabled = true; continue; } } else { cell.otherMonth = false; hasdays = true; } cell.disabled = false; cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday; if (dates) dates[date.print("%Y%m%d")] = cell; if (this.getDateStatus) { var status = this.getDateStatus(date, year, month, iday); if (status === true) { cell.className += " disabled"; cell.disabled = true; } else { if (/disabled/i.test(status)) cell.disabled = true; cell.className += " " + status; } } if (!cell.disabled) { cell.caldate = new Date(date); cell.ttip = "_"; if (!this.multiple && current_month && iday == mday && this.hiliteToday) { cell.className += " selected"; this.currentDateEl = cell; } if (date.getFullYear() == TY && date.getMonth() == TM && iday == TD) { cell.className += " today"; cell.ttip += Calendar._TT["PART_TODAY"]; } if (weekend.indexOf(wday.toString()) != -1) cell.className += cell.otherMonth ? " oweekend" : " weekend"; } } if (!(hasdays || this.showsOtherMonths)) row.className = "emptyrow"; } this.title.innerHTML = Calendar._MN[month] + ", " + year; this.onSetTime(); this.table.style.visibility = "visible"; this._initMultipleDates(); // PROFILE // this.tooltips.innerHTML = "Generated in " + ((new Date()) - today) + " ms"; }; Calendar.prototype._initMultipleDates = function() { if (this.multiple) { for (var i in this.multiple) { var cell = this.datesCells[i]; var d = this.multiple[i]; if (!d) continue; if (cell) cell.className += " selected"; } } }; Calendar.prototype._toggleMultipleDate = function(date) { if (this.multiple) { var ds = date.print("%Y%m%d"); var cell = this.datesCells[ds]; if (cell) { var d = this.multiple[ds]; if (!d) { Calendar.addClass(cell, "selected"); this.multiple[ds] = date; } else { Calendar.removeClass(cell, "selected"); delete this.multiple[ds]; } } } }; Calendar.prototype.setDateToolTipHandler = function (unaryFunction) { this.getDateToolTip = unaryFunction; }; /** * Calls _init function above for going to a certain date (but only if the * date is different than the currently selected one). */ Calendar.prototype.setDate = function (date) { if (!date.equalsTo(this.date)) { this._init(this.firstDayOfWeek, date); } }; /** * Refreshes the calendar. Useful if the "disabledHandler" function is * dynamic, meaning that the list of disabled date can change at runtime. * Just * call this function if you think that the list of disabled dates * should * change. */ Calendar.prototype.refresh = function () { this._init(this.firstDayOfWeek, this.date); }; /** Modifies the "firstDayOfWeek" parameter (pass 0 for Synday, 1 for Monday, etc.). */ Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) { this._init(firstDayOfWeek, this.date); this._displayWeekdays(); }; /** * Allows customization of what dates are enabled. The "unaryFunction" * parameter must be a function object that receives the date (as a JS Date * object) and returns a boolean value. If the returned value is true then * the passed date will be marked as disabled. */ Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) { this.getDateStatus = unaryFunction; }; /** Customization of allowed year range for the calendar. */ Calendar.prototype.setRange = function (a, z) { this.minYear = a; this.maxYear = z; }; /** Calls the first user handler (selectedHandler). */ Calendar.prototype.callHandler = function () { if (this.onSelected) { this.onSelected(this, this.date.print(this.dateFormat)); } }; /** Calls the second user handler (closeHandler). */ Calendar.prototype.callCloseHandler = function () { if (this.onClose) { this.onClose(this); } this.hideShowCovered(); }; /** Removes the calendar object from the DOM tree and destroys it. */ Calendar.prototype.destroy = function () { var el = this.element.parentNode; el.removeChild(this.element); Calendar._C = null; window._dynarch_popupCalendar = null; }; /** * Moves the calendar element to a different section in the DOM tree (changes * its parent). */ Calendar.prototype.reparent = function (new_parent) { var el = this.element; el.parentNode.removeChild(el); new_parent.appendChild(el); }; // This gets called when the user presses a mouse button anywhere in the // document, if the calendar is shown. If the click was outside the open // calendar this function closes it. Calendar._checkCalendar = function(ev) { var calendar = window._dynarch_popupCalendar; if (!calendar) { return false; } var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev); for (; el != null && el != calendar.element; el = el.parentNode); if (el == null) { // calls closeHandler which should hide the calendar. window._dynarch_popupCalendar.callCloseHandler(); return Calendar.stopEvent(ev); } }; /** Shows the calendar. */ Calendar.prototype.show = function () { var rows = this.table.getElementsByTagName("tr"); for (var i = rows.length; i > 0;) { var row = rows[--i]; Calendar.removeClass(row, "rowhilite"); var cells = row.getElementsByTagName("td"); for (var j = cells.length; j > 0;) { var cell = cells[--j]; Calendar.removeClass(cell, "hilite"); Calendar.removeClass(cell, "active"); } } this.element.style.display = "block"; this.hidden = false; if (this.isPopup) { window._dynarch_popupCalendar = this; Calendar.addEvent(document, "keydown", Calendar._keyEvent); Calendar.addEvent(document, "keypress", Calendar._keyEvent); Calendar.addEvent(document, "mousedown", Calendar._checkCalendar); } this.hideShowCovered(); }; /** * Hides the calendar. Also removes any "hilite" from the class of any TD * element. */ Calendar.prototype.hide = function () { if (this.isPopup) { Calendar.removeEvent(document, "keydown", Calendar._keyEvent); Calendar.removeEvent(document, "keypress", Calendar._keyEvent); Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar); } this.element.style.display = "none"; this.hidden = true; this.hideShowCovered(); }; /** * Shows the calendar at a given absolute position (beware that, depending on * the calendar element style -- position property -- this might be relative * to the parent's containing rectangle). */ Calendar.prototype.showAt = function (x, y) { var s = this.element.style; s.left = x + "px"; s.top = y + "px"; this.show(); }; /** Shows the calendar near a given element. */ Calendar.prototype.showAtElement = function (el, opts) { var self = this; var p = Calendar.getAbsolutePos(el); if (!opts || typeof opts != "string") { this.showAt(p.x, p.y + el.offsetHeight); return true; } function fixPosition(box) { if (box.x < 0) box.x = 0; if (box.y < 0) box.y = 0; var cp = document.createElement("div"); var s = cp.style; s.position = "absolute"; s.right = s.bottom = s.width = s.height = "0px"; document.body.appendChild(cp); var br = Calendar.getAbsolutePos(cp); document.body.removeChild(cp); if (Calendar.is_ie) { br.y += document.body.scrollTop; br.x += document.body.scrollLeft; } else { br.y += window.scrollY; br.x += window.scrollX; } var tmp = box.x + box.width - br.x; if (tmp > 0) box.x -= tmp; tmp = box.y + box.height - br.y; if (tmp > 0) box.y -= tmp; }; this.element.style.display = "block"; Calendar.continuation_for_the_khtml_browser = function() { var w = self.element.offsetWidth; var h = self.element.offsetHeight; self.element.style.display = "none"; var valign = opts.substr(0, 1); var halign = "l"; if (opts.length > 1) { halign = opts.substr(1, 1); } // vertical alignment switch (valign) { case "T": p.y -= h; break; case "B": p.y += el.offsetHeight; break; case "C": p.y += (el.offsetHeight - h) / 2; break; case "t": p.y += el.offsetHeight - h; break; case "b": break; // already there } // horizontal alignment switch (halign) { case "L": p.x -= w; break; case "R": p.x += el.offsetWidth; break; case "C": p.x += (el.offsetWidth - w) / 2; break; case "l": p.x += el.offsetWidth - w; break; case "r": break; // already there } p.width = w; p.height = h + 40; self.monthsCombo.style.display = "none"; fixPosition(p); self.showAt(p.x, p.y); }; if (Calendar.is_khtml) setTimeout("Calendar.continuation_for_the_khtml_browser()", 10); else Calendar.continuation_for_the_khtml_browser(); }; /** Customizes the date format. */ Calendar.prototype.setDateFormat = function (str) { this.dateFormat = str; }; /** Customizes the tooltip date format. */ Calendar.prototype.setTtDateFormat = function (str) { this.ttDateFormat = str; }; /** * Tries to identify the date represented in a string. If successful it also * calls this.setDate which moves the calendar to the given date. */ Calendar.prototype.parseDate = function(str, fmt) { if (!fmt) fmt = this.dateFormat; this.setDate(Date.parseDate(str, fmt)); }; Calendar.prototype.hideShowCovered = function () { if (!Calendar.is_ie && !Calendar.is_opera) return; function getVisib(obj){ var value = obj.style.visibility; if (!value) { if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C if (!Calendar.is_khtml) value = document.defaultView. getComputedStyle(obj, "").getPropertyValue("visibility"); else value = ''; } else if (obj.currentStyle) { // IE value = obj.currentStyle.visibility; } else value = ''; } return value; }; var tags = new Array("applet", "iframe", "select"); var el = this.element; var p = Calendar.getAbsolutePos(el); var EX1 = p.x; var EX2 = el.offsetWidth + EX1; var EY1 = p.y; var EY2 = el.offsetHeight + EY1; for (var k = tags.length; k > 0; ) { var ar = document.getElementsByTagName(tags[--k]); var cc = null; for (var i = ar.length; i > 0;) { cc = ar[--i]; p = Calendar.getAbsolutePos(cc); var CX1 = p.x; var CX2 = cc.offsetWidth + CX1; var CY1 = p.y; var CY2 = cc.offsetHeight + CY1; if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) { if (!cc.__msh_save_visibility) { cc.__msh_save_visibility = getVisib(cc); } cc.style.visibility = cc.__msh_save_visibility; } else { if (!cc.__msh_save_visibility) { cc.__msh_save_visibility = getVisib(cc); } cc.style.visibility = "hidden"; } } } }; /** Internal function; it displays the bar with the names of the weekday. */ Calendar.prototype._displayWeekdays = function () { var fdow = this.firstDayOfWeek; var cell = this.firstdayname; var weekend = Calendar._TT["WEEKEND"]; for (var i = 0; i < 7; ++i) { cell.className = "day name"; var realday = (i + fdow) % 7; if (i) { cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]); cell.navtype = 100; cell.calendar = this; cell.fdow = realday; Calendar._add_evs(cell); } if (weekend.indexOf(realday.toString()) != -1) { Calendar.addClass(cell, "weekend"); } cell.innerHTML = Calendar._SDN[(i + fdow) % 7]; cell = cell.nextSibling; } }; /** Internal function. Hides all combo boxes that might be displayed. */ Calendar.prototype._hideCombos = function () { this.monthsCombo.style.display = "none"; this.yearsCombo.style.display = "none"; }; /** Internal function. Starts dragging the element. */ Calendar.prototype._dragStart = function (ev) { if (this.dragging) { return; } this.dragging = true; var posX; var posY; if (Calendar.is_ie) { posY = window.event.clientY + document.body.scrollTop; posX = window.event.clientX + document.body.scrollLeft; } else { posY = ev.clientY + window.scrollY; posX = ev.clientX + window.scrollX; } var st = this.element.style; this.xOffs = posX - parseInt(st.left); this.yOffs = posY - parseInt(st.top); with (Calendar) { addEvent(document, "mousemove", calDragIt); addEvent(document, "mouseup", calDragEnd); } }; // BEGIN: DATE OBJECT PATCHES /** Adds the number of days array to the Date object. */ Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31); /** Constants used for time computations */ Date.SECOND = 1000 /* milliseconds */; Date.MINUTE = 60 * Date.SECOND; Date.HOUR = 60 * Date.MINUTE; Date.DAY = 24 * Date.HOUR; Date.WEEK = 7 * Date.DAY; Date.parseDate = function(str, fmt) { var today = new Date(); var y = 0; var m = -1; var d = 0; var a = str.split(/\W+/); var b = fmt.match(/%./g); var i = 0, j = 0; var hr = 0; var min = 0; for (i = 0; i < a.length; ++i) { if (!a[i]) continue; switch (b[i]) { case "%d": case "%e": d = parseInt(a[i], 10); break; case "%m": m = parseInt(a[i], 10) - 1; break; case "%Y": case "%y": y = parseInt(a[i], 10); (y < 100) && (y += (y > 29) ? 1900 : 2000); break; case "%b": case "%B": for (j = 0; j < 12; ++j) { if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; } } break; case "%H": case "%I": case "%k": case "%l": hr = parseInt(a[i], 10); break; case "%P": case "%p": if (/pm/i.test(a[i]) && hr < 12) hr += 12; else if (/am/i.test(a[i]) && hr >= 12) hr -= 12; break; case "%M": min = parseInt(a[i], 10); break; } } if (isNaN(y)) y = today.getFullYear(); if (isNaN(m)) m = today.getMonth(); if (isNaN(d)) d = today.getDate(); if (isNaN(hr)) hr = today.getHours(); if (isNaN(min)) min = today.getMinutes(); if (y != 0 && m != -1 && d != 0) return new Date(y, m, d, hr, min, 0); y = 0; m = -1; d = 0; for (i = 0; i < a.length; ++i) { if (a[i].search(/[a-zA-Z]+/) != -1) { var t = -1; for (j = 0; j < 12; ++j) { if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; } } if (t != -1) { if (m != -1) { d = m+1; } m = t; } } else if (parseInt(a[i], 10) <= 12 && m == -1) { m = a[i]-1; } else if (parseInt(a[i], 10) > 31 && y == 0) { y = parseInt(a[i], 10); (y < 100) && (y += (y > 29) ? 1900 : 2000); } else if (d == 0) { d = a[i]; } } if (y == 0) y = today.getFullYear(); if (m != -1 && d != 0) return new Date(y, m, d, hr, min, 0); return today; }; /** Returns the number of days in the current month */ Date.prototype.getMonthDays = function(month) { var year = this.getFullYear(); if (typeof month == "undefined") { month = this.getMonth(); } if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) { return 29; } else { return Date._MD[month]; } }; /** Returns the number of day in the year. */ Date.prototype.getDayOfYear = function() { var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0); var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0); var time = now - then; return Math.floor(time / Date.DAY); }; /** Returns the number of the week in year, as defined in ISO 8601. */ Date.prototype.getWeekNumber = function() { var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0); var DoW = d.getDay(); d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu var ms = d.valueOf(); // GMT d.setMonth(0); d.setDate(4); // Thu in Week 1 return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1; }; /** Checks date and time equality */ Date.prototype.equalsTo = function(date) { return ((this.getFullYear() == date.getFullYear()) && (this.getMonth() == date.getMonth()) && (this.getDate() == date.getDate()) && (this.getHours() == date.getHours()) && (this.getMinutes() == date.getMinutes())); }; /** Set only the year, month, date parts (keep existing time) */ Date.prototype.setDateOnly = function(date) { var tmp = new Date(date); this.setDate(1); this.setFullYear(tmp.getFullYear()); this.setMonth(tmp.getMonth()); this.setDate(tmp.getDate()); }; /** Prints the date in a string according to the given format. */ Date.prototype.print = function (str) { var m = this.getMonth(); var d = this.getDate(); var y = this.getFullYear(); var wn = this.getWeekNumber(); var w = this.getDay(); var s = {}; var hr = this.getHours(); var pm = (hr >= 12); var ir = (pm) ? (hr - 12) : hr; var dy = this.getDayOfYear(); if (ir == 0) ir = 12; var min = this.getMinutes(); var sec = this.getSeconds(); s["%a"] = Calendar._SDN[w]; // abbreviated weekday name [FIXME: I18N] s["%A"] = Calendar._DN[w]; // full weekday name s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N] s["%B"] = Calendar._MN[m]; // full month name // FIXME: %c : preferred date and time representation for the current locale s["%C"] = 1 + Math.floor(y / 100); // the century number s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31) s["%e"] = d; // the day of the month (range 1 to 31) // FIXME: %D : american date style: %m/%d/%y // FIXME: %E, %F, %G, %g, %h (man strftime) s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format) s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format) s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366) s["%k"] = hr; // hour, range 0 to 23 (24h format) s["%l"] = ir; // hour, range 1 to 12 (12h format) s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12 s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59 s["%n"] = "\n"; // a newline character s["%p"] = pm ? "PM" : "AM"; s["%P"] = pm ? "pm" : "am"; // FIXME: %r : the time in am/pm notation %I:%M:%S %p // FIXME: %R : the time in 24-hour notation %H:%M s["%s"] = Math.floor(this.getTime() / 1000); s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59 s["%t"] = "\t"; // a tab character // FIXME: %T : the time in 24-hour notation (%H:%M:%S) s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn; s["%u"] = w + 1; // the day of the week (range 1 to 7, 1 = MON) s["%w"] = w; // the day of the week (range 0 to 6, 0 = SUN) // FIXME: %x : preferred date representation for the current locale without the time // FIXME: %X : preferred time representation for the current locale without the date s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99) s["%Y"] = y; // year with the century s["%%"] = "%"; // a literal '%' character var re = /%./g; if (!Calendar.is_ie5 && !Calendar.is_khtml) return str.replace(re, function (par) { return s[par] || par; }); var a = str.match(re); for (var i = 0; i < a.length; i++) { var tmp = s[a[i]]; if (tmp) { re = new RegExp(a[i], 'g'); str = str.replace(re, tmp); } } return str; }; Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear; Date.prototype.setFullYear = function(y) { var d = new Date(this); d.__msh_oldSetFullYear(y); if (d.getMonth() != this.getMonth()) this.setDate(28); this.__msh_oldSetFullYear(y); }; // END: DATE OBJECT PATCHES // global object that remembers the calendar window._dynarch_popupCalendar = null;
JavaScript
/* Copyright Mihai Bazon, 2002, 2003 | http://dynarch.com/mishoo/ * --------------------------------------------------------------------------- * * The DHTML Calendar * * Details and latest version at: * http://dynarch.com/mishoo/calendar.epl * * This script is distributed under the GNU Lesser General Public License. * Read the entire license text here: http://www.gnu.org/licenses/lgpl.html * * This file defines helper functions for setting up the calendar. They are * intended to help non-programmers get a working calendar on their site * quickly. This script should not be seen as part of the calendar. It just * shows you what one can do with the calendar, while in the same time * providing a quick and simple method for setting it up. If you need * exhaustive customization of the calendar creation process feel free to * modify this code to suit your needs (this is recommended and much better * than modifying calendar.js itself). */ /** * This function "patches" an input field (or other element) to use a calendar * widget for date selection. * * The "params" is a single object that can have the following properties: * * prop. name | description * ------------------------------------------------------------------------------------------------- * inputField | the ID of an input field to store the date * displayArea | the ID of a DIV or other element to show the date * button | ID of a button or other element that will trigger the calendar * eventName | event that will trigger the calendar, without the "on" prefix (default: "click") * ifFormat | date format that will be stored in the input field * daFormat | the date format that will be used to display the date in displayArea * singleClick | (true/false) wether the calendar is in single click mode or not (default: true) * firstDay | numeric: 0 to 6. "0" means display Sunday first, "1" means display Monday first, etc. * align | alignment (default: "Br"); if you don't know what's this see the calendar documentation * range | array with 2 elements. Default: [1900, 2999] -- the range of years available * weekNumbers | (true/false) if it's true (default) the calendar will display week numbers * flat | null or element ID; if not null the calendar will be a flat calendar having the parent with the given ID * flatCallback | function that receives a JS Date object and returns an URL to point the browser to (for flat calendar) * disableFunc | function that receives a JS Date object and should return true if that date has to be disabled in the calendar * onSelect | function that gets called when a date is selected. You don't _have_ to supply this (the default is generally okay) * onClose | function that gets called when the calendar is closed. [default] * onUpdate | function that gets called after the date is updated in the input field. Receives a reference to the calendar. * date | the date that the calendar will be initially displayed to * showsTime | default: false; if true the calendar will include a time selector * timeFormat | the time format; can be "12" or "24", default is "12" * electric | if true (default) then given fields/date areas are updated for each move; otherwise they're updated only on close * step | configures the step of the years in drop-down boxes; default: 2 * position | configures the calendar absolute position; default: null * cache | if "true" (but default: "false") it will reuse the same calendar object, where possible * showOthers | if "true" (but default: "false") it will show days from other months too * * None of them is required, they all have default values. However, if you * pass none of "inputField", "displayArea" or "button" you'll get a warning * saying "nothing to setup". */ Calendar.setup = function (params) { function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } }; param_default("inputField", null); param_default("displayArea", null); param_default("button", null); param_default("eventName", "click"); param_default("ifFormat", "%Y/%m/%d"); param_default("daFormat", "%Y/%m/%d"); param_default("singleClick", true); param_default("disableFunc", null); param_default("dateStatusFunc", params["disableFunc"]); // takes precedence if both are defined param_default("dateTooltipFunc", null); param_default("dateText", null); param_default("firstDay", null); param_default("align", "Br"); param_default("range", [1900, 2999]); param_default("weekNumbers", true); param_default("flat", null); param_default("flatCallback", null); param_default("onSelect", null); param_default("onClose", null); param_default("onUpdate", null); param_default("date", null); param_default("showsTime", false); param_default("timeFormat", "24"); param_default("electric", true); param_default("step", 2); param_default("position", null); param_default("cache", false); param_default("showOthers", false); param_default("multiple", null); var tmp = ["inputField", "displayArea", "button"]; for (var i in tmp) { if (typeof params[tmp[i]] == "string") { params[tmp[i]] = document.getElementById(params[tmp[i]]); } } if (!(params.flat || params.multiple || params.inputField || params.displayArea || params.button)) { alert("Calendar.setup:\n Nothing to setup (no fields found). Please check your code"); return false; } function onSelect(cal) { var p = cal.params; var update = (cal.dateClicked || p.electric); if (update && p.inputField) { p.inputField.value = cal.date.print(p.ifFormat); if (typeof p.inputField.onchange == "function") p.inputField.onchange(); } if (update && p.displayArea) p.displayArea.innerHTML = cal.date.print(p.daFormat); if (update && typeof p.onUpdate == "function") p.onUpdate(cal); if (update && p.flat) { if (typeof p.flatCallback == "function") p.flatCallback(cal); } if (update && p.singleClick && cal.dateClicked) cal.callCloseHandler(); }; if (params.flat != null) { if (typeof params.flat == "string") params.flat = document.getElementById(params.flat); if (!params.flat) { alert("Calendar.setup:\n Flat specified but can't find parent."); return false; } var cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect); cal.setDateToolTipHandler(params.dateTooltipFunc); cal.showsOtherMonths = params.showOthers; cal.showsTime = params.showsTime; cal.time24 = (params.timeFormat == "24"); cal.params = params; cal.weekNumbers = params.weekNumbers; cal.setRange(params.range[0], params.range[1]); cal.setDateStatusHandler(params.dateStatusFunc); cal.getDateText = params.dateText; if (params.ifFormat) { cal.setDateFormat(params.ifFormat); } if (params.inputField && typeof params.inputField.value == "string") { cal.parseDate(params.inputField.value); } cal.create(params.flat); cal.show(); return false; } var triggerEl = params.button || params.displayArea || params.inputField; triggerEl["on" + params.eventName] = function() { var dateEl = params.inputField || params.displayArea; var dateFmt = params.inputField ? params.ifFormat : params.daFormat; var mustCreate = false; var cal = window.calendar; if (dateEl) params.date = Date.parseDate(dateEl.value || dateEl.innerHTML, dateFmt); if (!(cal && params.cache)) { window.calendar = cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect, params.onClose || function(cal) { cal.hide(); }); cal.setDateToolTipHandler(params.dateTooltipFunc); cal.showsTime = params.showsTime; cal.time24 = (params.timeFormat == "24"); cal.weekNumbers = params.weekNumbers; mustCreate = true; } else { if (params.date) cal.setDate(params.date); cal.hide(); } if (params.multiple) { cal.multiple = {}; for (var i = params.multiple.length; --i >= 0;) { var d = params.multiple[i]; var ds = d.print("%Y%m%d"); cal.multiple[ds] = d; } } cal.showsOtherMonths = params.showOthers; cal.yearStep = params.step; cal.setRange(params.range[0], params.range[1]); cal.params = params; cal.setDateStatusHandler(params.dateStatusFunc); cal.getDateText = params.dateText; cal.setDateFormat(dateFmt); if (mustCreate) cal.create(); cal.refresh(); if (!params.position) cal.showAtElement(params.button || params.displayArea || params.inputField, params.align); else cal.showAt(params.position[0], params.position[1]); return false; }; return cal; };
JavaScript
/** * Swiff.Uploader - Flash FileReference Control * * @version 3.0 * * @license MIT License * * @author Harald Kirschner <http://digitarald.de> * @author Valerio Proietti, <http://mad4milk.net> * @copyright Authors */ Swiff.Uploader = new Class({ Extends: Swiff, Implements: Events, options: { path: 'Swiff.Uploader.swf', target: null, zIndex: 9999, callBacks: null, params: { wMode: 'opaque', menu: 'false', allowScriptAccess: 'always' }, typeFilter: null, multiple: true, queued: true, verbose: false, height: 30, width: 100, passStatus: null, url: null, method: null, data: null, mergeData: true, fieldName: null, fileSizeMin: 1, fileSizeMax: null, // Official limit is 100 MB for FileReference, but I tested up to 2Gb! allowDuplicates: false, timeLimit: (Browser.Platform.linux) ? 0 : 30, policyFile: null, buttonImage: null, fileListMax: 0, fileListSizeMax: 0, instantStart: false, appendCookieData: false, fileClass: null /* onLoad: $empty, onFail: $empty, onStart: $empty, onQueue: $empty, onComplete: $empty, onBrowse: $empty, onDisabledBrowse: $empty, onCancel: $empty, onSelect: $empty, onSelectSuccess: $empty, onSelectFail: $empty, onButtonEnter: $empty, onButtonLeave: $empty, onButtonDown: $empty, onButtonDisable: $empty, onFileStart: $empty, onFileStop: $empty, onFileRequeue: $empty, onFileOpen: $empty, onFileProgress: $empty, onFileComplete: $empty, onFileRemove: $empty, onBeforeStart: $empty, onBeforeStop: $empty, onBeforeRemove: $empty */ }, initialize: function(options) { // protected events to control the class, added // before setting options (which adds own events) this.addEvent('load', this.initializeSwiff, true) .addEvent('select', this.processFiles, true) .addEvent('complete', this.update, true) .addEvent('fileRemove', function(file) { this.fileList.erase(file); }.bind(this), true); this.setOptions(options); // callbacks are no longer in the options, every callback // is fired as event, this is just compat if (this.options.callBacks) { Hash.each(this.options.callBacks, function(fn, name) { this.addEvent(name, fn); }, this); } this.options.callBacks = { fireCallback: this.fireCallback.bind(this) }; var path = this.options.path; if (!path.contains('?')) path += '?noCache=' + Date.now; // cache in IE // container options for Swiff class this.options.container = this.box = new Element('span', {'class': 'swiff-uploader-box'}).inject(document.id(this.options.container) || document.body); // target this.target = document.id(this.options.target); if (this.target) { var scroll = window.getScroll(); this.box.setStyles({ position: 'absolute', visibility: 'visible', zIndex: this.options.zIndex, overflow: 'hidden', height: 1, width: 1, top: scroll.y, left: scroll.x }); // we force wMode to transparent for the overlay effect this.parent(path, { params: { wMode: 'transparent' }, height: '100%', width: '100%' }); this.target.addEvent('mouseenter', this.reposition.bind(this, [])); // button interactions, relayed to to the target this.addEvents({ buttonEnter: this.targetRelay.bind(this, ['mouseenter']), buttonLeave: this.targetRelay.bind(this, ['mouseleave']), buttonDown: this.targetRelay.bind(this, ['mousedown']), buttonDisable: this.targetRelay.bind(this, ['disable']) }); this.reposition(); window.addEvent('resize', this.reposition.bind(this, [])); } else { this.parent(path); } this.inject(this.box); this.fileList = []; this.size = this.uploading = this.bytesLoaded = this.percentLoaded = 0; if (Browser.Plugins.Flash.version < 9) { this.fireEvent('fail', ['flash']); } else { this.verifyLoad.delay(1000, this); } }, verifyLoad: function() { if (this.loaded) return; if (!this.object.parentNode) { this.fireEvent('fail', ['disabled']); } else if (this.object.style.display == 'none') { this.fireEvent('fail', ['hidden']); } else if (!this.object.offsetWidth) { this.fireEvent('fail', ['empty']); } }, fireCallback: function(name, args) { // file* callbacks are relayed to the specific file if (name.substr(0, 4) == 'file') { // updated queue data is the second argument if (args.length > 1) this.update(args[1]); var data = args[0]; var file = this.findFile(data.id); this.fireEvent(name, file || data, 5); if (file) { var fire = name.replace(/^file([A-Z])/, function($0, $1) { return $1.toLowerCase(); }); file.update(data).fireEvent(fire, [data], 10); } } else { this.fireEvent(name, args, 5); } }, update: function(data) { // the data is saved right to the instance Object.append(this, data); this.fireEvent('queue', [this], 10); return this; }, findFile: function(id) { for (var i = 0; i < this.fileList.length; i++) { if (this.fileList[i].id == id) return this.fileList[i]; } return null; }, initializeSwiff: function() { // extracted options for the swf this.remote('xInitialize', { typeFilter: this.options.typeFilter, multiple: this.options.multiple, queued: this.options.queued, verbose: this.options.verbose, width: this.options.width, height: this.options.height, passStatus: this.options.passStatus, url: this.options.url, method: this.options.method, data: this.options.data, mergeData: this.options.mergeData, fieldName: this.options.fieldName, fileSizeMin: this.options.fileSizeMin, fileSizeMax: this.options.fileSizeMax, allowDuplicates: this.options.allowDuplicates, timeLimit: this.options.timeLimit, policyFile: this.options.policyFile, buttonImage: this.options.buttonImage }); this.loaded = true; this.appendCookieData(); }, targetRelay: function(name) { if (this.target) this.target.fireEvent(name); }, reposition: function(coords) { // update coordinates, manual or automatically coords = coords || (this.target && this.target.offsetHeight) ? this.target.getCoordinates(this.box.getOffsetParent()) : {top: window.getScrollTop(), left: 0, width: 40, height: 40} this.box.setStyles(coords); this.fireEvent('reposition', [coords, this.box, this.target]); }, setOptions: function(options) { if (options) { if (options.url) options.url = Swiff.Uploader.qualifyPath(options.url); if (options.buttonImage) options.buttonImage = Swiff.Uploader.qualifyPath(options.buttonImage); this.parent(options); if (this.loaded) this.remote('xSetOptions', options); } return this; }, setEnabled: function(status) { this.remote('xSetEnabled', status); }, start: function() { this.fireEvent('beforeStart'); this.remote('xStart'); }, stop: function() { this.fireEvent('beforeStop'); this.remote('xStop'); }, remove: function() { this.fireEvent('beforeRemove'); this.remote('xRemove'); }, fileStart: function(file) { this.remote('xFileStart', file.id); }, fileStop: function(file) { this.remote('xFileStop', file.id); }, fileRemove: function(file) { this.remote('xFileRemove', file.id); }, fileRequeue: function(file) { this.remote('xFileRequeue', file.id); }, appendCookieData: function() { var append = this.options.appendCookieData; if (!append) return; var hash = {}; document.cookie.split(/;\s*/).each(function(cookie) { cookie = cookie.split('='); if (cookie.length == 2) { hash[decodeURIComponent(cookie[0])] = decodeURIComponent(cookie[1]); } }); var data = this.options.data || {}; if ($type(append) == 'string') data[append] = hash; else Object.append(data, hash); this.setOptions({data: data}); }, processFiles: function(successraw, failraw, queue) { var cls = this.options.fileClass || Swiff.Uploader.File; var fail = [], success = []; if (successraw) { successraw.each(function(data) { var ret = new cls(this, data); if (!ret.validate()) { ret.remove.delay(10, ret); fail.push(ret); } else { this.size += data.size; this.fileList.push(ret); success.push(ret); ret.render(); } }, this); this.fireEvent('selectSuccess', [success], 10); } if (failraw || fail.length) { fail.extend((failraw) ? failraw.map(function(data) { return new cls(this, data); }, this) : []).each(function(file) { file.invalidate().render(); }); this.fireEvent('selectFail', [fail], 10); } this.update(queue); if (this.options.instantStart && success.length) this.start(); } }); Object.append(Swiff.Uploader, { STATUS_QUEUED: 0, STATUS_RUNNING: 1, STATUS_ERROR: 2, STATUS_COMPLETE: 3, STATUS_STOPPED: 4, log: function() { if (window.console && console.info) console.info.apply(console, arguments); }, unitLabels: { b: [{min: 1, unit: 'B'}, {min: 1024, unit: 'kB'}, {min: 1048576, unit: 'MB'}, {min: 1073741824, unit: 'GB'}], s: [{min: 1, unit: 's'}, {min: 60, unit: 'm'}, {min: 3600, unit: 'h'}, {min: 86400, unit: 'd'}] }, formatUnit: function(base, type, join) { var labels = Swiff.Uploader.unitLabels[(type == 'bps') ? 'b' : type]; var append = (type == 'bps') ? '/s' : ''; var i, l = labels.length, value; if (base < 1) return '0 ' + labels[0].unit + append; if (type == 's') { var units = []; for (i = l - 1; i >= 0; i--) { value = Math.floor(base / labels[i].min); if (value) { units.push(value + ' ' + labels[i].unit); base -= value * labels[i].min; if (!base) break; } } return (join === false) ? units : units.join(join || ', '); } for (i = l - 1; i >= 0; i--) { value = labels[i].min; if (base >= value) break; } return (base / value).toFixed(1) + ' ' + labels[i].unit + append; } }); Swiff.Uploader.qualifyPath = (function() { var anchor; return function(path) { (anchor || (anchor = new Element('a'))).href = path; return anchor.href; }; })(); Swiff.Uploader.File = new Class({ Implements: Events, initialize: function(base, data) { this.base = base; this.update(data); }, update: function(data) { return Object.append(this, data); }, validate: function() { var options = this.base.options; if (options.fileListMax && this.base.fileList.length >= options.fileListMax) { this.validationError = 'fileListMax'; return false; } if (options.fileListSizeMax && (this.base.size + this.size) > options.fileListSizeMax) { this.validationError = 'fileListSizeMax'; return false; } return true; }, invalidate: function() { this.invalid = true; this.base.fireEvent('fileInvalid', this, 10); return this.fireEvent('invalid', this, 10); }, render: function() { return this; }, setOptions: function(options) { if (options) { if (options.url) options.url = Swiff.Uploader.qualifyPath(options.url); this.base.remote('xFileSetOptions', this.id, options); this.options = $merge(this.options, options); } return this; }, start: function() { this.base.fileStart(this); return this; }, stop: function() { this.base.fileStop(this); return this; }, remove: function() { this.base.fileRemove(this); return this; }, requeue: function() { this.base.fileRequeue(this); } });
JavaScript
/** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * JCaption javascript behavior * * Used for displaying image captions * * @package Joomla * @since 1.5 * @version 1.0 */ var JCaption = new Class({ initialize: function(selector) { this.selector = selector; var images = $$(selector); images.each(function(image){ this.createCaption(image); }, this); }, createCaption: function(element) { var caption = document.createTextNode(element.title); var container = document.createElement("div"); var text = document.createElement("p"); var width = element.getAttribute("width"); var align = element.getAttribute("align"); if(!width) { width = element.width; } //Windows fix if (!align) align = element.getStyle("float"); // Rest of the world fix if (!align) // IE DOM Fix align = element.style.styleFloat; if (align=="" || !align) { align="none"; } text.appendChild(caption); text.className = this.selector.replace('.', '_'); element.parentNode.insertBefore(container, element); container.appendChild(element); if (element.title != "") { container.appendChild(text); } container.className = this.selector.replace('.', '_'); container.className = container.className + " " + align; container.setAttribute("style","float:"+align); container.style.width = width + "px"; } });
JavaScript
/** * FancyUpload - Flash meets Ajax for powerful and elegant uploads. * * Updated to latest 3.0 API. Hopefully 100% compat! * * @version 3.0 * * @license MIT License * * @author Harald Kirschner <http://digitarald.de> * @copyright Authors */ var FancyUpload2 = new Class({ Extends: Swiff.Uploader, options: { queued: 1, // compat limitSize: 0, limitFiles: 0, validateFile: Function.from(true) }, initialize: function(status, list, options) { this.status = document.id(status); this.list = document.id(list); // compat options.fileClass = options.fileClass || FancyUpload2.File; options.fileSizeMax = options.limitSize || options.fileSizeMax; options.fileListMax = options.limitFiles || options.fileListMax; options.url = options.url + '&format=json'; this.parent(options); this.addEvents({ 'load': this.render, 'select': this.onSelect, 'cancel': this.onCancel, 'start': this.onStart, 'queue': this.onQueue, 'complete': this.onComplete }); }, render: function() { this.overallTitle = this.status.getElement('.overall-title'); this.currentTitle = this.status.getElement('.current-title'); this.currentText = this.status.getElement('.current-text'); var progress = this.status.getElement('.overall-progress'); this.overallProgress = new Fx.ProgressBar(progress, { text: new Element('span', {'class': 'progress-text'}).inject(progress, 'after') }); progress = this.status.getElement('.current-progress') this.currentProgress = new Fx.ProgressBar(progress, { text: new Element('span', {'class': 'progress-text'}).inject(progress, 'after') }); this.updateOverall(); }, onSelect: function() { this.status.removeClass('status-browsing'); }, onCancel: function() { this.status.removeClass('file-browsing'); }, onStart: function() { this.status.addClass('file-uploading'); this.overallProgress.set(0); }, onQueue: function() { this.updateOverall(); }, onComplete: function() { this.status.removeClass('file-uploading'); if (this.size) { this.overallProgress.start(100); } else { this.overallProgress.set(0); this.currentProgress.set(0); } }, updateOverall: function() { this.overallTitle.set('html', Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_PROGRESS_OVERALL', 'Overall Progress').substitute({ total: Swiff.Uploader.formatUnit(this.size, 'b') })); if (!this.size) { this.currentTitle.set('html', Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_CURRENT_TITLE', 'Current Title')); this.currentText.set('html', ''); } }, /** * compat */ upload: function() { this.start(); }, removeFile: function() { return this.remove(); } }); FancyUpload2.File = new Class({ Extends: Swiff.Uploader.File, render: function() { if (this.invalid) { if (this.validationError) { var msg = Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_VALIDATION_ERROR_'+this.validationError, this.validationError); this.validationErrorMessage = msg.substitute({ name: this.name, size: Swiff.Uploader.formatUnit(this.size, 'b'), fileSizeMin: Swiff.Uploader.formatUnit(this.base.options.fileSizeMin || 0, 'b'), fileSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileSizeMax || 0, 'b'), fileListMax: this.base.options.fileListMax || 0, fileListSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileListSizeMax || 0, 'b') }); } this.remove(); return; } this.addEvents({ 'start': this.onStart, 'progress': this.onProgress, 'complete': this.onComplete, 'error': this.onError, 'remove': this.onRemove }); this.info = new Element('span', {'class': 'file-info'}); this.element = new Element('li', {'class': 'file'}).adopt( new Element('span', {'class': 'file-size', 'html': Swiff.Uploader.formatUnit(this.size, 'b')}), new Element('a', { 'class': 'file-remove', href: '#', html: Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_REMOVE', 'Remove'), title: Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_REMOVE_TITLE', 'Remove Title'), events: { click: function() { this.remove(); return false; }.bind(this) } }), new Element('span', {'class': 'file-name', 'html': Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_FILENAME', 'Filename').substitute(this)}), this.info ).inject(this.base.list); }, validate: function() { return (this.parent() && this.base.options.validateFile(this)); }, onStart: function() { this.element.addClass('file-uploading'); this.base.currentProgress.cancel().set(0); this.base.currentTitle.set('html', Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_CURRENT_FILE', 'Current File').substitute(this)); }, onProgress: function() { this.base.overallProgress.start(this.base.percentLoaded); this.base.currentText.set('html', Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_CURRENT_PROGRESS', 'Current Progress').substitute({ rate: (this.progress.rate) ? Swiff.Uploader.formatUnit(this.progress.rate, 'bps') : '- B', bytesLoaded: Swiff.Uploader.formatUnit(this.progress.bytesLoaded, 'b'), timeRemaining: (this.progress.timeRemaining) ? Swiff.Uploader.formatUnit(this.progress.timeRemaining, 's') : '-' })); this.base.currentProgress.start(this.progress.percentLoaded); }, onComplete: function() { this.element.removeClass('file-uploading'); this.base.currentText.set('html', Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_UPLOAD_COMPLETED', 'Upload Completed')); this.base.currentProgress.start(100); if (this.response.error) { var msg = this.response.error; this.errorMessage = msg; var args = [this, this.errorMessage, this.response]; this.fireEvent('error', args).base.fireEvent('fileError', args); } else { this.base.fireEvent('fileSuccess', [this, this.response.text || '']); } }, onError: function() { this.element.addClass('file-failed'); var error = Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_FILE_ERROR', 'File Error').substitute(this); this.info.set('html', '<strong>' + error + ':</strong> ' + this.errorMessage); }, onRemove: function() { this.element.getElements('a').setStyle('visibility', 'hidden'); this.element.fade('out').retrieve('tween').chain(Element.destroy.bind(Element, this.element)); } });
JavaScript
/** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // Only define the Joomla namespace if not defined. if (typeof(Joomla) === 'undefined') { var Joomla = {}; } Joomla.editors = {}; // An object to hold each editor instance on page Joomla.editors.instances = {}; /** * Generic submit form */ Joomla.submitform = function(task, form) { if (typeof(form) === 'undefined') { form = document.getElementById('adminForm'); /** * Added to ensure Joomla 1.5 compatibility */ if(!form){ form = document.adminForm; } } if (typeof(task) !== 'undefined' && '' !== task) { form.task.value = task; } // Submit the form. if (typeof form.onsubmit == 'function') { form.onsubmit(); } if (typeof form.fireEvent == "function") { form.fireEvent('submit'); } form.submit(); }; /** * Default function. Usually would be overriden by the component */ Joomla.submitbutton = function(pressbutton) { Joomla.submitform(pressbutton); } /** * Custom behavior for JavaScript I18N in Joomla! 1.6 * * Allows you to call Joomla.JText._() to get a translated JavaScript string pushed in with JText::script() in Joomla. */ Joomla.JText = { strings: {}, '_': function(key, def) { return typeof this.strings[key.toUpperCase()] !== 'undefined' ? this.strings[key.toUpperCase()] : def; }, load: function(object) { for (var key in object) { this.strings[key.toUpperCase()] = object[key]; } return this; } }; /** * Method to replace all request tokens on the page with a new one. */ Joomla.replaceTokens = function(n) { var els = document.getElementsByTagName('input'); for (var i = 0; i < els.length; i++) { if ((els[i].type == 'hidden') && (els[i].name.length == 32) && els[i].value == '1') { els[i].name = n; } } }; /** * USED IN: administrator/components/com_banners/views/client/tmpl/default.php * * Verifies if the string is in a valid email format * * @param string * @return boolean */ Joomla.isEmail = function(text) { var regex = new RegExp("^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$"); return regex.test(text); }; /** * USED IN: all list forms. * * Toggles the check state of a group of boxes * * Checkboxes must have an id attribute in the form cb0, cb1... * * @param mixed The number of box to 'check', for a checkbox element * @param string An alternative field name */ Joomla.checkAll = function(checkbox, stub) { if (!stub) { stub = 'cb'; } if (checkbox.form) { var c = 0; for (var i = 0, n = checkbox.form.elements.length; i < n; i++) { var e = checkbox.form.elements[i]; if (e.type == checkbox.type) { if ((stub && e.id.indexOf(stub) == 0) || !stub) { e.checked = checkbox.checked; c += (e.checked == true ? 1 : 0); } } } if (checkbox.form.boxchecked) { checkbox.form.boxchecked.value = c; } return true; } return false; } /** * Render messages send via JSON * * @param object messages JavaScript object containing the messages to render * @return void */ Joomla.renderMessages = function(messages) { Joomla.removeMessages(); var container = document.id('system-message-container'); var dl = new Element('dl', { id: 'system-message', role: 'alert' }); Object.each(messages, function (item, type) { var dt = new Element('dt', { 'class': type, html: type }); dt.inject(dl); var dd = new Element('dd', { 'class': type }); dd.addClass('message'); var list = new Element('ul'); Array.each(item, function (item, index, object) { var li = new Element('li', { html: item }); li.inject(list); }, this); list.inject(dd); dd.inject(dl); }, this); dl.inject(container); }; /** * Remove messages * * @return void */ Joomla.removeMessages = function() { var children = $$('#system-message-container > *'); children.destroy(); } /** * USED IN: administrator/components/com_cache/views/cache/tmpl/default.php * administrator/components/com_installer/views/discover/tmpl/default_item.php * administrator/components/com_installer/views/update/tmpl/default_item.php * administrator/components/com_languages/helpers/html/languages.php * libraries/joomla/html/html/grid.php * * @param isitchecked * @param form * @return */ Joomla.isChecked = function(isitchecked, form) { if (typeof(form) === 'undefined') { form = document.getElementById('adminForm'); /** * Added to ensure Joomla 1.5 compatibility */ if(!form){ form = document.adminForm; } } if (isitchecked == true) { form.boxchecked.value++; } else { form.boxchecked.value--; } } /** * USED IN: libraries/joomla/html/toolbar/button/help.php * * Pops up a new window in the middle of the screen */ Joomla.popupWindow = function(mypage, myname, w, h, scroll) { var winl = (screen.width - w) / 2; var wint = (screen.height - h) / 2; var winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=' + scroll + ',resizable' var win = window.open(mypage, myname, winprops) win.window.focus(); } /** * USED IN: libraries/joomla/html/html/grid.php */ Joomla.tableOrdering = function(order, dir, task, form) { if (typeof(form) === 'undefined') { form = document.getElementById('adminForm'); /** * Added to ensure Joomla 1.5 compatibility */ if(!form){ form = document.adminForm; } } form.filter_order.value = order; form.filter_order_Dir.value = dir; Joomla.submitform(task, form); } /** * USED IN: administrator/components/com_modules/views/module/tmpl/default.php * * Writes a dynamically generated list * * @param string * The parameters to insert into the <select> tag * @param array * A javascript array of list options in the form [key,value,text] * @param string * The key to display for the initial state of the list * @param string * The original key that was selected * @param string * The original item value that was selected */ function writeDynaList(selectParams, source, key, orig_key, orig_val) { var html = '\n <select ' + selectParams + '>'; var i = 0; for (x in source) { if (source[x][0] == key) { var selected = ''; if ((orig_key == key && orig_val == source[x][1]) || (i == 0 && orig_key != key)) { selected = 'selected="selected"'; } html += '\n <option value="' + source[x][1] + '" ' + selected + '>' + source[x][2] + '</option>'; } i++; } html += '\n </select>'; document.writeln(html); } /** * USED IN: administrator/components/com_content/views/article/view.html.php * * Changes a dynamically generated list * * @param string * The name of the list to change * @param array * A javascript array of list options in the form [key,value,text] * @param string * The key to display * @param string * The original key that was selected * @param string * The original item value that was selected */ function changeDynaList(listname, source, key, orig_key, orig_val) { var list = document.adminForm[listname]; // empty the list for (i in list.options.length) { list.options[i] = null; } i = 0; for (x in source) { if (source[x][0] == key) { opt = new Option(); opt.value = source[x][1]; opt.text = source[x][2]; if ((orig_key == key && orig_val == opt.value) || i == 0) { opt.selected = true; } list.options[i++] = opt; } } list.length = i; } /** * USED IN: administrator/components/com_menus/views/menus/tmpl/default.php * * @param radioObj * @return */ // return the value of the radio button that is checked // return an empty string if none are checked, or // there are no radio buttons function radioGetCheckedValue(radioObj) { if (!radioObj) { return ''; } var n = radioObj.length; if (n == undefined) { if (radioObj.checked) { return radioObj.value; } else { return ''; } } for ( var i = 0; i < n; i++) { if (radioObj[i].checked) { return radioObj[i].value; } } return ''; } /** * USED IN: administrator/components/com_banners/views/banner/tmpl/default/php * administrator/components/com_categories/views/category/tmpl/default.php * administrator/components/com_categories/views/copyselect/tmpl/default.php * administrator/components/com_content/views/copyselect/tmpl/default.php * administrator/components/com_massmail/views/massmail/tmpl/default.php * administrator/components/com_menus/views/list/tmpl/copy.php * administrator/components/com_menus/views/list/tmpl/move.php * administrator/components/com_messages/views/message/tmpl/default_form.php * administrator/components/com_newsfeeds/views/newsfeed/tmpl/default.php * components/com_content/views/article/tmpl/form.php * templates/beez/html/com_content/article/form.php * * @param frmName * @param srcListName * @return */ function getSelectedValue(frmName, srcListName) { var form = document[frmName]; var srcList = form[srcListName]; i = srcList.selectedIndex; if (i != null && i > -1) { return srcList.options[i].value; } else { return null; } } /** * USED IN: all list forms. * * Toggles the check state of a group of boxes * * Checkboxes must have an id attribute in the form cb0, cb1... * * @param mixed The number of box to 'check', for a checkbox element * @param string An alternative field name * * @deprecated 12.1 This function will be removed in a future version. Use Joomla.checkAll() instead. */ function checkAll(checkbox, stub) { if (!stub) { stub = 'cb'; } if (checkbox.form) { var c = 0; for (var i = 0, n = checkbox.form.elements.length; i < n; i++) { var e = checkbox.form.elements[i]; if (e.type == checkbox.type) { if ((stub && e.id.indexOf(stub) == 0) || !stub) { e.checked = checkbox.checked; c += (e.checked == true ? 1 : 0); } } } if (checkbox.form.boxchecked) { checkbox.form.boxchecked.value = c; } return true; } else { // The old way of doing it var f = document.adminForm; var c = f.toggle.checked; var n = checkbox; var n2 = 0; for (var i = 0; i < n; i++) { var cb = f[stub+''+i]; if (cb) { cb.checked = c; n2++; } } if (c) { document.adminForm.boxchecked.value = n2; } else { document.adminForm.boxchecked.value = 0; } } } /** * USED IN: all over :) * * @param id * @param task * @return */ function listItemTask(id, task) { var f = document.adminForm; var cb = f[id]; if (cb) { for (var i = 0; true; i++) { var cbx = f['cb'+i]; if (!cbx) break; cbx.checked = false; } // for cb.checked = true; f.boxchecked.value = 1; submitbutton(task); } return false; } /** * USED IN: administrator/components/com_cache/views/cache/tmpl/default.php * administrator/components/com_installer/views/discover/tmpl/default_item.php * administrator/components/com_installer/views/update/tmpl/default_item.php * administrator/components/com_languages/helpers/html/languages.php * libraries/joomla/html/html/grid.php * * @deprecated 12.1 This function will be removed in a future version. Use Joomla.isChecked() instead. * * @param isitchecked * @return * */ function isChecked(isitchecked) { if (isitchecked == true) { document.adminForm.boxchecked.value++; } else { document.adminForm.boxchecked.value--; } } /** * Default function. Usually would be overriden by the component * * @deprecated 12.1 This function will be removed in a future version. Use Joomla.submitbutton() instead. */ function submitbutton(pressbutton) { submitform(pressbutton); } /** * Submit the admin form * * @deprecated 12.1 This function will be removed in a future version. Use Joomla.submitform() instead. */ function submitform(pressbutton) { if (pressbutton) { document.adminForm.task.value = pressbutton; } if (typeof document.adminForm.onsubmit == "function") { document.adminForm.onsubmit(); } if (typeof document.adminForm.fireEvent == "function") { document.adminForm.fireEvent('submit'); } document.adminForm.submit(); } /** * USED IN: libraries/joomla/html/toolbar/button/help.php * * Pops up a new window in the middle of the screen * * @deprecated 12.1 This function will be removed in a future version. Use Joomla.popupWindow() instead. */ function popupWindow(mypage, myname, w, h, scroll) { var winl = (screen.width - w) / 2; var wint = (screen.height - h) / 2; winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=' + scroll + ',resizable' win = window.open(mypage, myname, winprops) if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); } } // needed for Table Column ordering /** * USED IN: libraries/joomla/html/html/grid.php * * @deprecated 12.1 This function will be removed in a future version. Use Joomla.tableOrdering() instead. */ function tableOrdering(order, dir, task) { var form = document.adminForm; form.filter_order.value = order; form.filter_order_Dir.value = dir; submitform(task); } /** * USED IN: libraries/joomla/html/html/grid.php */ function saveorder(n, task) { checkAll_button(n, task); } function checkAll_button(n, task) { if (!task) { task = 'saveorder'; } for (var j = 0; j <= n; j++) { var box = document.adminForm['cb'+j]; if (box) { if (box.checked == false) { box.checked = true; } } else { alert("You cannot change the order of items, as an item in the list is `Checked Out`"); return; } } submitform(task); }
JavaScript
/* name: Fx.ProgressBar description: Creates a progressbar with WAI-ARIA and optional HTML5 support. license: MIT-style authors: - Harald Kirschner <mail [at] digitarald [dot] de> - Rouven Weßling <me [at] rouvenwessling [dot] de> requires: [Core/Fx, Core/Class, Core/Element] provides: Fx.ProgressBar */ Fx.ProgressBar = new Class({ Extends: Fx, options: { text: null, url: null, transition: Fx.Transitions.Circ.easeOut, fit: true, link: 'cancel', html5: true }, initialize: function(element, options) { this.element = document.id(element); this.parent(options); var url = this.options.url; this.useHtml5 = this.options.html5 && this.supportsHtml5(); if (this.useHtml5) { this.progressElement = new Element('progress').replaces(this.element); this.progressElement.max = 100; this.progressElement.value = 0; } else { //WAI-ARIA this.element.set('role', 'progressbar'); this.element.set('aria-valuenow', '0'); this.element.set('aria-valuemin', '0'); this.element.set('aria-valuemax', '100'); if (url) { this.element.setStyles({ 'background-image': 'url(' + url + ')', 'background-repeat': 'no-repeat' }); } } if (this.options.fit && !this.useHtml5) { url = url || this.element.getStyle('background-image').replace(/^url\(["']?|["']?\)$/g, ''); if (url) { var fill = new Image(); fill.onload = function() { this.fill = fill.width; fill = fill.onload = null; this.set(this.now || 0); }.bind(this); fill.src = url; if (!this.fill && fill.width) fill.onload(); } } else { this.set(0); } }, supportsHtml5: function () { return 'value' in document.createElement('progress'); }, start: function(to, total) { return this.parent(this.now, (arguments.length == 1) ? to.limit(0, 100) : to / total * 100); }, set: function(to) { this.now = to; if (this.useHtml5) { this.progressElement.value = to; } else { var css = (this.fill) ? (((this.fill / -2) + (to / 100) * (this.element.width || 1) || 0).round() + 'px') : ((100 - to) + '%'); this.element.setStyle('backgroundPosition', css + ' 0px').title = Math.round(to) + '%'; this.element.set('aria-valuenow', to); } var text = document.id(this.options.text); if (text) text.set('text', Math.round(to) + '%'); return this; } });
JavaScript
/* --- description: Form.PasswordStrength class, and basic dom methods license: MIT-style authors: - Al Kent requires: - core/1.3.1: '*' provides: - Form.PasswordStrength - Element.Events.keyupandchange - String.strength ... */ if (!this.Form) this.Form = {}; Form.PasswordStrength = new Class({ Implements: [Options, Events], options: { //onUpdate: $empty, threshold: 66, primer: '', height: 5, opacity: 1, bgcolor: 'transparent' }, element: null, fx: null, initialize: function(el, options){ this.element = document.id(el); this.setOptions(options); if (this.options.primer) this.options.threshold = this.options.primer.strength(); var coord = this.element.getCoordinates(); var bar = new Element('div', { styles: { 'position': 'absolute', 'top': coord.top + coord.height, 'left': coord.left, 'width': coord.width, 'height': this.options.height, 'opacity': this.options.opacity, 'background-color': this.options.bgcolor } }).inject(document.body, 'bottom'); var meter = new Element('div', { styles: { 'width': 0, 'height': '100%' } }).inject(bar); this.fx = new Fx.Morph(meter, { duration: 'short', link: 'cancel', unit: '%' }); this.element.addEvent('keyupandchange', this.animate.bind(this)); if (this.element.get('value')) this.animate(); }, animate: function(){ var value = this.element.get('value'); var color, strength = value.strength(), ratio = (strength / this.options.threshold).round(2).limit(0, 1); if (ratio < 0.5) color = ('rgb(255, ' + (255 * ratio * 2).round() + ', 0)').rgbToHex(); else color = ('rgb(' + (255 * (1 - ratio) * 2).round() + ', 255, 0)').rgbToHex(); this.fx.start({ 'width': 100 * ratio, 'background-color': color }); this.fireEvent('update', [this.element, strength, this.options.threshold]); } }); Element.Events.keyupandchange = { base: 'keyup', condition: function(event){ var prev = this.retrieve('prev', null); var cur = this.get('value'); if (typeOf(prev) != 'null' && prev == cur) return false; this.store('prev', cur); return true; } }; String.implement({ strength: function(){ var n = 0; if (this.match(/\d/)) n += 10; if (this.match(/[a-z]+/)) n += 26; if (this.match(/[A-Z]+/)) n += 26; if (this.match(/[^\da-zA-Z]/)) n += 33; return (n == 0) ? 0 : (this.length * n.log() / (2).log()).round(); } });
JavaScript
/* --- script: mooRainbow.js version: 1.3 description: MooRainbow is a ColorPicker for MooTools 1.3 license: MIT-Style authors: - Djamil Legato (w00fz) - Christopher Beloch requires: [Core/*, More/Slider, More/Drag, More/Color] provides: [mooRainbow] ... */ var MooRainbow = new Class({ options: { id: 'mooRainbow', prefix: 'moor-', imgPath: 'images/', startColor: [255, 0, 0], wheel: false, onComplete: Class.empty, onChange: Class.empty }, initialize: function(el, options) { this.element = document.id(el); if (!this.element) return; this.setOptions(options); this.sliderPos = 0; this.pickerPos = {x: 0, y: 0}; this.backupColor = this.options.startColor; this.currentColor = this.options.startColor; this.sets = { rgb: [], hsb: [], hex: [] }; this.pickerClick = this.sliderClick = false; if (!this.layout) this.doLayout(); this.OverlayEvents(); this.sliderEvents(); this.backupEvent(); if (this.options.wheel) this.wheelEvents(); this.element.addEvent('click', function(e) { this.toggle(e); }.bind(this)); this.layout.overlay.setStyle('background-color', this.options.startColor.rgbToHex()); this.layout.backup.setStyle('background-color', this.backupColor.rgbToHex()); this.pickerPos.x = this.snippet('curPos').l + this.snippet('curSize', 'int').w; this.pickerPos.y = this.snippet('curPos').t + this.snippet('curSize', 'int').h; this.manualSet(this.options.startColor); this.pickerPos.x = this.snippet('curPos').l + this.snippet('curSize', 'int').w; this.pickerPos.y = this.snippet('curPos').t + this.snippet('curSize', 'int').h; this.sliderPos = this.snippet('arrPos') - this.snippet('arrSize', 'int'); if (window.khtml) this.hide(); }, toggle: function() { this[this.visible ? 'hide' : 'show']() }, show: function() { this.rePosition(); this.layout.setStyle('display', 'block'); this.layout.set('aria-hidden', 'false'); this.visible = true; }, hide: function() { this.layout.setStyles({'display': 'none'}); this.layout.set('aria-hidden', 'true'); this.visible = false; }, manualSet: function(color, type) { if (!type || (type != 'hsb' && type != 'hex')) type = 'rgb'; var rgb, hsb, hex; if (type == 'rgb') { rgb = color; hsb = color.rgbToHsb(); hex = color.rgbToHex(); } else if (type == 'hsb') { hsb = color; rgb = color.hsbToRgb(); hex = rgb.rgbToHex(); } else { hex = color; rgb = color.hexToRgb(true); hsb = rgb.rgbToHsb(); } this.setMooRainbow(rgb); this.autoSet(hsb); }, autoSet: function(hsb) { var curH = this.snippet('curSize', 'int').h; var curW = this.snippet('curSize', 'int').w; var oveH = this.layout.overlay.height; var oveW = this.layout.overlay.width; var sliH = this.layout.slider.height; var arwH = this.snippet('arrSize', 'int'); var hue; var posx = Math.round(((oveW * hsb[1]) / 100) - curW); var posy = Math.round(- ((oveH * hsb[2]) / 100) + oveH - curH); var c = Math.round(((sliH * hsb[0]) / 360)); c = (c == 360) ? 0 : c; var position = sliH - c + this.snippet('slider') - arwH; hue = [this.sets.hsb[0], 100, 100].hsbToRgb().rgbToHex(); this.layout.cursor.setStyles({'top': posy, 'left': posx}); this.layout.arrows.setStyle('top', position); this.layout.overlay.setStyle('background-color', hue); this.sliderPos = this.snippet('arrPos') - arwH; this.pickerPos.x = this.snippet('curPos').l + curW; this.pickerPos.y = this.snippet('curPos').t + curH; }, setMooRainbow: function(color, type) { if (!type || (type != 'hsb' && type != 'hex')) type = 'rgb'; var rgb, hsb, hex; if (type == 'rgb') { rgb = color; hsb = color.rgbToHsb(); hex = color.rgbToHex(); } else if (type == 'hsb') { hsb = color; rgb = color.hsbToRgb(); hex = rgb.rgbToHex(); } else { hex = color; rgb = color.hexToRgb(); hsb = rgb.rgbToHsb(); } this.sets = { rgb: rgb, hsb: hsb, hex: hex }; if (!this.pickerPos.x) this.autoSet(hsb); this.RedInput.value = rgb[0]; this.GreenInput.value = rgb[1]; this.BlueInput.value = rgb[2]; this.HueInput.value = hsb[0]; this.SatuInput.value = hsb[1]; this.BrighInput.value = hsb[2]; this.hexInput.value = hex; this.currentColor = rgb; this.chooseColor.setStyle('background-color', rgb.rgbToHex()); this.fireEvent('onChange', [this.sets, this]); }, parseColors: function(x, y, z) { var s = Math.round((x * 100) / this.layout.overlay.width); var b = 100 - Math.round((y * 100) / this.layout.overlay.height); var h = 360 - Math.round((z * 360) / this.layout.slider.height) + this.snippet('slider') - this.snippet('arrSize', 'int'); h -= this.snippet('arrSize', 'int'); h = (h >= 360) ? 0 : (h < 0) ? 0 : h; s = (s > 100) ? 100 : (s < 0) ? 0 : s; b = (b > 100) ? 100 : (b < 0) ? 0 : b; return [h, s, b]; }, OverlayEvents: function() { var lim, curH, curW, inputs; curH = this.snippet('curSize', 'int').h; curW = this.snippet('curSize', 'int').w; inputs = this.arrRGB.concat(this.arrHSB, this.hexInput); document.addEvent('click', function() { if(this.visible) this.hide(this.layout); }.bind(this)); inputs.each(function(el) { el.addEvent('keydown', this.eventKeydown.bind(this, el)); el.addEvent('keyup', this.eventKeyup.bind(this, el)); }, this); [this.element, this.layout].each(function(el) { el.addEvents({ 'click': function(e) { new Event(e).stop(); }, 'keyup': function(e) { e = new Event(e); if(e.key == 'esc' && this.visible) this.hide(this.layout); }.bind(this) }, this); }, this); lim = { x: [0 - curW, (this.layout.overlay.width - curW)], y: [0 - curH, (this.layout.overlay.height - curH)] }; this.layout.drag = new Drag(this.layout.cursor, { onStart: this.overlayDrag.bind(this), onDrag: this.overlayDrag.bind(this), snap: 0 }); this.layout.overlay2.addEvent('mousedown', function(e){ e = new Event(e); this.layout.cursor.setStyles({ 'top': e.page.y - this.layout.overlay.getTop() - curH, 'left': e.page.x - this.layout.overlay.getLeft() - curW }); this.overlayDrag.call(this); this.layout.drag.start(e); }.bind(this)); this.okButton.addEvent('click', function() { if(this.currentColor == this.options.startColor) { this.hide(); this.fireEvent('onComplete', [this.sets, this]); } else { this.backupColor = this.currentColor; this.layout.backup.setStyle('background-color', this.backupColor.rgbToHex()); this.hide(); this.fireEvent('onComplete', [this.sets, this]); } }.bind(this)); }, overlayDrag: function() { var curH = this.snippet('curSize', 'int').h; var curW = this.snippet('curSize', 'int').w; this.pickerPos.x = this.snippet('curPos').l + curW; this.pickerPos.y = this.snippet('curPos').t + curH; this.setMooRainbow(this.parseColors(this.pickerPos.x, this.pickerPos.y, this.sliderPos), 'hsb'); this.fireEvent('onChange', [this.sets, this]); }, sliderEvents: function() { var arwH = this.snippet('arrSize', 'int'), lim; lim = [0 + this.snippet('slider') - arwH, this.layout.slider.height - arwH + this.snippet('slider')]; this.layout.sliderDrag = new Drag(this.layout.arrows, { limit: {y: lim}, modifiers: {x: false}, onStart: this.sliderDrag.bind(this), onDrag: this.sliderDrag.bind(this), snap: 0 }); this.layout.slider.addEvent('mousedown', function(e){ e = new Event(e); this.layout.arrows.setStyle( 'top', e.page.y - this.layout.slider.getTop() + this.snippet('slider') - arwH ); this.sliderDrag.call(this); this.layout.sliderDrag.start(e); }.bind(this)); }, sliderDrag: function() { var arwH = this.snippet('arrSize', 'int'), hue; this.sliderPos = this.snippet('arrPos') - arwH; this.setMooRainbow(this.parseColors(this.pickerPos.x, this.pickerPos.y, this.sliderPos), 'hsb'); hue = [this.sets.hsb[0], 100, 100].hsbToRgb().rgbToHex(); this.layout.overlay.setStyle('background-color', hue); this.fireEvent('onChange', [this.sets, this]); }, backupEvent: function() { this.layout.backup.addEvent('click', function() { this.manualSet(this.backupColor); this.fireEvent('onChange', [this.sets, this]); }.bind(this)); }, wheelEvents: function() { var arrColors = this.arrRGB.copy().extend(this.arrHSB); arrColors.each(function(el) { el.addEvents({ 'mousewheel': this.eventKeys.bindWithEvent(this, el), 'keydown': this.eventKeys.bindWithEvent(this, el) }); }, this); [this.layout.arrows, this.layout.slider].each(function(el) { el.addEvents({ 'mousewheel': this.eventKeys.bindWithEvent(this, [this.arrHSB[0], 'slider']), 'keydown': this.eventKeys.bindWithEvent(this, [this.arrHSB[0], 'slider']) }); }, this); }, eventKeys: function(e, el, id) { var wheel, type; id = (!id) ? el.id : this.arrHSB[0]; if (e.type == 'keydown') { if (e.key == 'up') wheel = 1; else if (e.key == 'down') wheel = -1; else return; } else if (e.type == Element.Events.mousewheel.type) wheel = (e.wheel > 0) ? 1 : -1; if (this.arrRGB.test(el)) type = 'rgb'; else if (this.arrHSB.test(el)) type = 'hsb'; else type = 'hsb'; if (type == 'rgb') { var rgb = this.sets.rgb, hsb = this.sets.hsb, prefix = this.options.prefix, pass; var value = el.value.toInt() + wheel; value = (value > 255) ? 255 : (value < 0) ? 0 : value; switch(el.className) { case prefix + 'rInput': pass = [value, rgb[1], rgb[2]]; break; case prefix + 'gInput': pass = [rgb[0], value, rgb[2]]; break; case prefix + 'bInput': pass = [rgb[0], rgb[1], value]; break; default : pass = rgb; } this.manualSet(pass); this.fireEvent('onChange', [this.sets, this]); } else { var rgb = this.sets.rgb, hsb = this.sets.hsb, prefix = this.options.prefix, pass; var value = el.value.toInt() + wheel; if (el.className.test(/(HueInput)/)) value = (value > 359) ? 0 : (value < 0) ? 0 : value; else value = (value > 100) ? 100 : (value < 0) ? 0 : value; switch(el.className) { case prefix + 'HueInput': pass = [value, hsb[1], hsb[2]]; break; case prefix + 'SatuInput': pass = [hsb[0], value, hsb[2]]; break; case prefix + 'BrighInput': pass = [hsb[0], hsb[1], value]; break; default : pass = hsb; } this.manualSet(pass, 'hsb'); this.fireEvent('onChange', [this.sets, this]); } e.stop(); }, eventKeydown: function(el, e) { var n = e.code, k = e.key; if ((!el.className.test(/hexInput/) && !(n >= 48 && n <= 57)) && (k!='backspace' && k!='tab' && k !='delete' && k!='left' && k!='right')) e.stop(); }, eventKeyup: function(el, e) { var n = e.code, k = e.key, pass, prefix, chr = el.value.charAt(0); if (!(el.value || el.value === 0)) return; if (el.className.test(/hexInput/)) { if (chr != "#" && el.value.length != 6) return; if (chr == '#' && el.value.length != 7) return; } else { if (!(n >= 48 && n <= 57) && (!['backspace', 'tab', 'delete', 'left', 'right'].test(k)) && el.value.length > 3) return; } prefix = this.options.prefix; if (el.className.test(/(rInput|gInput|bInput)/)) { if (el.value < 0 || el.value > 255) return; switch(el.className){ case prefix + 'rInput': pass = [el.value, this.sets.rgb[1], this.sets.rgb[2]]; break; case prefix + 'gInput': pass = [this.sets.rgb[0], el.value, this.sets.rgb[2]]; break; case prefix + 'bInput': pass = [this.sets.rgb[0], this.sets.rgb[1], el.value]; break; default : pass = this.sets.rgb; } this.manualSet(pass); this.fireEvent('onChange', [this.sets, this]); } else if (!el.className.test(/hexInput/)) { if (el.className.test(/HueInput/) && el.value < 0 || el.value > 360) return; else if (el.className.test(/HueInput/) && el.value == 360) el.value = 0; else if (el.className.test(/(SatuInput|BrighInput)/) && el.value < 0 || el.value > 100) return; switch(el.className){ case prefix + 'HueInput': pass = [el.value, this.sets.hsb[1], this.sets.hsb[2]]; break; case prefix + 'SatuInput': pass = [this.sets.hsb[0], el.value, this.sets.hsb[2]]; break; case prefix + 'BrighInput': pass = [this.sets.hsb[0], this.sets.hsb[1], el.value]; break; default : pass = this.sets.hsb; } this.manualSet(pass, 'hsb'); this.fireEvent('onChange', [this.sets, this]); } else { pass = el.value.hexToRgb(true); if (isNaN(pass[0])||isNaN(pass[1])||isNaN(pass[2])) return; if (pass || pass === 0) { this.manualSet(pass); this.fireEvent('onChange', [this.sets, this]); } } }, doLayout: function() { var id = this.options.id, prefix = this.options.prefix; var idPrefix = id + ' .' + prefix; this.layout = new Element('div', { 'styles': {'display': 'block', 'position': 'absolute'}, 'id': id }).inject(document.body); var box = new Element('div', { 'styles': {'position': 'relative'}, 'class': prefix + 'box' }).inject(this.layout); var div = new Element('div', { 'styles': {'position': 'absolute', 'overflow': 'hidden'}, 'class': prefix + 'overlayBox' }).inject(box); var ar = new Element('div', { 'styles': {'position': 'absolute', 'zIndex': 1}, 'class': prefix + 'arrows' }).inject(box); ar.width = ar.getStyle('width').toInt(); ar.height = ar.getStyle('height').toInt(); var ov = new Element('img', { 'styles': {'background-color': '#fff', 'position': 'relative', 'zIndex': 2}, 'src': this.options.imgPath + 'moor_woverlay.png', 'class': prefix + 'overlay' }).inject(div); var ov2 = new Element('img', { 'styles': {'position': 'absolute', 'top': 0, 'left': 0, 'zIndex': 2}, 'src': this.options.imgPath + 'moor_boverlay.png', 'class': prefix + 'overlay' }).inject(div); if (window.ie6) { div.setStyle('overflow', ''); var src = ov.src; ov.src = this.options.imgPath + 'blank.gif'; ov.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')"; src = ov2.src; ov2.src = this.options.imgPath + 'blank.gif'; ov2.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')"; } ov.width = ov2.width = div.getStyle('width').toInt(); ov.height = ov2.height = div.getStyle('height').toInt(); var cr = new Element('div', { 'styles': {'overflow': 'hidden', 'position': 'absolute', 'zIndex': 2}, 'class': prefix + 'cursor' }).inject(div); cr.width = cr.getStyle('width').toInt(); cr.height = cr.getStyle('height').toInt(); var sl = new Element('img', { 'styles': {'position': 'absolute', 'z-index': 2}, 'src': this.options.imgPath + 'moor_slider.png', 'class': prefix + 'slider' }).inject(box); this.layout.slider = Slick.find(document, '#' + idPrefix + 'slider'); sl.width = sl.getStyle('width').toInt(); sl.height = sl.getStyle('height').toInt(); new Element('div', { 'styles': {'position': 'absolute'}, 'class': prefix + 'colorBox' }).inject(box); new Element('div', { 'styles': {'zIndex': 2, 'position': 'absolute'}, 'class': prefix + 'chooseColor' }).inject(box); this.layout.backup = new Element('div', { 'styles': {'zIndex': 2, 'position': 'absolute', 'cursor': 'pointer'}, 'class': prefix + 'currentColor' }).inject(box); var R = new Element('label').inject(box).setStyle('position', 'absolute'); var G = R.clone().inject(box).addClass(prefix + 'gLabel').appendText('G: '); var B = R.clone().inject(box).addClass(prefix + 'bLabel').appendText('B: '); R.appendText('R: ').addClass(prefix + 'rLabel'); var inputR = new Element('input'); var inputG = inputR.clone().inject(G).addClass(prefix + 'gInput'); var inputB = inputR.clone().inject(B).addClass(prefix + 'bInput'); inputR.inject(R).addClass(prefix + 'rInput'); var HU = new Element('label').inject(box).setStyle('position', 'absolute'); var SA = HU.clone().inject(box).addClass(prefix + 'SatuLabel').appendText('S: '); var BR = HU.clone().inject(box).addClass(prefix + 'BrighLabel').appendText('B: '); HU.appendText('H: ').addClass(prefix + 'HueLabel'); var inputHU = new Element('input'); var inputSA = inputHU.clone().inject(SA).addClass(prefix + 'SatuInput'); var inputBR = inputHU.clone().inject(BR).addClass(prefix + 'BrighInput'); inputHU.inject(HU).addClass(prefix + 'HueInput'); SA.appendText(' %'); BR.appendText(' %'); (new Element('span', {'styles': {'position': 'absolute'}, 'class': prefix + 'ballino'}).set('html', " &deg;").inject(HU, 'after')); var hex = new Element('label').inject(box).setStyle('position', 'absolute').addClass(prefix + 'hexLabel').appendText('#hex: ').adopt(new Element('input').addClass(prefix + 'hexInput')); var ok = new Element('input', { 'styles': {'position': 'absolute'}, 'type': 'button', 'value': 'Select', 'class': prefix + 'okButton' }).inject(box); this.rePosition(); var overlays = $$('#' + idPrefix + 'overlay'); this.layout.overlay = overlays[0]; this.layout.overlay2 = overlays[1]; this.layout.cursor = Slick.find(document, '#' + idPrefix + 'cursor'); this.layout.arrows = Slick.find(document, '#' + idPrefix + 'arrows'); this.chooseColor = Slick.find(document, '#' + idPrefix + 'chooseColor'); this.layout.backup = Slick.find(document, '#' + idPrefix + 'currentColor'); this.RedInput = Slick.find(document, '#' + idPrefix + 'rInput'); this.GreenInput = Slick.find(document, '#' + idPrefix + 'gInput'); this.BlueInput = Slick.find(document, '#' + idPrefix + 'bInput'); this.HueInput = Slick.find(document, '#' + idPrefix + 'HueInput'); this.SatuInput = Slick.find(document, '#' + idPrefix + 'SatuInput'); this.BrighInput = Slick.find(document, '#' + idPrefix + 'BrighInput'); this.hexInput = Slick.find(document, '#' + idPrefix + 'hexInput'); this.arrRGB = [this.RedInput, this.GreenInput, this.BlueInput]; this.arrHSB = [this.HueInput, this.SatuInput, this.BrighInput]; this.okButton = Slick.find(document, '#' + idPrefix + 'okButton'); this.layout.cursor.setStyle('background-image', 'url(' + this.options.imgPath + 'moor_cursor.gif)'); if (!window.khtml) this.hide(); }, rePosition: function() { var coords = this.element.getCoordinates(); this.layout.setStyles({ 'left': coords.left, 'top': coords.top + coords.height + 1 }); }, snippet: function(mode, type) { var size; type = (type) ? type : 'none'; switch(mode) { case 'arrPos': var t = this.layout.arrows.getStyle('top').toInt(); size = t; break; case 'arrSize': var h = this.layout.arrows.height; h = (type == 'int') ? (h/2).toInt() : h; size = h; break; case 'curPos': var l = this.layout.cursor.getStyle('left').toInt(); var t = this.layout.cursor.getStyle('top').toInt(); size = {'l': l, 't': t}; break; case 'slider': var t = this.layout.slider.getStyle('marginTop').toInt(); size = t; break; default : var h = this.layout.cursor.height; var w = this.layout.cursor.width; h = (type == 'int') ? (h/2).toInt() : h; w = (type == 'int') ? (w/2).toInt() : w; size = {w: w, h: h}; }; return size; } }); MooRainbow.implement(new Options); MooRainbow.implement(new Events);
JavaScript
/* Script: mootree.js My Object Oriented Tree - Developed by Rasmus Schultz, <http://www.mindplay.dk> - Tested with MooTools release 1.2, under Firefox 2, Opera 9 and Internet Explorer 6 and 7. License: MIT-style license. Credits: Inspired by: - WebFX xTree, <http://webfx.eae.net/dhtml/xtree/> - Destroydrop dTree, <http://www.destroydrop.com/javascripts/tree/> Changes: rev.12: - load() only worked once on the same node, fixed. - the script would sometimes try to get 'R' from the server, fixed. - the 'load' attribute is now supported in XML files (see example_5.html). rev.13: - enable() and disable() added - the adopt() and load() methods use these to improve performance by minimizing the number of visual updates. rev.14: - toggle() was using enable() and disable() which actually caused it to do extra work - fixed. rev.15: - adopt() now picks up 'href', 'target', 'title' and 'name' attributes of the a-tag, and stores them in the data object. - adopt() now picks up additional constructor arguments from embedded comments, e.g. icons, colors, etc. - documentation now generates properly with NaturalDocs, <http://www.naturaldocs.org/> rev.16: - onClick events added to MooTreeControl and MooTreeNode - nodes can now have id's - <MooTreeControl.get> method can be used to find a node with a given id rev.17: - changed icon rendering to use innerHTML, making the control faster (and code size slightly smaller). rev.18: - migrated to MooTools 1.2 (previous versions no longer supported) */ var MooTreeIcon = ['I','L','Lminus','Lplus','Rminus','Rplus','T','Tminus','Tplus','_closed','_doc','_open','minus','plus']; /* Class: MooTreeControl This class implements a tree control. Properties: root - returns the root <MooTreeNode> object. selected - returns the currently selected <MooTreeNode> object, or null if nothing is currently selected. Events: onExpand - called when a node is expanded or collapsed: function(node, state) - where node is the <MooTreeNode> object that fired the event, and state is a boolean meaning true:expanded or false:collapsed. onSelect - called when a node is selected or deselected: function(node, state) - where node is the <MooTreeNode> object that fired the event, and state is a boolean meaning true:selected or false:deselected. onClick - called when a node is clicked: function(node) - where node is the <MooTreeNode> object that fired the event. Parameters: The constructor takes two object parameters: config and options. The first, config, contains global settings for the tree control - you can use the configuration options listed below. The second, options, should contain options for the <MooTreeNode> constructor - please refer to the options listed in the <MooTreeNode> documentation. Config: div - a string representing the div Element inside which to build the tree control. mode - optional string, defaults to 'files' - specifies default icon behavior. In 'files' mode, empty nodes have a document icon - whereas, in 'folders' mode, all nodes are displayed as folders (a'la explorer). grid - boolean, defaults to false. If set to true, a grid is drawn to outline the structure of the tree. theme - string, optional, defaults to 'mootree.gif' - specifies the 'theme' GIF to use. loader - optional, an options object for the <MooTreeNode> constructor - defaults to {icon:'mootree_loader.gif', text:'Loading...', color:'a0a0a0'} onExpand - optional function (see Events above) onSelect - optional function (see Events above) */ var MooTreeControl = new Class({ initialize: function(config, options) { options.control = this; // make sure our new MooTreeNode knows who it's owner control is options.div = config.div; // tells the root node which div to insert itself into this.root = new MooTreeNode(options); // create the root node of this tree control this.index = new Object(); // used by the get() method this.enabled = true; // enable visual updates of the control this.theme = config.theme || 'mootree.gif'; this.loader = config.loader || {icon:'mootree_loader.gif', text:'Loading...', color:'#a0a0a0'}; this.selected = null; // set the currently selected node to nothing this.mode = config.mode; // mode can be "folders" or "files", and affects the default icons this.grid = config.grid; // grid can be turned on (true) or off (false) this.onExpand = config.onExpand || new Function(); // called when any node in the tree is expanded/collapsed this.onSelect = config.onSelect || new Function(); // called when any node in the tree is selected/deselected this.onClick = config.onClick || new Function(); // called when any node in the tree is clicked this.root.update(true); }, /* Property: insert Creates a new node under the root node of this tree. Parameters: options - an object containing the same options available to the <MooTreeNode> constructor. Returns: A new <MooTreeNode> instance. */ insert: function(options) { options.control = this; return this.root.insert(options); }, /* Property: select Sets the currently selected node. This is called by <MooTreeNode> when a node is selected (e.g. by clicking it's title with the mouse). Parameters: node - the <MooTreeNode> object to select. */ select: function(node) { this.onClick(node); node.onClick(); // fire click events if (this.selected === node) return; // already selected if (this.selected) { // deselect previously selected node: this.selected.select(false); this.onSelect(this.selected, false); } // select new node: this.selected = node; node.select(true); this.onSelect(node, true); }, /* Property: expand Expands the entire tree, recursively. */ expand: function() { this.root.toggle(true, true); }, /* Property: collapse Collapses the entire tree, recursively. */ collapse: function() { this.root.toggle(true, false); }, /* Property: get Retrieves the node with the given id - or null, if no node with the given id exists. Parameters: id - a string, the id of the node you wish to retrieve. Note: Node id can be assigned via the <MooTreeNode> constructor, e.g. using the <MooTreeNode.insert> method. */ get: function(id) { return this.index[id] || null; }, /* Property: adopt Adopts a structure of nested ul/li/a elements as tree nodes, then removes the original elements. Parameters: id - a string representing the ul element to be adopted, or an element reference. parentNode - optional, a <MooTreeNode> object under which to import the specified ul element. Defaults to the root node of the parent control. Note: The ul/li structure must be properly nested, and each li-element must contain one a-element, e.g.: ><ul id="mytree"> > <li><a href="test.html">Item One</a></li> > <li><a href="test.html">Item Two</a> > <ul> > <li><a href="test.html">Item Two Point One</a></li> > <li><a href="test.html">Item Two Point Two</a></li> > </ul> > </li> > <li><a href="test.html"><!-- icon:_doc; color:#ff0000 -->Item Three</a></li> ></ul> The "href", "target", "title" and "name" attributes of the a-tags are picked up and stored in the data property of the node. CSS-style comments inside a-tags are parsed, and treated as arguments for <MooTreeNode> constructor, e.g. "icon", "openicon", "color", etc. */ adopt: function(id, parentNode) { if (parentNode === undefined) parentNode = this.root; this.disable(); this._adopt(id, parentNode); parentNode.update(true); document.id(id).destroy(); this.enable(); }, _adopt: function(id, parentNode) { /* adopts a structure of ul/li elements into this tree */ e = document.id(id); var i=0, c = e.getChildren(); for (i=0; i<c.length; i++) { if (c[i].nodeName == 'LI') { var con={text:''}, comment='', node=null, subul=null; var n=0, z=0, se=null, s = c[i].getChildren(); for (n=0; n<s.length; n++) { switch (s[n].nodeName) { case 'A': for (z=0; z<s[n].childNodes.length; z++) { se = s[n].childNodes[z]; switch (se.nodeName) { case '#text': con.text += se.nodeValue; break; case '#comment': comment += se.nodeValue; break; } } con.data = s[n].getProperties('href','target','title','name'); break; case 'UL': subul = s[n]; break; } } if (con.label != '') { con.data.url = con.data['href']; // (for backwards compatibility) if (comment != '') { var bits = comment.split(';'); for (z=0; z<bits.length; z++) { var pcs = bits[z].trim().split(':'); if (pcs.length == 2) con[pcs[0].trim()] = pcs[1].trim(); } } if (c[i].id != null) { con.id = 'node_'+c[i].id; } node = parentNode.insert(con); if (subul) this._adopt(subul, node); } } } }, /* Property: disable Call this to temporarily disable visual updates -- if you need to insert/remove many nodes at a time, many visual updates would normally occur. By temporarily disabling the control, these visual updates will be skipped. When you're done making changes, call <MooTreeControl.enable> to turn on visual updates again, and automatically repaint all nodes that were changed. */ disable: function() { this.enabled = false; }, /* Property: enable Enables visual updates again after a call to <MooTreeControl.disable> */ enable: function() { this.enabled = true; this.root.update(true, true); } }); /* Class: MooTreeNode This class implements the functionality of a single node in a <MooTreeControl>. Note: You should not manually create objects of this class -- rather, you should use <MooTreeControl.insert> to create nodes in the root of the tree, and then use the similar function <MooTreeNode.insert> to create subnodes. Both insert methods have a similar syntax, and both return the newly created <MooTreeNode> object. Parameters: options - an object. See options below. Options: text - this is the displayed text of the node, and as such as is the only required parameter. id - string, optional - if specified, must be a unique node identifier. Nodes with id can be retrieved using the <MooTreeControl.get> method. color - string, optional - if specified, must be a six-digit hexadecimal RGB color code. open - boolean value, defaults to false. Use true if you want the node open from the start. icon - use this to customize the icon of the node. The following predefined values may be used: '_open', '_closed' and '_doc'. Alternatively, specify the URL of a GIF or PNG image to use - this should be exactly 18x18 pixels in size. If you have a strip of images, you can specify an image number (e.g. 'my_icons.gif#4' for icon number 4). openicon - use this to customize the icon of the node when it's open. data - an object containing whatever data you wish to associate with this node (such as an url and/or an id, etc.) Events: onExpand - called when the node is expanded or collapsed: function(state) - where state is a boolean meaning true:expanded or false:collapsed. onSelect - called when the node is selected or deselected: function(state) - where state is a boolean meaning true:selected or false:deselected. onClick - called when the node is clicked (no arguments). */ var MooTreeNode = new Class({ initialize: function(options) { this.text = options.text; // the text displayed by this node this.id = options.id || null; // the node's unique id this.nodes = new Array(); // subnodes nested beneath this node (MooTreeNode objects) this.parent = null; // this node's parent node (another MooTreeNode object) this.last = true; // a flag telling whether this node is the last (bottom) node of it's parent this.control = options.control; // owner control of this node's tree this.selected = false; // a flag telling whether this node is the currently selected node in it's tree this.color = options.color || null; // text color of this node this.data = options.data || {}; // optional object containing whatever data you wish to associate with the node (typically an url or an id) this.onExpand = options.onExpand || new Function(); // called when the individual node is expanded/collapsed this.onSelect = options.onSelect || new Function(); // called when the individual node is selected/deselected this.onClick = options.onClick || new Function(); // called when the individual node is clicked this.open = options.open ? true : false; // flag: node open or closed? this.icon = options.icon; this.openicon = options.openicon || this.icon; // add the node to the control's node index: if (this.id) this.control.index[this.id] = this; // create the necessary divs: this.div = { main: new Element('div').addClass('mooTree_node'), indent: new Element('div'), gadget: new Element('div'), icon: new Element('div'), text: new Element('div').addClass('mooTree_text'), sub: new Element('div') } // put the other divs under the main div: this.div.main.adopt(this.div.indent); this.div.main.adopt(this.div.gadget); this.div.main.adopt(this.div.icon); this.div.main.adopt(this.div.text); // put the main and sub divs in the specified parent div: document.id(options.div).adopt(this.div.main); document.id(options.div).adopt(this.div.sub); // attach event handler to gadget: this.div.gadget._node = this; this.div.gadget.onclick = this.div.gadget.ondblclick = function() { this._node.toggle(); } // attach event handler to icon/text: this.div.icon._node = this.div.text._node = this; this.div.icon.onclick = this.div.icon.ondblclick = this.div.text.onclick = this.div.text.ondblclick = function() { this._node.control.select(this._node); } }, /* Property: insert Creates a new node, nested inside this one. Parameters: options - an object containing the same options available to the <MooTreeNode> constructor. Returns: A new <MooTreeNode> instance. */ insert: function(options) { // set the parent div and create the node: options.div = this.div.sub; options.control = this.control; var node = new MooTreeNode(options); // set the new node's parent: node.parent = this; // mark this node's last node as no longer being the last, then add the new last node: var n = this.nodes; if (n.length) n[n.length-1].last = false; n.push(node); // repaint the new node: node.update(); // repaint the new node's parent (this node): if (n.length == 1) this.update(); // recursively repaint the new node's previous sibling node: if (n.length > 1) n[n.length-2].update(true); return node; }, /* Property: remove Removes this node, and all of it's child nodes. If you want to remove all the childnodes without removing the node itself, use <MooTreeNode.clear> */ remove: function() { var p = this.parent; this._remove(); p.update(true); }, _remove: function() { // recursively remove this node's subnodes: var n = this.nodes; while (n.length) n[n.length-1]._remove(); // remove the node id from the control's index: delete this.control.index[this.id]; // remove this node's divs: this.div.main.destroy(); this.div.sub.destroy(); if (this.parent) { // remove this node from the parent's collection of nodes: var p = this.parent.nodes; p.erase(this); // in case we removed the parent's last node, flag it's current last node as being the last: if (p.length) p[p.length-1].last = true; } }, /* Property: clear Removes all child nodes under this node, without removing the node itself. To remove all nodes including this one, use <MooTreeNode.remove> */ clear: function() { this.control.disable(); while (this.nodes.length) this.nodes[this.nodes.length-1].remove(); this.control.enable(); }, /* Property: update Update the tree node's visual appearance. Parameters: recursive - boolean, defaults to false. If true, recursively updates all nodes beneath this one. invalidated - boolean, defaults to false. If true, updates only nodes that have been invalidated while the control has been disabled. */ update: function(recursive, invalidated) { var draw = true; if (!this.control.enabled) { // control is currently disabled, so we don't do any visual updates this.invalidated = true; draw = false; } if (invalidated) { if (!this.invalidated) { draw = false; // this one is still valid, don't draw } else { this.invalidated = false; // we're drawing this item now } } if (draw) { var x; // make selected, or not: this.div.main.className = 'mooTree_node' + (this.selected ? ' mooTree_selected' : ''); // update indentations: var p = this, i = ''; while (p.parent) { p = p.parent; i = this.getImg(p.last || !this.control.grid ? '' : 'I') + i; } this.div.indent.innerHTML = i; // update the text: x = this.div.text; x.empty(); x.appendText(this.text); if (this.color) x.style.color = this.color; // update the icon: this.div.icon.innerHTML = this.getImg( this.nodes.length ? ( this.open ? (this.openicon || this.icon || '_open') : (this.icon || '_closed') ) : ( this.icon || (this.control.mode == 'folders' ? '_closed' : '_doc') ) ); // update the plus/minus gadget: this.div.gadget.innerHTML = this.getImg( ( this.control.grid ? ( this.control.root == this ? (this.nodes.length ? 'R' : '') : (this.last?'L':'T') ) : '') + (this.nodes.length ? (this.open?'minus':'plus') : '') ); // show/hide subnodes: this.div.sub.style.display = this.open ? 'block' : 'none'; } // if recursively updating, update all child nodes: if (recursive) this.nodes.forEach( function(node) { node.update(true, invalidated); }); }, /* Property: getImg Creates a new image, in the form of HTML for a DIV element with appropriate style. You should not need to manually call this method. (though if for some reason you want to, you can) Parameters: name - the name of new image to create, defined by <MooTreeIcon> or located in an external file. Returns: The HTML for a new div Element. */ getImg: function(name) { var html = '<div class="mooTree_img"'; if (name != '') { var img = this.control.theme; var i = MooTreeIcon.indexOf(name); if (i == -1) { // custom (external) icon: var x = name.split('#'); img = x[0]; i = (x.length == 2 ? parseInt(x[1])-1 : 0); } html += ' style="background-image:url(' + img + '); background-position:-' + (i*18) + 'px 0px;"'; } html += "></div>"; return html; }, /* Property: toggle By default (with no arguments) this function toggles the node between expanded/collapsed. Can also be used to recursively expand/collapse all or part of the tree. Parameters: recursive - boolean, defaults to false. With recursive set to true, all child nodes are recursively toggle to this node's new state. state - boolean. If undefined, the node's state is toggled. If true or false, the node can be explicitly opened or closed. */ toggle: function(recursive, state) { this.open = (state === undefined ? !this.open : state); this.update(); this.onExpand(this.open); this.control.onExpand(this, this.open); if (recursive) this.nodes.forEach( function(node) { node.toggle(true, this.open); }, this); }, /* Property: select Called by <MooTreeControl> when the selection changes. You should not manually call this method - to set the selection, use the <MooTreeControl.select> method. */ select: function(state) { this.selected = state; this.update(); this.onSelect(state); }, /* Property: load Asynchronously load an XML structure into a node of this tree. Parameters: url - string, required, specifies the URL from which to load the XML document. vars - query string, optional. */ load: function(url, vars) { if (this.loading) return; // if this node is already loading, return this.loading = true; // flag this node as loading this.toggle(false, true); // expand the node to make the loader visible this.clear(); this.insert(this.control.loader); var f = function() { new Request({ method: 'GET', url: url, onSuccess: this._loaded.bind(this), onFailure: this._load_err.bind(this) }).send(vars || ''); }.bind(this).delay(20); //window.setTimeout(f.bind(this), 20); // allowing a small delay for the browser to draw the loader-icon. }, _loaded: function(text, xml) { // called on success - import nodes from the root element: this.control.disable(); this.clear(); this._import(xml.documentElement); this.control.enable(); this.loading = false; }, _import: function(e) { // import childnodes from an xml element: var n = e.childNodes; for (var i=0; i<n.length; i++) if (n[i].tagName == 'node') { var opt = {data:{}}; var a = n[i].attributes; for (var t=0; t<a.length; t++) { switch (a[t].name) { case 'text': case 'id': case 'icon': case 'openicon': case 'color': case 'open': opt[a[t].name] = a[t].value; break; default: opt.data[a[t].name] = a[t].value; } } var node = this.insert(opt); if (node.data.load) { node.open = false; // can't have a dynamically loading node that's already open! node.insert(this.control.loader); node.onExpand = function(state) { this.load(this.data.load); this.onExpand = new Function(); } } // recursively import subnodes of this node: if (n[i].childNodes.length) node._import(n[i]); } }, _load_err: function(req) { window.alert('Error loading: ' + this.text); } });
JavaScript
/** * SqueezeBox - Expandable Lightbox * * Allows to open various content as modal, * centered and animated box. * * Dependencies: MooTools 1.4 or newer * * Inspired by * ... Lokesh Dhakar - The original Lightbox v2 * * @version 1.3 * * @license MIT-style license * @author Harald Kirschner <mail [at] digitarald.de> * @author Rouven Weßling <me [at] rouvenwessling.de> * @copyright Author */ var SqueezeBox = { presets: { onOpen: function(){}, onClose: function(){}, onUpdate: function(){}, onResize: function(){}, onMove: function(){}, onShow: function(){}, onHide: function(){}, size: {x: 600, y: 450}, sizeLoading: {x: 200, y: 150}, marginInner: {x: 20, y: 20}, marginImage: {x: 50, y: 75}, handler: false, target: null, closable: true, closeBtn: true, zIndex: 65555, overlayOpacity: 0.7, classWindow: '', classOverlay: '', overlayFx: {}, resizeFx: {}, contentFx: {}, parse: false, // 'rel' parseSecure: false, shadow: true, overlay: true, document: null, ajaxOptions: {} }, initialize: function(presets) { if (this.options) return this; this.presets = Object.merge(this.presets, presets); this.doc = this.presets.document || document; this.options = {}; this.setOptions(this.presets).build(); this.bound = { window: this.reposition.bind(this, [null]), scroll: this.checkTarget.bind(this), close: this.close.bind(this), key: this.onKey.bind(this) }; this.isOpen = this.isLoading = false; return this; }, build: function() { this.overlay = new Element('div', { id: 'sbox-overlay', 'aria-hidden': 'true', styles: { zIndex: this.options.zIndex}, tabindex: -1 }); this.win = new Element('div', { id: 'sbox-window', role: 'dialog', 'aria-hidden': 'true', styles: {zIndex: this.options.zIndex + 2} }); if (this.options.shadow) { if (Browser.chrome || (Browser.safari && Browser.version >= 3) || (Browser.opera && Browser.version >= 10.5) || (Browser.firefox && Browser.version >= 3.5) || (Browser.ie && Browser.version >= 9)) { this.win.addClass('shadow'); } else if (!Browser.ie6) { var shadow = new Element('div', {'class': 'sbox-bg-wrap'}).inject(this.win); var relay = function(e) { this.overlay.fireEvent('click', [e]); }.bind(this); ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].each(function(dir) { new Element('div', {'class': 'sbox-bg sbox-bg-' + dir}).inject(shadow).addEvent('click', relay); }); } } this.content = new Element('div', {id: 'sbox-content'}).inject(this.win); this.closeBtn = new Element('a', {id: 'sbox-btn-close', href: '#', role: 'button'}).inject(this.win); this.closeBtn.setProperty('aria-controls', 'sbox-window'); this.fx = { overlay: new Fx.Tween(this.overlay, Object.merge({ property: 'opacity', onStart: Events.prototype.clearChain, duration: 250, link: 'cancel' }, this.options.overlayFx)).set(0), win: new Fx.Morph(this.win, Object.merge({ onStart: Events.prototype.clearChain, unit: 'px', duration: 750, transition: Fx.Transitions.Quint.easeOut, link: 'cancel', unit: 'px' }, this.options.resizeFx)), content: new Fx.Tween(this.content, Object.merge({ property: 'opacity', duration: 250, link: 'cancel' }, this.options.contentFx)).set(0) }; document.id(this.doc.body).adopt(this.overlay, this.win); }, assign: function(to, options) { return (document.id(to) || $$(to)).addEvent('click', function() { return !SqueezeBox.fromElement(this, options); }); }, open: function(subject, options) { this.initialize(); if (this.element != null) this.trash(); this.element = document.id(subject) || false; this.setOptions(Object.merge(this.presets, options || {})); if (this.element && this.options.parse) { var obj = this.element.getProperty(this.options.parse); if (obj && (obj = JSON.decode(obj, this.options.parseSecure))) this.setOptions(obj); } this.url = ((this.element) ? (this.element.get('href')) : subject) || this.options.url || ''; this.assignOptions(); var handler = handler || this.options.handler; if (handler) return this.setContent(handler, this.parsers[handler].call(this, true)); var ret = false; return this.parsers.some(function(parser, key) { var content = parser.call(this); if (content) { ret = this.setContent(key, content); return true; } return false; }, this); }, fromElement: function(from, options) { return this.open(from, options); }, assignOptions: function() { this.overlay.addClass(this.options.classOverlay); this.win.addClass(this.options.classWindow); }, close: function(e) { var stoppable = (typeOf(e) == 'domevent'); if (stoppable) e.stop(); if (!this.isOpen || (stoppable && !Function.from(this.options.closable).call(this, e))) return this; this.fx.overlay.start(0).chain(this.toggleOverlay.bind(this)); this.win.setProperty('aria-hidden', 'true'); this.fireEvent('onClose', [this.content]); this.trash(); this.toggleListeners(); this.isOpen = false; return this; }, trash: function() { this.element = this.asset = null; this.content.empty(); this.options = {}; this.removeEvents().setOptions(this.presets).callChain(); }, onError: function() { this.asset = null; this.setContent('string', this.options.errorMsg || 'An error occurred'); }, setContent: function(handler, content) { if (!this.handlers[handler]) return false; this.content.className = 'sbox-content-' + handler; this.applyTimer = this.applyContent.delay(this.fx.overlay.options.duration, this, this.handlers[handler].call(this, content)); if (this.overlay.retrieve('opacity')) return this; this.toggleOverlay(true); this.fx.overlay.start(this.options.overlayOpacity); return this.reposition(); }, applyContent: function(content, size) { if (!this.isOpen && !this.applyTimer) return; this.applyTimer = clearTimeout(this.applyTimer); this.hideContent(); if (!content) { this.toggleLoading(true); } else { if (this.isLoading) this.toggleLoading(false); this.fireEvent('onUpdate', [this.content], 20); } if (content) { if (['string', 'array'].contains(typeOf(content))) { this.content.set('html', content); } else if (!(content !== this.content && this.content.contains(content))) { this.content.adopt(content); } } this.callChain(); if (!this.isOpen) { this.toggleListeners(true); this.resize(size, true); this.isOpen = true; this.win.setProperty('aria-hidden', 'false'); this.fireEvent('onOpen', [this.content]); } else { this.resize(size); } }, resize: function(size, instantly) { this.showTimer = clearTimeout(this.showTimer || null); var box = this.doc.getSize(), scroll = this.doc.getScroll(); this.size = Object.merge((this.isLoading) ? this.options.sizeLoading : this.options.size, size); var parentSize = self.getSize(); if (this.size.x == parentSize.x) { this.size.y = this.size.y - 50; this.size.x = this.size.x - 20; } var to = { width: this.size.x, height: this.size.y, left: (scroll.x + (box.x - this.size.x - this.options.marginInner.x) / 2).toInt(), top: (scroll.y + (box.y - this.size.y - this.options.marginInner.y) / 2).toInt() }; this.hideContent(); if (!instantly) { this.fx.win.start(to).chain(this.showContent.bind(this)); } else { this.win.setStyles(to); this.showTimer = this.showContent.delay(50, this); } return this.reposition(); }, toggleListeners: function(state) { var fn = (state) ? 'addEvent' : 'removeEvent'; this.closeBtn[fn]('click', this.bound.close); this.overlay[fn]('click', this.bound.close); this.doc[fn]('keydown', this.bound.key)[fn]('mousewheel', this.bound.scroll); this.doc.getWindow()[fn]('resize', this.bound.window)[fn]('scroll', this.bound.window); }, toggleLoading: function(state) { this.isLoading = state; this.win[(state) ? 'addClass' : 'removeClass']('sbox-loading'); if (state) { this.win.setProperty('aria-busy', state); this.fireEvent('onLoading', [this.win]); } }, toggleOverlay: function(state) { if (this.options.overlay) { var full = this.doc.getSize().x; this.overlay.set('aria-hidden', (state) ? 'false' : 'true'); this.doc.body[(state) ? 'addClass' : 'removeClass']('body-overlayed'); if (state) { this.scrollOffset = this.doc.getWindow().getSize().x - full; } else { this.doc.body.setStyle('margin-right', ''); } } }, showContent: function() { if (this.content.get('opacity')) this.fireEvent('onShow', [this.win]); this.fx.content.start(1); }, hideContent: function() { if (!this.content.get('opacity')) this.fireEvent('onHide', [this.win]); this.fx.content.cancel().set(0); }, onKey: function(e) { switch (e.key) { case 'esc': this.close(e); case 'up': case 'down': return false; } }, checkTarget: function(e) { return e.target !== this.content && this.content.contains(e.target); }, reposition: function() { var size = this.doc.getSize(), scroll = this.doc.getScroll(), ssize = this.doc.getScrollSize(); var over = this.overlay.getStyles('height'); var j = parseInt(over.height); if (ssize.y > j && size.y >= j) { this.overlay.setStyles({ width: ssize.x + 'px', height: ssize.y + 'px' }); this.win.setStyles({ left: (scroll.x + (size.x - this.win.offsetWidth) / 2 - this.scrollOffset).toInt() + 'px', top: (scroll.y + (size.y - this.win.offsetHeight) / 2).toInt() + 'px' }); } return this.fireEvent('onMove', [this.overlay, this.win]); }, removeEvents: function(type){ if (!this.$events) return this; if (!type) this.$events = null; else if (this.$events[type]) this.$events[type] = null; return this; }, extend: function(properties) { return Object.append(this, properties); }, handlers: new Hash(), parsers: new Hash() }; SqueezeBox.extend(new Events(function(){})).extend(new Options(function(){})).extend(new Chain(function(){})); SqueezeBox.parsers.extend({ image: function(preset) { return (preset || (/\.(?:jpg|png|gif)$/i).test(this.url)) ? this.url : false; }, clone: function(preset) { if (document.id(this.options.target)) return document.id(this.options.target); if (this.element && !this.element.parentNode) return this.element; var bits = this.url.match(/#([\w-]+)$/); return (bits) ? document.id(bits[1]) : (preset ? this.element : false); }, ajax: function(preset) { return (preset || (this.url && !(/^(?:javascript|#)/i).test(this.url))) ? this.url : false; }, iframe: function(preset) { return (preset || this.url) ? this.url : false; }, string: function(preset) { return true; } }); SqueezeBox.handlers.extend({ image: function(url) { var size, tmp = new Image(); this.asset = null; tmp.onload = tmp.onabort = tmp.onerror = (function() { tmp.onload = tmp.onabort = tmp.onerror = null; if (!tmp.width) { this.onError.delay(10, this); return; } var box = this.doc.getSize(); box.x -= this.options.marginImage.x; box.y -= this.options.marginImage.y; size = {x: tmp.width, y: tmp.height}; for (var i = 2; i--;) { if (size.x > box.x) { size.y *= box.x / size.x; size.x = box.x; } else if (size.y > box.y) { size.x *= box.y / size.y; size.y = box.y; } } size.x = size.x.toInt(); size.y = size.y.toInt(); this.asset = document.id(tmp); tmp = null; this.asset.width = size.x; this.asset.height = size.y; this.applyContent(this.asset, size); }).bind(this); tmp.src = url; if (tmp && tmp.onload && tmp.complete) tmp.onload(); return (this.asset) ? [this.asset, size] : null; }, clone: function(el) { if (el) return el.clone(); return this.onError(); }, adopt: function(el) { if (el) return el; return this.onError(); }, ajax: function(url) { var options = this.options.ajaxOptions || {}; this.asset = new Request.HTML(Object.merge({ method: 'get', evalScripts: false }, this.options.ajaxOptions)).addEvents({ onSuccess: function(resp) { this.applyContent(resp); if (options.evalScripts !== null && !options.evalScripts) Browser.exec(this.asset.response.javascript); this.fireEvent('onAjax', [resp, this.asset]); this.asset = null; }.bind(this), onFailure: this.onError.bind(this) }); this.asset.send.delay(10, this.asset, [{url: url}]); }, iframe: function(url) { this.asset = new Element('iframe', Object.merge({ src: url, frameBorder: 0, width: this.options.size.x, height: this.options.size.y }, this.options.iframeOptions)); if (this.options.iframePreload) { this.asset.addEvent('load', function() { this.applyContent(this.asset.setStyle('display', '')); }.bind(this)); this.asset.setStyle('display', 'none').inject(this.content); return false; } return this.asset; }, string: function(str) { return str; } }); SqueezeBox.handlers.url = SqueezeBox.handlers.ajax; SqueezeBox.parsers.url = SqueezeBox.parsers.ajax; SqueezeBox.parsers.adopt = SqueezeBox.parsers.clone;
JavaScript
var joomlaupdate_error_callback = dummy_error_handler; var joomlaupdate_stat_inbytes = 0; var joomlaupdate_stat_outbytes = 0; var joomlaupdate_stat_files = 0; var joomlaupdate_factory = null; /** * An extremely simple error handler, dumping error messages to screen * * @param error The error message string */ function dummy_error_handler(error) { alert("ERROR:\n"+error); } /** * Performs an AJAX request and returns the parsed JSON output. * * @param data An object with the query data, e.g. a serialized form * @param successCallback A function accepting a single object parameter, called on success * @param errorCallback A function accepting a single string parameter, called on failure */ function doAjax(data, successCallback, errorCallback) { var json = JSON.stringify(data); if( joomlaupdate_password.length > 0 ) { json = AesCtr.encrypt( json, joomlaupdate_password, 128 ); } var post_data = 'json='+encodeURIComponent(json); var structure = { onSuccess: function(msg, responseXML) { // Initialize var junk = null; var message = ""; // Get rid of junk before the data var valid_pos = msg.indexOf('###'); if( valid_pos == -1 ) { // Valid data not found in the response msg = 'Invalid AJAX data:\n' + msg; if(joomlaupdate_error_callback != null) { joomlaupdate_error_callback(msg); } return; } else if( valid_pos != 0 ) { // Data is prefixed with junk junk = msg.substr(0, valid_pos); message = msg.substr(valid_pos); } else { message = msg; } message = message.substr(3); // Remove triple hash in the beginning // Get of rid of junk after the data var valid_pos = message.lastIndexOf('###'); message = message.substr(0, valid_pos); // Remove triple hash in the end // Decrypt if required if( joomlaupdate_password.length > 0 ) { try { var data = JSON.parse(message); } catch(err) { message = AesCtr.decrypt(message, joomlaupdate_password, 128); } } try { var data = JSON.parse(message); } catch(err) { var msg = err.message + "\n<br/>\n<pre>\n" + message + "\n</pre>"; if(joomlaupdate_error_callback != null) { joomlaupdate_error_callback(msg); } return; } // Call the callback function successCallback(data); }, onFailure: function(req) { var message = 'AJAX Loading Error: '+req.statusText; if(joomlaupdate_error_callback != null) { joomlaupdate_error_callback(msg); } } }; var ajax_object = null; structure.url = joomlaupdate_ajax_url; ajax_object = new Request(structure); ajax_object.send(post_data); } /** * Pings the update script (making sure its executable!!) * @return */ function pingUpdate() { // Reset variables joomlaupdate_stat_files = 0; joomlaupdate_stat_inbytes = 0; joomlaupdate_stat_outbytes = 0; // Do AJAX post var post = {task : 'ping'}; doAjax(post, function(data){ startUpdate(data); }); } /** * Starts the update * @return */ function startUpdate() { // Reset variables joomlaupdate_stat_files = 0; joomlaupdate_stat_inbytes = 0; joomlaupdate_stat_outbytes = 0; var post = { task : 'startRestore' }; doAjax(post, function(data){ processUpdateStep(data); }); } /** * Steps through the update * @param data * @return */ function processUpdateStep(data) { if(data.status == false) { if(joomlaupdate_error_callback != null) { joomlaupdate_error_callback(data.message); } } else { if(data.done) { joomlaupdate_factory = data.factory; window.location = joomlaupdate_return_url; } else { // Add data to variables joomlaupdate_stat_inbytes += data.bytesIn; joomlaupdate_stat_outbytes += data.bytesOut; joomlaupdate_stat_files += data.files; // Display data document.getElementById('extbytesin').innerHTML = joomlaupdate_stat_inbytes; document.getElementById('extbytesout').innerHTML = joomlaupdate_stat_outbytes; document.getElementById('extfiles').innerHTML = joomlaupdate_stat_files; // Do AJAX post post = { task: 'stepRestore', factory: data.factory }; doAjax(post, function(data){ processUpdateStep(data); }); } } } window.addEvent('domready', function() { pingUpdate(); });
JavaScript
window.addEvent('domready', function () { em = document.id('extraction_method'); if (em) { em.addEvent('change', function () { if(em.value == 'direct') { document.id('row_ftp_hostname').style.display = 'none'; document.id('row_ftp_port').style.display = 'none'; document.id('row_ftp_username').style.display = 'none'; document.id('row_ftp_password').style.display = 'none'; document.id('row_ftp_directory').style.display = 'none'; } else { document.id('row_ftp_hostname').style.display = 'table-row'; document.id('row_ftp_port').style.display = 'table-row'; document.id('row_ftp_username').style.display = 'table-row'; document.id('row_ftp_password').style.display = 'table-row'; document.id('row_ftp_directory').style.display = 'table-row'; } }); } });
JavaScript
/* * http://www.JSON.org/json2.js * 2009-09-29 * Public Domain. * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. * See http://www.JSON.org/js.html */ if(!this.JSON){this.JSON={};} (function(){function f(n){return n<10?'0'+n:n;} if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+ f(this.getUTCMonth()+1)+'-'+ f(this.getUTCDate())+'T'+ f(this.getUTCHours())+':'+ f(this.getUTCMinutes())+':'+ f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};} var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';} function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);} if(typeof rep==='function'){value=rep.call(holder,key,value);} switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';} gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';} v=partial.length===0?'[]':gap?'[\n'+gap+ partial.join(',\n'+gap)+'\n'+ mind+']':'['+partial.join(',')+']';gap=mind;return v;} if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}} v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+ mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}} if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;} rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');} return str('',{'':value});};} if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}} return reviver.call(holder,key,value);} cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+ ('0000'+a.charCodeAt(0).toString(16)).slice(-4);});} if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;} throw new SyntaxError('JSON.parse');};}}());
JavaScript
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* AES implementation in JavaScript (c) Chris Veness 2005-2010 */ /* - see http://csrc.nist.gov/publications/PubsFIPS.html#197 */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ var Aes = {}; // Aes namespace /** * AES Cipher function: encrypt 'input' state with Rijndael algorithm * applies Nr rounds (10/12/14) using key schedule w for 'add round key' stage * * @param {Number[]} input 16-byte (128-bit) input state array * @param {Number[][]} w Key schedule as 2D byte-array (Nr+1 x Nb bytes) * @returns {Number[]} Encrypted output state array */ Aes.Cipher = function(input, w) { // main Cipher function [§5.1] var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES) var Nr = w.length/Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys var state = [[],[],[],[]]; // initialise 4xNb byte-array 'state' with input [§3.4] for (var i=0; i<4*Nb; i++) state[i%4][Math.floor(i/4)] = input[i]; state = Aes.AddRoundKey(state, w, 0, Nb); for (var round=1; round<Nr; round++) { state = Aes.SubBytes(state, Nb); state = Aes.ShiftRows(state, Nb); state = Aes.MixColumns(state, Nb); state = Aes.AddRoundKey(state, w, round, Nb); } state = Aes.SubBytes(state, Nb); state = Aes.ShiftRows(state, Nb); state = Aes.AddRoundKey(state, w, Nr, Nb); var output = new Array(4*Nb); // convert state to 1-d array before returning [§3.4] for (var i=0; i<4*Nb; i++) output[i] = state[i%4][Math.floor(i/4)]; return output; } /** * Perform Key Expansion to generate a Key Schedule * * @param {Number[]} key Key as 16/24/32-byte array * @returns {Number[][]} Expanded key schedule as 2D byte-array (Nr+1 x Nb bytes) */ Aes.KeyExpansion = function(key) { // generate Key Schedule (byte-array Nr+1 x Nb) from Key [§5.2] var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES) var Nk = key.length/4 // key length (in words): 4/6/8 for 128/192/256-bit keys var Nr = Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys var w = new Array(Nb*(Nr+1)); var temp = new Array(4); for (var i=0; i<Nk; i++) { var r = [key[4*i], key[4*i+1], key[4*i+2], key[4*i+3]]; w[i] = r; } for (var i=Nk; i<(Nb*(Nr+1)); i++) { w[i] = new Array(4); for (var t=0; t<4; t++) temp[t] = w[i-1][t]; if (i % Nk == 0) { temp = Aes.SubWord(Aes.RotWord(temp)); for (var t=0; t<4; t++) temp[t] ^= Aes.Rcon[i/Nk][t]; } else if (Nk > 6 && i%Nk == 4) { temp = Aes.SubWord(temp); } for (var t=0; t<4; t++) w[i][t] = w[i-Nk][t] ^ temp[t]; } return w; } /* * ---- remaining routines are private, not called externally ---- */ Aes.SubBytes = function(s, Nb) { // apply SBox to state S [§5.1.1] for (var r=0; r<4; r++) { for (var c=0; c<Nb; c++) s[r][c] = Aes.Sbox[s[r][c]]; } return s; } Aes.ShiftRows = function(s, Nb) { // shift row r of state S left by r bytes [§5.1.2] var t = new Array(4); for (var r=1; r<4; r++) { for (var c=0; c<4; c++) t[c] = s[r][(c+r)%Nb]; // shift into temp copy for (var c=0; c<4; c++) s[r][c] = t[c]; // and copy back } // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES): return s; // see asmaes.sourceforge.net/rijndael/rijndaelImplementation.pdf } Aes.MixColumns = function(s, Nb) { // combine bytes of each col of state S [§5.1.3] for (var c=0; c<4; c++) { var a = new Array(4); // 'a' is a copy of the current column from 's' var b = new Array(4); // 'b' is a•{02} in GF(2^8) for (var i=0; i<4; i++) { a[i] = s[i][c]; b[i] = s[i][c]&0x80 ? s[i][c]<<1 ^ 0x011b : s[i][c]<<1; } // a[n] ^ b[n] is a•{03} in GF(2^8) s[0][c] = b[0] ^ a[1] ^ b[1] ^ a[2] ^ a[3]; // 2*a0 + 3*a1 + a2 + a3 s[1][c] = a[0] ^ b[1] ^ a[2] ^ b[2] ^ a[3]; // a0 * 2*a1 + 3*a2 + a3 s[2][c] = a[0] ^ a[1] ^ b[2] ^ a[3] ^ b[3]; // a0 + a1 + 2*a2 + 3*a3 s[3][c] = a[0] ^ b[0] ^ a[1] ^ a[2] ^ b[3]; // 3*a0 + a1 + a2 + 2*a3 } return s; } Aes.AddRoundKey = function(state, w, rnd, Nb) { // xor Round Key into state S [§5.1.4] for (var r=0; r<4; r++) { for (var c=0; c<Nb; c++) state[r][c] ^= w[rnd*4+c][r]; } return state; } Aes.SubWord = function(w) { // apply SBox to 4-byte word w for (var i=0; i<4; i++) w[i] = Aes.Sbox[w[i]]; return w; } Aes.RotWord = function(w) { // rotate 4-byte word w left by one byte var tmp = w[0]; for (var i=0; i<3; i++) w[i] = w[i+1]; w[3] = tmp; return w; } // Sbox is pre-computed multiplicative inverse in GF(2^8) used in SubBytes and KeyExpansion [§5.1.1] Aes.Sbox = [0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15, 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75, 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84, 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf, 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8, 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2, 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08, 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a, 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e, 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16]; // Rcon is Round Constant used for the Key Expansion [1st col is 2^(r-1) in GF(2^8)] [§5.2] Aes.Rcon = [ [0x00, 0x00, 0x00, 0x00], [0x01, 0x00, 0x00, 0x00], [0x02, 0x00, 0x00, 0x00], [0x04, 0x00, 0x00, 0x00], [0x08, 0x00, 0x00, 0x00], [0x10, 0x00, 0x00, 0x00], [0x20, 0x00, 0x00, 0x00], [0x40, 0x00, 0x00, 0x00], [0x80, 0x00, 0x00, 0x00], [0x1b, 0x00, 0x00, 0x00], [0x36, 0x00, 0x00, 0x00] ]; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* AES Counter-mode implementation in JavaScript (c) Chris Veness 2005-2010 */ /* - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ var AesCtr = {}; // AesCtr namespace /** * Encrypt a text using AES encryption in Counter mode of operation * * Unicode multi-byte character safe * * @param {String} plaintext Source text to be encrypted * @param {String} password The password to use to generate a key * @param {Number} nBits Number of bits to be used in the key (128, 192, or 256) * @returns {string} Encrypted text */ AesCtr.encrypt = function(plaintext, password, nBits) { var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES if (!(nBits==128 || nBits==192 || nBits==256)) return ''; // standard allows 128/192/256 bit keys plaintext = Utf8.encode(plaintext); password = Utf8.encode(password); //var t = new Date(); // timer // use AES itself to encrypt password to get cipher key (using plain password as source for key // expansion) - gives us well encrypted key var nBytes = nBits/8; // no bytes in key var pwBytes = new Array(nBytes); for (var i=0; i<nBytes; i++) { pwBytes[i] = isNaN(password.charCodeAt(i)) ? 0 : password.charCodeAt(i); } var key = Aes.Cipher(pwBytes, Aes.KeyExpansion(pwBytes)); // gives us 16-byte key key = key.concat(key.slice(0, nBytes-16)); // expand key to 16/24/32 bytes long // initialise counter block (NIST SP800-38A §B.2): millisecond time-stamp for nonce in 1st 8 bytes, // block counter in 2nd 8 bytes var counterBlock = new Array(blockSize); var nonce = (new Date()).getTime(); // timestamp: milliseconds since 1-Jan-1970 var nonceSec = Math.floor(nonce/1000); var nonceMs = nonce%1000; // encode nonce with seconds in 1st 4 bytes, and (repeated) ms part filling 2nd 4 bytes for (var i=0; i<4; i++) counterBlock[i] = (nonceSec >>> i*8) & 0xff; for (var i=0; i<4; i++) counterBlock[i+4] = nonceMs & 0xff; // and convert it to a string to go on the front of the ciphertext var ctrTxt = ''; for (var i=0; i<8; i++) ctrTxt += String.fromCharCode(counterBlock[i]); // generate key schedule - an expansion of the key into distinct Key Rounds for each round var keySchedule = Aes.KeyExpansion(key); var blockCount = Math.ceil(plaintext.length/blockSize); var ciphertxt = new Array(blockCount); // ciphertext as array of strings for (var b=0; b<blockCount; b++) { // set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes) // done in two stages for 32-bit ops: using two words allows us to go past 2^32 blocks (68GB) for (var c=0; c<4; c++) counterBlock[15-c] = (b >>> c*8) & 0xff; for (var c=0; c<4; c++) counterBlock[15-c-4] = (b/0x100000000 >>> c*8) var cipherCntr = Aes.Cipher(counterBlock, keySchedule); // -- encrypt counter block -- // block size is reduced on final block var blockLength = b<blockCount-1 ? blockSize : (plaintext.length-1)%blockSize+1; var cipherChar = new Array(blockLength); for (var i=0; i<blockLength; i++) { // -- xor plaintext with ciphered counter char-by-char -- cipherChar[i] = cipherCntr[i] ^ plaintext.charCodeAt(b*blockSize+i); cipherChar[i] = String.fromCharCode(cipherChar[i]); } ciphertxt[b] = cipherChar.join(''); } // Array.join is more efficient than repeated string concatenation in IE var ciphertext = ctrTxt + ciphertxt.join(''); ciphertext = Base64.encode(ciphertext); // encode in base64 //alert((new Date()) - t); return ciphertext; } /** * Decrypt a text encrypted by AES in counter mode of operation * * @param {String} ciphertext Source text to be encrypted * @param {String} password The password to use to generate a key * @param {Number} nBits Number of bits to be used in the key (128, 192, or 256) * @returns {String} Decrypted text */ AesCtr.decrypt = function(ciphertext, password, nBits) { var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES if (!(nBits==128 || nBits==192 || nBits==256)) return ''; // standard allows 128/192/256 bit keys ciphertext = Base64.decode(ciphertext); password = Utf8.encode(password); //var t = new Date(); // timer // use AES to encrypt password (mirroring encrypt routine) var nBytes = nBits/8; // no bytes in key var pwBytes = new Array(nBytes); for (var i=0; i<nBytes; i++) { pwBytes[i] = isNaN(password.charCodeAt(i)) ? 0 : password.charCodeAt(i); } var key = Aes.Cipher(pwBytes, Aes.KeyExpansion(pwBytes)); key = key.concat(key.slice(0, nBytes-16)); // expand key to 16/24/32 bytes long // recover nonce from 1st 8 bytes of ciphertext var counterBlock = new Array(8); ctrTxt = ciphertext.slice(0, 8); for (var i=0; i<8; i++) counterBlock[i] = ctrTxt.charCodeAt(i); // generate key schedule var keySchedule = Aes.KeyExpansion(key); // separate ciphertext into blocks (skipping past initial 8 bytes) var nBlocks = Math.ceil((ciphertext.length-8) / blockSize); var ct = new Array(nBlocks); for (var b=0; b<nBlocks; b++) ct[b] = ciphertext.slice(8+b*blockSize, 8+b*blockSize+blockSize); ciphertext = ct; // ciphertext is now array of block-length strings // plaintext will get generated block-by-block into array of block-length strings var plaintxt = new Array(ciphertext.length); for (var b=0; b<nBlocks; b++) { // set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes) for (var c=0; c<4; c++) counterBlock[15-c] = ((b) >>> c*8) & 0xff; for (var c=0; c<4; c++) counterBlock[15-c-4] = (((b+1)/0x100000000-1) >>> c*8) & 0xff; var cipherCntr = Aes.Cipher(counterBlock, keySchedule); // encrypt counter block var plaintxtByte = new Array(ciphertext[b].length); for (var i=0; i<ciphertext[b].length; i++) { // -- xor plaintxt with ciphered counter byte-by-byte -- plaintxtByte[i] = cipherCntr[i] ^ ciphertext[b].charCodeAt(i); plaintxtByte[i] = String.fromCharCode(plaintxtByte[i]); } plaintxt[b] = plaintxtByte.join(''); } // join array of blocks into single plaintext string var plaintext = plaintxt.join(''); plaintext = Utf8.decode(plaintext); // decode from UTF8 back to Unicode multi-byte chars //alert((new Date()) - t); return plaintext; } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Base64 class: Base 64 encoding / decoding (c) Chris Veness 2002-2010 */ /* note: depends on Utf8 class */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ var Base64 = {}; // Base64 namespace Base64.code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; /** * Encode string into Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648] * (instance method extending String object). As per RFC 4648, no newlines are added. * * @param {String} str The string to be encoded as base-64 * @param {Boolean} [utf8encode=false] Flag to indicate whether str is Unicode string to be encoded * to UTF8 before conversion to base64; otherwise string is assumed to be 8-bit characters * @returns {String} Base64-encoded string */ Base64.encode = function(str, utf8encode) { // http://tools.ietf.org/html/rfc4648 utf8encode = (typeof utf8encode == 'undefined') ? false : utf8encode; var o1, o2, o3, bits, h1, h2, h3, h4, e=[], pad = '', c, plain, coded; var b64 = Base64.code; plain = utf8encode ? str.encodeUTF8() : str; c = plain.length % 3; // pad string to length of multiple of 3 if (c > 0) { while (c++ < 3) { pad += '='; plain += '\0'; } } // note: doing padding here saves us doing special-case packing for trailing 1 or 2 chars for (c=0; c<plain.length; c+=3) { // pack three octets into four hexets o1 = plain.charCodeAt(c); o2 = plain.charCodeAt(c+1); o3 = plain.charCodeAt(c+2); bits = o1<<16 | o2<<8 | o3; h1 = bits>>18 & 0x3f; h2 = bits>>12 & 0x3f; h3 = bits>>6 & 0x3f; h4 = bits & 0x3f; // use hextets to index into code string e[c/3] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } coded = e.join(''); // join() is far faster than repeated string concatenation in IE // replace 'A's from padded nulls with '='s coded = coded.slice(0, coded.length-pad.length) + pad; return coded; } /** * Decode string from Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648] * (instance method extending String object). As per RFC 4648, newlines are not catered for. * * @param {String} str The string to be decoded from base-64 * @param {Boolean} [utf8decode=false] Flag to indicate whether str is Unicode string to be decoded * from UTF8 after conversion from base64 * @returns {String} decoded string */ Base64.decode = function(str, utf8decode) { utf8decode = (typeof utf8decode == 'undefined') ? false : utf8decode; var o1, o2, o3, h1, h2, h3, h4, bits, d=[], plain, coded; var b64 = Base64.code; coded = utf8decode ? str.decodeUTF8() : str; for (var c=0; c<coded.length; c+=4) { // unpack four hexets into three octets h1 = b64.indexOf(coded.charAt(c)); h2 = b64.indexOf(coded.charAt(c+1)); h3 = b64.indexOf(coded.charAt(c+2)); h4 = b64.indexOf(coded.charAt(c+3)); bits = h1<<18 | h2<<12 | h3<<6 | h4; o1 = bits>>>16 & 0xff; o2 = bits>>>8 & 0xff; o3 = bits & 0xff; d[c/4] = String.fromCharCode(o1, o2, o3); // check for padding if (h4 == 0x40) d[c/4] = String.fromCharCode(o1, o2); if (h3 == 0x40) d[c/4] = String.fromCharCode(o1); } plain = d.join(''); // join() is far faster than repeated string concatenation in IE return utf8decode ? plain.decodeUTF8() : plain; } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Utf8 class: encode / decode between multi-byte Unicode characters and UTF-8 multiple */ /* single-byte character encoding (c) Chris Veness 2002-2010 */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ var Utf8 = {}; // Utf8 namespace /** * Encode multi-byte Unicode string into utf-8 multiple single-byte characters * (BMP / basic multilingual plane only) * * Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars * * @param {String} strUni Unicode string to be encoded as UTF-8 * @returns {String} encoded string */ Utf8.encode = function(strUni) { // use regular expressions & String.replace callback function for better efficiency // than procedural approaches var strUtf = strUni.replace( /[\u0080-\u07ff]/g, // U+0080 - U+07FF => 2 bytes 110yyyyy, 10zzzzzz function(c) { var cc = c.charCodeAt(0); return String.fromCharCode(0xc0 | cc>>6, 0x80 | cc&0x3f); } ); strUtf = strUtf.replace( /[\u0800-\uffff]/g, // U+0800 - U+FFFF => 3 bytes 1110xxxx, 10yyyyyy, 10zzzzzz function(c) { var cc = c.charCodeAt(0); return String.fromCharCode(0xe0 | cc>>12, 0x80 | cc>>6&0x3F, 0x80 | cc&0x3f); } ); return strUtf; } /** * Decode utf-8 encoded string back into multi-byte Unicode characters * * @param {String} strUtf UTF-8 string to be decoded back to Unicode * @returns {String} decoded string */ Utf8.decode = function(strUtf) { var strUni = strUtf.replace( /[\u00c0-\u00df][\u0080-\u00bf]/g, // 2-byte chars function(c) { // (note parentheses for precence) var cc = (c.charCodeAt(0)&0x1f)<<6 | c.charCodeAt(1)&0x3f; return String.fromCharCode(cc); } ); strUni = strUni.replace( /[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, // 3-byte chars function(c) { // (note parentheses for precence) var cc = ((c.charCodeAt(0)&0x0f)<<12) | ((c.charCodeAt(1)&0x3f)<<6) | ( c.charCodeAt(2)&0x3f); return String.fromCharCode(cc); } ); return strUni; } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
JavaScript
/** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * Some state variables for the overrider */ Joomla.overrider = { states : { refreshing: false, refreshed: false, counter: 0, searchstring: '', searchtype: 'value' } }; /** * Method for refreshing the database cache of known language strings via Ajax * * @return void * * @since 2.5 */ Joomla.overrider.refreshCache = function() { var req = new Request.JSON({ method: 'post', url: 'index.php?option=com_languages&task=strings.refresh&format=json', onRequest: function() { this.states.refreshing = true; document.id('refresh-status').reveal(); }.bind(this), onSuccess: function(r) { if (r.error && r.message) { alert(r.message); } if (r.messages) { Joomla.renderMessages(r.messages); } document.id('refresh-status').dissolve(); this.states.refreshing = false; }.bind(this), onFailure: function(xhr) { alert(Joomla.JText._('COM_LANGUAGES_VIEW_OVERRIDE_REQUEST_ERROR')); document.id('refresh-status').dissolve(); }.bind(this), onError: function(text, error) { alert(error + "\n\n" + text); document.id('refresh-status').dissolve(); }.bind(this) }); req.post(); }; /** * Method for searching known language strings via Ajax * * @param int more Determines the limit start of the results * * @return void * * @since 2.5 */ Joomla.overrider.searchStrings = function(more) { // Prevent searching if the cache is refreshed at the moment if (this.states.refreshing) { return; } // Only update the used searchstring and searchtype if the search button // was used to start the search (that will be the case if 'more' is null) if (!more) { this.states.searchstring = document.id('jform_searchstring').value; this.states.searchtype = 'value'; if (document.id('jform_searchtype0').checked) { this.states.searchtype = 'constant'; } } if (!this.states.searchstring) { document.id('jform_searchstring').addClass('invalid'); return; } var req = new Request.JSON({ method: 'post', url: 'index.php?option=com_languages&task=strings.search&format=json', onRequest: function() { if (more) { // If 'more' is greater than 0 we have already displayed some results for // the current searchstring, so display the spinner at the more link document.id('more-results').addClass('overrider-spinner'); } else { // Otherwise it is a new searchstring and we have to remove all previous results first document.id('more-results').set('style', 'display:none;'); var children = $$('#results-container div.language-results'); children.destroy(); document.id('results-container').addClass('overrider-spinner').reveal(); } }.bind(this), onSuccess: function(r) { if (r.error && r.message) { alert(r.message); } if (r.messages) { Joomla.renderMessages(r.messages); } if(r.data) { if(r.data.results) { this.insertResults(r.data.results); } if(r.data.more) { // If there are more results than the sent ones // display the more link this.states.more = r.data.more; document.id('more-results').reveal(); } else { document.id('more-results').set('style', 'display:none;'); } } document.id('results-container').removeClass('overrider-spinner'); document.id('more-results').removeClass('overrider-spinner'); }.bind(this), onFailure: function(xhr) { alert(Joomla.JText._('COM_LANGUAGES_VIEW_OVERRIDE_REQUEST_ERROR')); document.id('results-container').removeClass('overrider-spinner'); document.id('more-results').removeClass('overrider-spinner'); }.bind(this), onError: function(text, error) { alert(error + "\n\n" + text); document.id('results-container').removeClass('overrider-spinner'); document.id('more-results').removeClass('overrider-spinner'); }.bind(this) }); req.post('searchstring=' + this.states.searchstring + '&searchtype=' + this.states.searchtype + '&more=' + more); }; /** * Method inserting the received results into the results container * * @param array results An array of search result objects * * @return void * * @since 2.5 */ Joomla.overrider.insertResults = function(results) { // For creating an individual ID for each result we use a counter this.states.counter = this.states.counter + 1; // Create a container into which all the results will be inserted var results_div = new Element('div', { id: 'language-results' + this.states.counter, 'class': 'language-results', style: 'display:none;' }); // Create some elements for each result and insert it into the container Array.each(results, function (item, index) { var div = new Element('div', { 'class': 'result row' + index%2, onclick: 'Joomla.overrider.selectString(' + this.states.counter + index + ');', }); var key = new Element('div', { id: 'override_key' + this.states.counter + index, 'class': 'result-key', html: item.constant, title: item.file }); key.inject(div); var string = new Element('div', { id: 'override_string' + this.states.counter + index, 'class': 'result-string', html: item.string }); string.inject(div); div.inject(results_div); }, this); // If there aren't any results display an appropriate message if(!results.length) { var noresult = new Element('div', { html: Joomla.JText._('COM_LANGUAGES_VIEW_OVERRIDE_NO_RESULTS') }); noresult.inject(results_div); } // Finally insert the container afore the more link and reveal it results_div.inject(document.id('more-results'), 'before'); document.id('language-results' + this.states.counter).reveal(); }; /** * Inserts a specific constant/value pair into the form and scrolls the page back to the top * * @param int id The ID of the element which was selected for insertion * * @return void * * @since 2.5 */ Joomla.overrider.selectString = function(id) { document.id('jform_key').value = document.id('override_key' + id).get('html'); document.id('jform_override').value = document.id('override_string' + id).get('html'); new Fx.Scroll(window).toTop(); };
JavaScript
/** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ window.addEvent('domready', function(){ var ajax_structure = { onSuccess: function(msg, responseXML) { try { var updateInfoList = JSON.decode(msg, true); } catch(e) { // An error occured document.id('plg_quickicon_extensionupdate').getElements('span').set('html', plg_quickicon_extensionupdate_text.ERROR); } if (updateInfoList instanceof Array) { if (updateInfoList.length < 1) { // No updates document.id('plg_quickicon_extensionupdate').getElements('span').set('html', plg_quickicon_extensionupdate_text.UPTODATE); } else { var updateString = plg_quickicon_extensionupdate_text.UPDATEFOUND.replace("%s", updateInfoList.length); document.id('plg_quickicon_extensionupdate').getElements('span').set('html', updateString); } } else { // An error occured document.id('plg_quickicon_extensionupdate').getElements('span').set('html', plg_quickicon_extensionupdate_text.ERROR); } }, onFailure: function(req) { // An error occured document.id('plg_quickicon_extensionupdate').getElements('span').set('html', plg_quickicon_extensionupdate_text.ERROR); }, url: plg_quickicon_extensionupdate_ajax_url }; ajax_object = new Request(ajax_structure); ajax_object.send('eid=0&skip=700'); });
JavaScript
// ------------------------------------------------------------------- // Switch Content Script- By Dynamic Drive, available at: http://www.dynamicdrive.com // Created: Jan 5th, 2007 // April 5th, 07: Added ability to persist content states by x days versus just session only // March 27th, 08': Added ability for certain headers to get its contents remotely from an external file via Ajax (2 variables below to customize) // ------------------------------------------------------------------- var switchcontent_ajax_msg='<em>Loading Ajax content...</em>' //Customize message to show while fetching Ajax content (if applicable) var switchcontent_ajax_bustcache=true //Bust cache and refresh fetched Ajax contents when page is reloaded/ viewed again? function switchcontent(className, filtertag){ this.className=className this.collapsePrev=false //Default: Collapse previous content each time this.persistType="none" //Default: Disable persistence //Limit type of element to scan for on page for switch contents if 2nd function parameter is defined, for efficiency sake (ie: "div") this.filter_content_tag=(typeof filtertag!="undefined")? filtertag.toLowerCase() : "" this.ajaxheaders={} //object to hold path to ajax content for corresponding header (ie: ajaxheaders["header1"]='external.htm') } switchcontent.prototype.setStatus=function(openHTML, closeHTML){ //PUBLIC: Set open/ closing HTML indicator. Optional this.statusOpen=openHTML this.statusClosed=closeHTML } switchcontent.prototype.setColor=function(openColor, closeColor){ //PUBLIC: Set open/ closing color of switch header. Optional this.colorOpen=openColor this.colorClosed=closeColor } switchcontent.prototype.setPersist=function(bool, days){ //PUBLIC: Enable/ disable persistence. Default is false. if (bool==true){ //if enable persistence if (typeof days=="undefined") //if session only this.persistType="session" else{ //else if non session persistent this.persistType="days" this.persistDays=parseInt(days) } } else this.persistType="none" } switchcontent.prototype.collapsePrevious=function(bool){ //PUBLIC: Enable/ disable collapse previous content. Default is false. this.collapsePrev=bool } switchcontent.prototype.setContent=function(index, filepath){ //PUBLIC: Set path to ajax content for corresponding header based on header index this.ajaxheaders["header"+index]=filepath } switchcontent.prototype.sweepToggle=function(setting){ //PUBLIC: Expand/ contract all contents method. (Values: "contract"|"expand") if (typeof this.headers!="undefined" && this.headers.length>0){ //if there are switch contents defined on the page for (var i=0; i<this.headers.length; i++){ if (setting=="expand") this.expandcontent(this.headers[i]) //expand each content else if (setting=="contract") this.contractcontent(this.headers[i]) //contract each content } } } switchcontent.prototype.defaultExpanded=function(){ //PUBLIC: Set contents that should be expanded by default when the page loads (ie: defaultExpanded(0,2,3)). Persistence if enabled overrides this setting. var expandedindices=[] //Array to hold indices (position) of content to be expanded by default //Loop through function arguments, and store each one within array //Two test conditions: 1) End of Arguments array, or 2) If "collapsePrev" is enabled, only the first entered index (as only 1 content can be expanded at any time) for (var i=0; (!this.collapsePrev && i<arguments.length) || (this.collapsePrev && i==0); i++) expandedindices[expandedindices.length]=arguments[i] this.expandedindices=expandedindices.join(",") //convert array into a string of the format: "0,2,3" for later parsing by script } //PRIVATE: Sets color of switch header. switchcontent.prototype.togglecolor=function(header, status){ if (typeof this.colorOpen!="undefined") header.style.color=status } //PRIVATE: Sets status indicator HTML of switch header. switchcontent.prototype.togglestatus=function(header, status){ if (typeof this.statusOpen!="undefined") header.firstChild.innerHTML=status } //PRIVATE: Contracts a content based on its corresponding header entered switchcontent.prototype.contractcontent=function(header){ var innercontent=document.getElementById(header.id.replace("-title", "")) //Reference content container for this header innercontent.style.display="none" this.togglestatus(header, this.statusClosed) this.togglecolor(header, this.colorClosed) } //PRIVATE: Expands a content based on its corresponding header entered switchcontent.prototype.expandcontent=function(header){ var innercontent=document.getElementById(header.id.replace("-title", "")) if (header.ajaxstatus=="waiting"){//if this is an Ajax header AND remote content hasn't already been fetched switchcontent.connect(header.ajaxfile, header) } innercontent.style.display="block" this.togglestatus(header, this.statusOpen) this.togglecolor(header, this.colorOpen) } // ------------------------------------------------------------------- // PRIVATE: toggledisplay(header)- Toggles between a content being expanded or contracted // If "Collapse Previous" is enabled, contracts previous open content before expanding current // ------------------------------------------------------------------- switchcontent.prototype.toggledisplay=function(header){ var innercontent=document.getElementById(header.id.replace("-title", "")) //Reference content container for this header if (innercontent.style.display=="block") this.contractcontent(header) else{ this.expandcontent(header) if (this.collapsePrev && typeof this.prevHeader!="undefined" && this.prevHeader.id!=header.id) // If "Collapse Previous" is enabled and there's a previous open content this.contractcontent(this.prevHeader) //Contract that content first } if (this.collapsePrev) this.prevHeader=header //Set current expanded content as the next "Previous Content" } // ------------------------------------------------------------------- // PRIVATE: collectElementbyClass()- Searches and stores all switch contents (based on shared class name) and their headers in two arrays // Each content should carry an unique ID, and for its header, an ID equal to "CONTENTID-TITLE" // ------------------------------------------------------------------- switchcontent.prototype.collectElementbyClass=function(classname){ //Returns an array containing DIVs with specified classname var classnameRE=new RegExp("(^|\\s+)"+classname+"($|\\s+)", "i") //regular expression to screen for classname within element this.headers=[], this.innercontents=[] if (this.filter_content_tag!="") //If user defined limit type of element to scan for to a certain element (ie: "div" only) var allelements=document.getElementsByTagName(this.filter_content_tag) else //else, scan all elements on the page! var allelements=document.all? document.all : document.getElementsByTagName("*") for (var i=0; i<allelements.length; i++){ if (typeof allelements[i].className=="string" && allelements[i].className.search(classnameRE)!=-1){ if (document.getElementById(allelements[i].id+"-title")!=null){ //if header exists for this inner content this.headers[this.headers.length]=document.getElementById(allelements[i].id+"-title") //store reference to header intended for this inner content this.innercontents[this.innercontents.length]=allelements[i] //store reference to this inner content } } } } //PRIVATE: init()- Initializes Switch Content function (collapse contents by default unless exception is found) switchcontent.prototype.init=function(){ var instanceOf=this this.collectElementbyClass(this.className) //Get all headers and its corresponding content based on shared class name of contents if (this.headers.length==0) //If no headers are present (no contents to switch), just exit return //If admin has changed number of days to persist from current cookie records, reset persistence by deleting cookie if (this.persistType=="days" && (parseInt(switchcontent.getCookie(this.className+"_dtrack"))!=this.persistDays)) switchcontent.setCookie(this.className+"_d", "", -1) //delete cookie // Get ids of open contents below. Four possible scenerios: // 1) Session only persistence is enabled AND corresponding cookie contains a non blank ("") string // 2) Regular (in days) persistence is enabled AND corresponding cookie contains a non blank ("") string // 3) If there are contents that should be enabled by default (even if persistence is enabled and this IS the first page load) // 4) Default to no contents should be expanded on page load ("" value) var opencontents_ids=(this.persistType=="session" && switchcontent.getCookie(this.className)!="")? ','+switchcontent.getCookie(this.className)+',' : (this.persistType=="days" && switchcontent.getCookie(this.className+"_d")!="")? ','+switchcontent.getCookie(this.className+"_d")+',' : (this.expandedindices)? ','+this.expandedindices+',' : "" for (var i=0; i<this.headers.length; i++){ //BEGIN FOR LOOP if (typeof this.ajaxheaders["header"+i]!="undefined"){ //if this is an Ajax header this.headers[i].ajaxstatus='waiting' //two possible statuses: "waiting" and "loaded" this.headers[i].ajaxfile=this.ajaxheaders["header"+i] } if (typeof this.statusOpen!="undefined") //If open/ closing HTML indicator is enabled/ set this.headers[i].innerHTML='<span class="status"></span>'+this.headers[i].innerHTML //Add a span element to original HTML to store indicator if (opencontents_ids.indexOf(','+i+',')!=-1){ //if index "i" exists within cookie string or default-enabled string (i=position of the content to expand) this.expandcontent(this.headers[i]) //Expand each content per stored indices (if ""Collapse Previous" is set, only one content) if (this.collapsePrev) //If "Collapse Previous" set this.prevHeader=this.headers[i] //Indicate the expanded content's corresponding header as the last clicked on header (for logic purpose) } else //else if no indices found in stored string this.contractcontent(this.headers[i]) //Contract each content by default this.headers[i].onclick=function(){instanceOf.toggledisplay(this)} } //END FOR LOOP switchcontent.dotask(window, function(){instanceOf.rememberpluscleanup()}, "unload") //Call persistence method onunload } // ------------------------------------------------------------------- // PRIVATE: rememberpluscleanup()- Stores the indices of content that are expanded inside session only cookie // If "Collapse Previous" is enabled, only 1st expanded content index is stored // ------------------------------------------------------------------- //Function to store index of opened ULs relative to other ULs in Tree into cookie: switchcontent.prototype.rememberpluscleanup=function(){ //Define array to hold ids of open content that should be persisted //Default to just "none" to account for the case where no contents are open when user leaves the page (and persist that): var opencontents=new Array("none") for (var i=0; i<this.innercontents.length; i++){ //If persistence enabled, content in question is expanded, and either "Collapse Previous" is disabled, or if enabled, this is the first expanded content if (this.persistType!="none" && this.innercontents[i].style.display=="block" && (!this.collapsePrev || (this.collapsePrev && opencontents.length<2))) opencontents[opencontents.length]=i //save the index of the opened UL (relative to the entire list of ULs) as an array element this.headers[i].onclick=null //Cleanup code } if (opencontents.length>1) //If there exists open content to be persisted opencontents.shift() //Boot the "none" value from the array, so all it contains are the ids of the open contents if (typeof this.statusOpen!="undefined") this.statusOpen=this.statusClosed=null //Cleanup code if (this.persistType=="session") //if session only cookie set switchcontent.setCookie(this.className, opencontents.join(",")) //populate cookie with indices of open contents: classname=1,2,3,etc else if (this.persistType=="days" && typeof this.persistDays=="number"){ //if persistent cookie set instead switchcontent.setCookie(this.className+"_d", opencontents.join(","), this.persistDays) //populate cookie with indices of open contents switchcontent.setCookie(this.className+"_dtrack", this.persistDays, this.persistDays) //also remember number of days to persist (int) } } // ------------------------------------------------------------------- // A few utility functions below: // ------------------------------------------------------------------- switchcontent.dotask=function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload) var tasktype=(window.addEventListener)? tasktype : "on"+tasktype if (target.addEventListener) target.addEventListener(tasktype, functionref, false) else if (target.attachEvent) target.attachEvent(tasktype, functionref) } switchcontent.connect=function(pageurl, header){ var page_request = false var bustcacheparameter="" if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) try { page_request = new ActiveXObject("Msxml2.XMLHTTP") } catch (e){ try{ page_request = new ActiveXObject("Microsoft.XMLHTTP") } catch (e){} } } else if (window.XMLHttpRequest) // if Mozilla, Safari etc page_request = new XMLHttpRequest() else return false page_request.onreadystatechange=function(){switchcontent.loadpage(page_request, header)} if (switchcontent_ajax_bustcache) //if bust caching of external page bustcacheparameter=(pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime() page_request.open('GET', pageurl+bustcacheparameter, true) page_request.send(null) } switchcontent.loadpage=function(page_request, header){ var innercontent=document.getElementById(header.id.replace("-title", "")) //Reference content container for this header innercontent.innerHTML=switchcontent_ajax_msg //Display "fetching page message" if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){ innercontent.innerHTML=page_request.responseText header.ajaxstatus="loaded" } } switchcontent.getCookie=function(Name){ var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair if (document.cookie.match(re)) //if cookie found return document.cookie.match(re)[0].split("=")[1] //return its value return "" } switchcontent.setCookie=function(name, value, days){ if (typeof days!="undefined"){ //if set persistent cookie var expireDate = new Date() var expstring=expireDate.setDate(expireDate.getDate()+days) document.cookie = name+"="+value+"; expires="+expireDate.toGMTString() } else //else if this is a session only cookie document.cookie = name+"="+value }
JavaScript
/************************************************************************************************************ JS Calendar Copyright (C) September 2006 DTHMLGoodies.com, Alf Magne Kalleland This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Dhtmlgoodies.com., hereby disclaims all copyright interest in this script written by Alf Magne Kalleland. Alf Magne Kalleland, 2006 Owner of DHTMLgoodies.com ************************************************************************************************************/ /* Update log: (C) www.dhtmlgoodies.com, September 2005 Version 1.2, November 8th - 2005 - Added <iframe> background in IE Version 1.3, November 12th - 2005 - Fixed top bar position in Opera 7 Version 1.4, December 28th - 2005 - Support for Spanish and Portuguese Version 1.5, January 18th - 2006 - Fixed problem with next-previous buttons after a month has been selected from dropdown Version 1.6, February 22nd - 2006 - Added variable which holds the path to images. Format todays date at the bottom by use of the todayStringFormat variable Pick todays date by clicking on todays date at the bottom of the calendar Version 2.0 May, 25th - 2006 - Added support for time(hour and minutes) and changing year and hour when holding mouse over + and - options. (i.e. instead of click) Version 2.1 July, 2nd - 2006 - Added support for more date formats(example: d.m.yyyy, i.e. one letter day and month). // Modifications by Gregg Buntin Version 2.1.1 8/9/2007 gfb - Add switch to turn off Year Span Selection This allows me to only have this year & next year in the drop down Version 2.1.2 8/30/2007 gfb - Add switch to start week on Sunday Add switch to turn off week number display Fix bug when using on an HTTPS page */ var turnOffYearSpan = false; // true = Only show This Year and Next, false = show +/- 5 years var weekStartsOnSunday = false; // true = Start the week on Sunday, false = start the week on Monday var showWeekNumber = false; // true = show week number, false = do not show week number var languageCode = 'en'; // Possible values: en,ge,no,nl,es,pt-br,fr // en = english, ge = german, no = norwegian,nl = dutch, es = spanish, pt-br = portuguese, fr = french, da = danish, hu = hungarian(Use UTF-8 doctype for hungarian) var calendar_display_time = true; // Format of current day at the bottom of the calendar // [todayString] = the value of todayString // [dayString] = day of week (examle: mon, tue, wed...) // [UCFdayString] = day of week (examle: Mon, Tue, Wed...) ( First letter in uppercase) // [day] = Day of month, 1..31 // [monthString] = Name of current month // [year] = Current year var todayStringFormat = '[todayString] [UCFdayString]. [day]. [monthString] [year]'; var pathToImages = 'images/'; // Relative to your HTML file var speedOfSelectBoxSliding = 200; // Milliseconds between changing year and hour when holding mouse over "-" and "+" - lower value = faster var intervalSelectBox_minutes = 5; // Minute select box - interval between each option (5 = default) var calendar_offsetTop = 0; // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype var calendar_offsetLeft = 0; // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype var calendarDiv = false; var MSIE = false; var Opera = false; if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)MSIE=true; if(navigator.userAgent.indexOf('Opera')>=0)Opera=true; switch(languageCode){ case "en": /* English */ var monthArray = ['January','February','March','April','May','June','July','August','September','October','November','December']; var monthArrayShort = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; var dayArray = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']; var weekString = 'Week'; var todayString = ''; break; case "ge": /* German */ var monthArray = ['Januar','Februar','M�rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember']; var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez']; var dayArray = ['Mon','Die','Mit','Don','Fre','Sam','Son']; var weekString = 'Woche'; var todayString = 'Heute'; break; case "no": /* Norwegian */ var monthArray = ['Januar','Februar','Mars','April','Mai','Juni','Juli','August','September','Oktober','November','Desember']; var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Des']; var dayArray = ['Man','Tir','Ons','Tor','Fre','L&oslash;r','S&oslash;n']; var weekString = 'Uke'; var todayString = 'Dagen i dag er'; break; case "nl": /* Dutch */ var monthArray = ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December']; var monthArrayShort = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec']; var dayArray = ['Ma','Di','Wo','Do','Vr','Za','Zo']; var weekString = 'Week'; var todayString = 'Vandaag'; break; case "es": /* Spanish */ var monthArray = ['Enero','Febrero','Marzo','April','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre']; var monthArrayShort =['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic']; var dayArray = ['Lun','Mar','Mie','Jue','Vie','Sab','Dom']; var weekString = 'Semana'; var todayString = 'Hoy es'; break; case "pt-br": /* Brazilian portuguese (pt-br) */ var monthArray = ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro']; var monthArrayShort = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez']; var dayArray = ['Seg','Ter','Qua','Qui','Sex','S&aacute;b','Dom']; var weekString = 'Sem.'; var todayString = 'Hoje &eacute;'; break; case "fr": /* French */ var monthArray = ['Janvier','F�vrier','Mars','Avril','Mai','Juin','Juillet','Ao�t','Septembre','Octobre','Novembre','D�cembre']; var monthArrayShort = ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Aou','Sep','Oct','Nov','Dec']; var dayArray = ['Lun','Mar','Mer','Jeu','Ven','Sam','Dim']; var weekString = 'Sem'; var todayString = "Aujourd'hui"; break; case "da": /*Danish*/ var monthArray = ['januar','februar','marts','april','maj','juni','juli','august','september','oktober','november','december']; var monthArrayShort = ['jan','feb','mar','apr','maj','jun','jul','aug','sep','okt','nov','dec']; var dayArray = ['man','tirs','ons','tors','fre','l&oslash;r','s&oslash;n']; var weekString = 'Uge'; var todayString = 'I dag er den'; break; case "hu": /* Hungarian - Remember to use UTF-8 encoding, i.e. the <meta> tag */ var monthArray = ['Január','Február','Március','�?prilis','Május','Június','Július','Augusztus','Szeptember','Október','November','December']; var monthArrayShort = ['Jan','Feb','Márc','�?pr','Máj','Jún','Júl','Aug','Szep','Okt','Nov','Dec']; var dayArray = ['Hé','Ke','Sze','Cs','Pé','Szo','Vas']; var weekString = 'Hét'; var todayString = 'Mai nap'; break; case "it": /* Italian*/ var monthArray = ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre']; var monthArrayShort = ['Gen','Feb','Mar','Apr','Mag','Giu','Lugl','Ago','Set','Ott','Nov','Dic']; var dayArray = ['Lun',';Mar','Mer','Gio','Ven','Sab','Dom']; var weekString = 'Settimana'; var todayString = 'Oggi &egrave; il'; break; case "sv": /* Swedish */ var monthArray = ['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December']; var monthArrayShort = ['Jan','Feb','Mar','Apr','Maj','Jun','Jul','Aug','Sep','Okt','Nov','Dec']; var dayArray = ['M&aring;n','Tis','Ons','Tor','Fre','L&ouml;r','S&ouml;n']; var weekString = 'Vecka'; var todayString = 'Idag &auml;r det den'; break; case "cz": /* Czech */ var monthArray = ['leden','&#250;nor','b&#345;ezen','duben','kv&#283;ten','&#269;erven','&#269;ervenec','srpen','z&#225;&#345;&#237;','&#345;&#237;jen','listopad','prosinec']; var monthArrayShort = ['led','&#250;n','b&#345;','dub','kv&#283;','&#269;er','&#269;er-ec','srp','z&#225;&#345;','&#345;&#237;j','list','pros']; var dayArray = ['Pon','&#218;t','St','&#268;t','P&#225;','So','Ne']; var weekString = 't&#253;den'; var todayString = ''; break; } if (weekStartsOnSunday) { var tempDayName = dayArray[6]; for(var theIx = 6; theIx > 0; theIx--) { dayArray[theIx] = dayArray[theIx-1]; } dayArray[0] = tempDayName; } var daysInMonthArray = [31,28,31,30,31,30,31,31,30,31,30,31]; var currentMonth; var currentYear; var currentHour; var currentMinute; var calendarContentDiv; var returnDateTo; var returnFormat; var activeSelectBoxMonth; var activeSelectBoxYear; var activeSelectBoxHour; var activeSelectBoxMinute; var iframeObj = false; //// fix for EI frame problem on time dropdowns 09/30/2006 var iframeObj2 =false; function EIS_FIX_EI1(where2fixit) { if(!iframeObj2)return; iframeObj2.style.display = 'block'; iframeObj2.style.height =document.getElementById(where2fixit).offsetHeight+1; iframeObj2.style.width=document.getElementById(where2fixit).offsetWidth; iframeObj2.style.left=getleftPos(document.getElementById(where2fixit))+1-calendar_offsetLeft; iframeObj2.style.top=getTopPos(document.getElementById(where2fixit))-document.getElementById(where2fixit).offsetHeight-calendar_offsetTop; } function EIS_Hide_Frame() { if(iframeObj2)iframeObj2.style.display = 'none';} //// fix for EI frame problem on time dropdowns 09/30/2006 var returnDateToYear; var returnDateToMonth; var returnDateToDay; var returnDateToHour; var returnDateToMinute; var inputYear; var inputMonth; var inputDay; var inputHour; var inputMinute; var calendarDisplayTime = false; var selectBoxHighlightColor = '#D60808'; // Highlight color of select boxes var selectBoxRolloverBgColor = '#E2EBED'; // Background color on drop down lists(rollover) var selectBoxMovementInProgress = false; var activeSelectBox = false; function cancelCalendarEvent() { return false; } function isLeapYear(inputYear) { if(inputYear%400==0||(inputYear%4==0&&inputYear%100!=0)) return true; return false; } var activeSelectBoxMonth = false; var activeSelectBoxDirection = false; function highlightMonthYear() { if(activeSelectBoxMonth)activeSelectBoxMonth.className=''; activeSelectBox = this; if(this.className=='monthYearActive'){ this.className=''; }else{ this.className = 'monthYearActive'; activeSelectBoxMonth = this; } if(this.innerHTML.indexOf('-')>=0 || this.innerHTML.indexOf('+')>=0){ if(this.className=='monthYearActive') selectBoxMovementInProgress = true; else selectBoxMovementInProgress = false; if(this.innerHTML.indexOf('-')>=0)activeSelectBoxDirection = -1; else activeSelectBoxDirection = 1; }else selectBoxMovementInProgress = false; } function showMonthDropDown() { if(document.getElementById('monthDropDown').style.display=='block'){ document.getElementById('monthDropDown').style.display='none'; //// fix for EI frame problem on time dropdowns 09/30/2006 EIS_Hide_Frame(); }else{ document.getElementById('monthDropDown').style.display='block'; document.getElementById('yearDropDown').style.display='none'; document.getElementById('hourDropDown').style.display='none'; document.getElementById('minuteDropDown').style.display='none'; if (MSIE) { EIS_FIX_EI1('monthDropDown')} //// fix for EI frame problem on time dropdowns 09/30/2006 } } function showYearDropDown() { if(document.getElementById('yearDropDown').style.display=='block'){ document.getElementById('yearDropDown').style.display='none'; //// fix for EI frame problem on time dropdowns 09/30/2006 EIS_Hide_Frame(); }else{ document.getElementById('yearDropDown').style.display='block'; document.getElementById('monthDropDown').style.display='none'; document.getElementById('hourDropDown').style.display='none'; document.getElementById('minuteDropDown').style.display='none'; if (MSIE) { EIS_FIX_EI1('yearDropDown')} //// fix for EI frame problem on time dropdowns 09/30/2006 } } function showHourDropDown() { if(document.getElementById('hourDropDown').style.display=='block'){ document.getElementById('hourDropDown').style.display='none'; //// fix for EI frame problem on time dropdowns 09/30/2006 EIS_Hide_Frame(); }else{ document.getElementById('hourDropDown').style.display='block'; document.getElementById('monthDropDown').style.display='none'; document.getElementById('yearDropDown').style.display='none'; document.getElementById('minuteDropDown').style.display='none'; if (MSIE) { EIS_FIX_EI1('hourDropDown')} //// fix for EI frame problem on time dropdowns 09/30/2006 } } function showMinuteDropDown() { if(document.getElementById('minuteDropDown').style.display=='block'){ document.getElementById('minuteDropDown').style.display='none'; //// fix for EI frame problem on time dropdowns 09/30/2006 EIS_Hide_Frame(); }else{ document.getElementById('minuteDropDown').style.display='block'; document.getElementById('monthDropDown').style.display='none'; document.getElementById('yearDropDown').style.display='none'; document.getElementById('hourDropDown').style.display='none'; if (MSIE) { EIS_FIX_EI1('minuteDropDown')} //// fix for EI frame problem on time dropdowns 09/30/2006 } } function selectMonth() { document.getElementById('calendar_month_txt').innerHTML = this.innerHTML currentMonth = this.id.replace(/[^\d]/g,''); document.getElementById('monthDropDown').style.display='none'; //// fix for EI frame problem on time dropdowns 09/30/2006 EIS_Hide_Frame(); for(var no=0;no<monthArray.length;no++){ document.getElementById('monthDiv_'+no).style.color=''; } this.style.color = selectBoxHighlightColor; activeSelectBoxMonth = this; writeCalendarContent(); } function selectHour() { document.getElementById('calendar_hour_txt').innerHTML = this.innerHTML currentHour = this.innerHTML.replace(/[^\d]/g,''); document.getElementById('hourDropDown').style.display='none'; //// fix for EI frame problem on time dropdowns 09/30/2006 EIS_Hide_Frame(); if(activeSelectBoxHour){ activeSelectBoxHour.style.color=''; } activeSelectBoxHour=this; this.style.color = selectBoxHighlightColor; } function selectMinute() { document.getElementById('calendar_minute_txt').innerHTML = this.innerHTML currentMinute = this.innerHTML.replace(/[^\d]/g,''); document.getElementById('minuteDropDown').style.display='none'; //// fix for EI frame problem on time dropdowns 09/30/2006 EIS_Hide_Frame(); if(activeSelectBoxMinute){ activeSelectBoxMinute.style.color=''; } activeSelectBoxMinute=this; this.style.color = selectBoxHighlightColor; } function selectYear() { document.getElementById('calendar_year_txt').innerHTML = this.innerHTML currentYear = this.innerHTML.replace(/[^\d]/g,''); document.getElementById('yearDropDown').style.display='none'; //// fix for EI frame problem on time dropdowns 09/30/2006 EIS_Hide_Frame(); if(activeSelectBoxYear){ activeSelectBoxYear.style.color=''; } activeSelectBoxYear=this; this.style.color = selectBoxHighlightColor; writeCalendarContent(); } function switchMonth() { if(this.src.indexOf('left')>=0){ currentMonth=currentMonth-1;; if(currentMonth<0){ currentMonth=11; currentYear=currentYear-1; } }else{ currentMonth=currentMonth+1;; if(currentMonth>11){ currentMonth=0; currentYear=currentYear/1+1; } } writeCalendarContent(); } function createMonthDiv(){ var div = document.createElement('DIV'); div.className='monthYearPicker'; div.id = 'monthPicker'; for(var no=0;no<monthArray.length;no++){ var subDiv = document.createElement('DIV'); subDiv.innerHTML = monthArray[no]; subDiv.onmouseover = highlightMonthYear; subDiv.onmouseout = highlightMonthYear; subDiv.onclick = selectMonth; subDiv.id = 'monthDiv_' + no; subDiv.style.width = '56px'; subDiv.onselectstart = cancelCalendarEvent; div.appendChild(subDiv); if(currentMonth && currentMonth==no){ subDiv.style.color = selectBoxHighlightColor; activeSelectBoxMonth = subDiv; } } return div; } function changeSelectBoxYear(e,inputObj) { if(!inputObj)inputObj =this; var yearItems = inputObj.parentNode.getElementsByTagName('DIV'); if(inputObj.innerHTML.indexOf('-')>=0){ var startYear = yearItems[1].innerHTML/1 -1; if(activeSelectBoxYear){ activeSelectBoxYear.style.color=''; } }else{ var startYear = yearItems[1].innerHTML/1 +1; if(activeSelectBoxYear){ activeSelectBoxYear.style.color=''; } } for(var no=1;no<yearItems.length-1;no++){ yearItems[no].innerHTML = startYear+no-1; yearItems[no].id = 'yearDiv' + (startYear/1+no/1-1); } if(activeSelectBoxYear){ activeSelectBoxYear.style.color=''; if(document.getElementById('yearDiv'+currentYear)){ activeSelectBoxYear = document.getElementById('yearDiv'+currentYear); activeSelectBoxYear.style.color=selectBoxHighlightColor;; } } } function changeSelectBoxHour(e,inputObj) { if(!inputObj)inputObj = this; var hourItems = inputObj.parentNode.getElementsByTagName('DIV'); if(inputObj.innerHTML.indexOf('-')>=0){ var startHour = hourItems[1].innerHTML/1 -1; if(!startHour || startHour<0)startHour=0; if(activeSelectBoxHour){ activeSelectBoxHour.style.color=''; } }else{ var startHour = hourItems[1].innerHTML/1 +1; if(!startHour || startHour>14)startHour = 14; if(activeSelectBoxHour){ activeSelectBoxHour.style.color=''; } } var prefix = ''; for(var no=1;no<hourItems.length-1;no++){ if((startHour/1 + no/1) < 11)prefix = '0'; else prefix = ''; hourItems[no].innerHTML = prefix + (startHour+no-1); hourItems[no].id = 'hourDiv' + (startHour/1+no/1-1); } if(activeSelectBoxHour){ activeSelectBoxHour.style.color=''; if(document.getElementById('hourDiv'+currentHour)){ activeSelectBoxHour = document.getElementById('hourDiv'+currentHour); activeSelectBoxHour.style.color=selectBoxHighlightColor;; } } } function updateYearDiv() { var yearSpan = 5; if (turnOffYearSpan) { yearSpan = 0; } var div = document.getElementById('yearDropDown'); var yearItems = div.getElementsByTagName('DIV'); for(var no=1;no<yearItems.length-1;no++){ yearItems[no].innerHTML = currentYear/1 -yearSpan + no; if(currentYear==(currentYear/1 -yearSpan + no)){ yearItems[no].style.color = selectBoxHighlightColor; activeSelectBoxYear = yearItems[no]; }else{ yearItems[no].style.color = ''; } } } function updateMonthDiv() { for(no=0;no<12;no++){ document.getElementById('monthDiv_' + no).style.color = ''; } document.getElementById('monthDiv_' + currentMonth).style.color = selectBoxHighlightColor; activeSelectBoxMonth = document.getElementById('monthDiv_' + currentMonth); } function updateHourDiv() { var div = document.getElementById('hourDropDown'); var hourItems = div.getElementsByTagName('DIV'); var addHours = 0; if((currentHour/1 -6 + 1)<0){ addHours = (currentHour/1 -6 + 1)*-1; } for(var no=1;no<hourItems.length-1;no++){ var prefix=''; if((currentHour/1 -6 + no + addHours) < 10)prefix='0'; hourItems[no].innerHTML = prefix + (currentHour/1 -6 + no + addHours); if(currentHour==(currentHour/1 -6 + no)){ hourItems[no].style.color = selectBoxHighlightColor; activeSelectBoxHour = hourItems[no]; }else{ hourItems[no].style.color = ''; } } } function updateMinuteDiv() { for(no=0;no<60;no+=intervalSelectBox_minutes){ var prefix = ''; if(no<10)prefix = '0'; document.getElementById('minuteDiv_' + prefix + no).style.color = ''; } if(document.getElementById('minuteDiv_' + currentMinute)){ document.getElementById('minuteDiv_' + currentMinute).style.color = selectBoxHighlightColor; activeSelectBoxMinute = document.getElementById('minuteDiv_' + currentMinute); } } function createYearDiv() { if(!document.getElementById('yearDropDown')){ var div = document.createElement('DIV'); div.className='monthYearPicker'; }else{ var div = document.getElementById('yearDropDown'); var subDivs = div.getElementsByTagName('DIV'); for(var no=0;no<subDivs.length;no++){ subDivs[no].parentNode.removeChild(subDivs[no]); } } var d = new Date(); if(currentYear){ d.setFullYear(currentYear); } var startYear = d.getFullYear()/1 - 5; var yearSpan = 10; if (! turnOffYearSpan) { var subDiv = document.createElement('DIV'); subDiv.innerHTML = '&nbsp;&nbsp;- '; subDiv.onclick = changeSelectBoxYear; subDiv.onmouseover = highlightMonthYear; subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;}; subDiv.onselectstart = cancelCalendarEvent; div.appendChild(subDiv); } else { startYear = d.getFullYear()/1 - 0; yearSpan = 2; } for(var no=startYear;no<(startYear+yearSpan);no++){ var subDiv = document.createElement('DIV'); subDiv.innerHTML = no; subDiv.onmouseover = highlightMonthYear; subDiv.onmouseout = highlightMonthYear; subDiv.onclick = selectYear; subDiv.id = 'yearDiv' + no; subDiv.onselectstart = cancelCalendarEvent; div.appendChild(subDiv); if(currentYear && currentYear==no){ subDiv.style.color = selectBoxHighlightColor; activeSelectBoxYear = subDiv; } } if (! turnOffYearSpan) { var subDiv = document.createElement('DIV'); subDiv.innerHTML = '&nbsp;&nbsp;+ '; subDiv.onclick = changeSelectBoxYear; subDiv.onmouseover = highlightMonthYear; subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;}; subDiv.onselectstart = cancelCalendarEvent; div.appendChild(subDiv); } return div; } /* This function creates the hour div at the bottom bar */ function slideCalendarSelectBox() { if(selectBoxMovementInProgress){ if(activeSelectBox.parentNode.id=='hourDropDown'){ changeSelectBoxHour(false,activeSelectBox); } if(activeSelectBox.parentNode.id=='yearDropDown'){ changeSelectBoxYear(false,activeSelectBox); } } setTimeout('slideCalendarSelectBox()',speedOfSelectBoxSliding); } function createHourDiv() { if(!document.getElementById('hourDropDown')){ var div = document.createElement('DIV'); div.className='monthYearPicker'; }else{ var div = document.getElementById('hourDropDown'); var subDivs = div.getElementsByTagName('DIV'); for(var no=0;no<subDivs.length;no++){ subDivs[no].parentNode.removeChild(subDivs[no]); } } if(!currentHour)currentHour=0; var startHour = currentHour/1; if(startHour>14)startHour=14; var subDiv = document.createElement('DIV'); subDiv.innerHTML = '&nbsp;&nbsp;- '; subDiv.onclick = changeSelectBoxHour; subDiv.onmouseover = highlightMonthYear; subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;}; subDiv.onselectstart = cancelCalendarEvent; div.appendChild(subDiv); for(var no=startHour;no<startHour+10;no++){ var prefix = ''; if(no/1<10)prefix='0'; var subDiv = document.createElement('DIV'); subDiv.innerHTML = prefix + no; subDiv.onmouseover = highlightMonthYear; subDiv.onmouseout = highlightMonthYear; subDiv.onclick = selectHour; subDiv.id = 'hourDiv' + no; subDiv.onselectstart = cancelCalendarEvent; div.appendChild(subDiv); if(currentYear && currentYear==no){ subDiv.style.color = selectBoxHighlightColor; activeSelectBoxYear = subDiv; } } var subDiv = document.createElement('DIV'); subDiv.innerHTML = '&nbsp;&nbsp;+ '; subDiv.onclick = changeSelectBoxHour; subDiv.onmouseover = highlightMonthYear; subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;}; subDiv.onselectstart = cancelCalendarEvent; div.appendChild(subDiv); return div; } /* This function creates the minute div at the bottom bar */ function createMinuteDiv() { if(!document.getElementById('minuteDropDown')){ var div = document.createElement('DIV'); div.className='monthYearPicker'; }else{ var div = document.getElementById('minuteDropDown'); var subDivs = div.getElementsByTagName('DIV'); for(var no=0;no<subDivs.length;no++){ subDivs[no].parentNode.removeChild(subDivs[no]); } } var startMinute = 0; var prefix = ''; for(var no=startMinute;no<60;no+=intervalSelectBox_minutes){ if(no<10)prefix='0'; else prefix = ''; var subDiv = document.createElement('DIV'); subDiv.innerHTML = prefix + no; subDiv.onmouseover = highlightMonthYear; subDiv.onmouseout = highlightMonthYear; subDiv.onclick = selectMinute; subDiv.id = 'minuteDiv_' + prefix + no; subDiv.onselectstart = cancelCalendarEvent; div.appendChild(subDiv); if(currentYear && currentYear==no){ subDiv.style.color = selectBoxHighlightColor; activeSelectBoxYear = subDiv; } } return div; } function highlightSelect() { if(this.className=='selectBoxTime'){ this.className = 'selectBoxTimeOver'; this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_time_over.gif'; }else if(this.className=='selectBoxTimeOver'){ this.className = 'selectBoxTime'; this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_time.gif'; } if(this.className=='selectBox'){ this.className = 'selectBoxOver'; this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_over.gif'; }else if(this.className=='selectBoxOver'){ this.className = 'selectBox'; this.getElementsByTagName('IMG')[0].src = pathToImages + 'down.gif'; } } function highlightArrow() { if(this.src.indexOf('over')>=0){ if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left.gif'; if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right.gif'; }else{ if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left_over.gif'; if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right_over.gif'; } } function highlightClose() { if(this.src.indexOf('over')>=0){ this.src = pathToImages + 'close.gif'; }else{ this.src = pathToImages + 'close_over.gif'; } } function closeCalendar(){ document.getElementById('yearDropDown').style.display='none'; document.getElementById('monthDropDown').style.display='none'; document.getElementById('hourDropDown').style.display='none'; document.getElementById('minuteDropDown').style.display='none'; calendarDiv.style.display='none'; if(iframeObj){ iframeObj.style.display='none'; //// //// fix for EI frame problem on time dropdowns 09/30/2006 EIS_Hide_Frame();} if(activeSelectBoxMonth)activeSelectBoxMonth.className=''; if(activeSelectBoxYear)activeSelectBoxYear.className=''; } function writeTopBar() { var topBar = document.createElement('DIV'); topBar.className = 'topBar'; topBar.id = 'topBar'; calendarDiv.appendChild(topBar); // Left arrow var leftDiv = document.createElement('DIV'); leftDiv.style.marginRight = '1px'; var img = document.createElement('IMG'); img.src = pathToImages + 'left.gif'; img.onmouseover = highlightArrow; img.onclick = switchMonth; img.onmouseout = highlightArrow; leftDiv.appendChild(img); topBar.appendChild(leftDiv); if(Opera)leftDiv.style.width = '16px'; // Right arrow var rightDiv = document.createElement('DIV'); rightDiv.style.marginRight = '1px'; var img = document.createElement('IMG'); img.src = pathToImages + 'right.gif'; img.onclick = switchMonth; img.onmouseover = highlightArrow; img.onmouseout = highlightArrow; rightDiv.appendChild(img); if(Opera)rightDiv.style.width = '16px'; topBar.appendChild(rightDiv); // Month selector var monthDiv = document.createElement('DIV'); monthDiv.id = 'monthSelect'; monthDiv.onmouseover = highlightSelect; monthDiv.onmouseout = highlightSelect; monthDiv.onclick = showMonthDropDown; var span = document.createElement('SPAN'); span.innerHTML = monthArray[currentMonth]; span.id = 'calendar_month_txt'; monthDiv.appendChild(span); var img = document.createElement('IMG'); img.src = pathToImages + 'down.gif'; img.style.position = 'absolute'; img.style.right = '0px'; monthDiv.appendChild(img); monthDiv.className = 'selectBox'; if(Opera){ img.style.cssText = 'float:right;position:relative'; img.style.position = 'relative'; img.style.styleFloat = 'right'; } topBar.appendChild(monthDiv); var monthPicker = createMonthDiv(); monthPicker.style.left = '37px'; monthPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px'; monthPicker.style.width ='60px'; monthPicker.id = 'monthDropDown'; calendarDiv.appendChild(monthPicker); // Year selector var yearDiv = document.createElement('DIV'); yearDiv.onmouseover = highlightSelect; yearDiv.onmouseout = highlightSelect; yearDiv.onclick = showYearDropDown; var span = document.createElement('SPAN'); span.innerHTML = currentYear; span.id = 'calendar_year_txt'; yearDiv.appendChild(span); topBar.appendChild(yearDiv); var img = document.createElement('IMG'); img.src = pathToImages + 'down.gif'; yearDiv.appendChild(img); yearDiv.className = 'selectBox'; if(Opera){ yearDiv.style.width = '50px'; img.style.cssText = 'float:right'; img.style.position = 'relative'; img.style.styleFloat = 'right'; } var yearPicker = createYearDiv(); yearPicker.style.left = '113px'; yearPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px'; yearPicker.style.width = '35px'; yearPicker.id = 'yearDropDown'; calendarDiv.appendChild(yearPicker); var img = document.createElement('IMG'); img.src = pathToImages + 'close.gif'; img.style.styleFloat = 'right'; img.onmouseover = highlightClose; img.onmouseout = highlightClose; img.onclick = closeCalendar; topBar.appendChild(img); if(!document.all){ img.style.position = 'absolute'; img.style.right = '2px'; } } function writeCalendarContent() { var calendarContentDivExists = true; if(!calendarContentDiv){ calendarContentDiv = document.createElement('DIV'); calendarDiv.appendChild(calendarContentDiv); calendarContentDivExists = false; } currentMonth = currentMonth/1; var d = new Date(); d.setFullYear(currentYear); d.setDate(1); d.setMonth(currentMonth); var dayStartOfMonth = d.getDay(); if (! weekStartsOnSunday) { if(dayStartOfMonth==0)dayStartOfMonth=7; dayStartOfMonth--; } document.getElementById('calendar_year_txt').innerHTML = currentYear; document.getElementById('calendar_month_txt').innerHTML = monthArray[currentMonth]; document.getElementById('calendar_hour_txt').innerHTML = currentHour; document.getElementById('calendar_minute_txt').innerHTML = currentMinute; var existingTable = calendarContentDiv.getElementsByTagName('TABLE'); if(existingTable.length>0){ calendarContentDiv.removeChild(existingTable[0]); } var calTable = document.createElement('TABLE'); calTable.width = '100%'; calTable.cellSpacing = '0'; calendarContentDiv.appendChild(calTable); var calTBody = document.createElement('TBODY'); calTable.appendChild(calTBody); var row = calTBody.insertRow(-1); row.className = 'calendar_week_row'; if (showWeekNumber) { var cell = row.insertCell(-1); cell.innerHTML = weekString; cell.className = 'calendar_week_column'; cell.style.backgroundColor = selectBoxRolloverBgColor; } for(var no=0;no<dayArray.length;no++){ var cell = row.insertCell(-1); cell.innerHTML = dayArray[no]; } var row = calTBody.insertRow(-1); row.className = 'calendar_day_row'; if (showWeekNumber) { var cell = row.insertCell(-1); cell.className = 'calendar_week_column'; cell.style.backgroundColor = selectBoxRolloverBgColor; var week = getWeek(currentYear,currentMonth,1); cell.innerHTML = week; // Week } for(var no=0;no<dayStartOfMonth;no++){ var cell = row.insertCell(-1); cell.innerHTML = '&nbsp;'; } var colCounter = dayStartOfMonth; var daysInMonth = daysInMonthArray[currentMonth]; if(daysInMonth==28){ if(isLeapYear(currentYear))daysInMonth=29; } for(var no=1;no<=daysInMonth;no++){ d.setDate(no-1); if(colCounter>0 && colCounter%7==0){ var row = calTBody.insertRow(-1); row.className = 'calendar_day_row'; if (showWeekNumber) { var cell = row.insertCell(-1); cell.className = 'calendar_week_column'; var week = getWeek(currentYear,currentMonth,no); cell.innerHTML = week; // Week cell.style.backgroundColor = selectBoxRolloverBgColor; } } var cell = row.insertCell(-1); if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){ cell.className='activeDay'; } cell.innerHTML = no; cell.onclick = pickDate; colCounter++; } if(!document.all){ if(calendarContentDiv.offsetHeight) document.getElementById('topBar').style.top = calendarContentDiv.offsetHeight + document.getElementById('timeBar').offsetHeight + document.getElementById('topBar').offsetHeight -1 + 'px'; else{ document.getElementById('topBar').style.top = ''; document.getElementById('topBar').style.bottom = '0px'; } } if(iframeObj){ if(!calendarContentDivExists)setTimeout('resizeIframe()',350);else setTimeout('resizeIframe()',10); } } function resizeIframe() { iframeObj.style.width = calendarDiv.offsetWidth + 'px'; iframeObj.style.height = calendarDiv.offsetHeight + 'px' ; } function pickTodaysDate() { var d = new Date(); currentMonth = d.getMonth(); currentYear = d.getFullYear(); pickDate(false,d.getDate()); } function pickDate(e,inputDay) { var month = currentMonth/1 +1; if(month<10)month = '0' + month; var day; if(!inputDay && this)day = this.innerHTML; else day = inputDay; if(day/1<10)day = '0' + day; if(returnFormat){ returnFormat = returnFormat.replace('dd',day); returnFormat = returnFormat.replace('mm',month); returnFormat = returnFormat.replace('yyyy',currentYear); returnFormat = returnFormat.replace('hh',currentHour); returnFormat = returnFormat.replace('ii',currentMinute); returnFormat = returnFormat.replace('d',day/1); returnFormat = returnFormat.replace('m',month/1); returnDateTo.value = returnFormat; try{ returnDateTo.onchange(); }catch(e){ } }else{ for(var no=0;no<returnDateToYear.options.length;no++){ if(returnDateToYear.options[no].value==currentYear){ returnDateToYear.selectedIndex=no; break; } } for(var no=0;no<returnDateToMonth.options.length;no++){ if(returnDateToMonth.options[no].value==parseInt(month)){ returnDateToMonth.selectedIndex=no; break; } } for(var no=0;no<returnDateToDay.options.length;no++){ if(returnDateToDay.options[no].value==parseInt(day)){ returnDateToDay.selectedIndex=no; break; } } if(calendarDisplayTime){ for(var no=0;no<returnDateToHour.options.length;no++){ if(returnDateToHour.options[no].value==parseInt(currentHour)){ returnDateToHour.selectedIndex=no; break; } } for(var no=0;no<returnDateToMinute.options.length;no++){ if(returnDateToMinute.options[no].value==parseInt(currentMinute)){ returnDateToMinute.selectedIndex=no; break; } } } } closeCalendar(); } // This function is from http://www.codeproject.com/csharp/gregorianwknum.asp // Only changed the month add function getWeek(year,month,day){ if (! weekStartsOnSunday) { day = (day/1); } else { day = (day/1)+1; } year = year /1; month = month/1 + 1; //use 1-12 var a = Math.floor((14-(month))/12); var y = year+4800-a; var m = (month)+(12*a)-3; var jd = day + Math.floor(((153*m)+2)/5) + (365*y) + Math.floor(y/4) - Math.floor(y/100) + Math.floor(y/400) - 32045; // (gregorian calendar) var d4 = (jd+31741-(jd%7))%146097%36524%1461; var L = Math.floor(d4/1460); var d1 = ((d4-L)%365)+L; NumberOfWeek = Math.floor(d1/7) + 1; return NumberOfWeek; } function writeTimeBar() { var timeBar = document.createElement('DIV'); timeBar.id = 'timeBar'; timeBar.className = 'timeBar'; var subDiv = document.createElement('DIV'); subDiv.innerHTML = 'Time:'; //timeBar.appendChild(subDiv); // Year selector var hourDiv = document.createElement('DIV'); hourDiv.onmouseover = highlightSelect; hourDiv.onmouseout = highlightSelect; hourDiv.onclick = showHourDropDown; hourDiv.style.width = '30px'; var span = document.createElement('SPAN'); if(!currentHour) currentHour = 0; span.innerHTML = currentHour; span.id = 'calendar_hour_txt'; hourDiv.appendChild(span); timeBar.appendChild(hourDiv); var img = document.createElement('IMG'); img.src = pathToImages + 'down_time.gif'; hourDiv.appendChild(img); hourDiv.className = 'selectBoxTime'; if(Opera){ hourDiv.style.width = '30px'; img.style.cssText = 'float:right'; img.style.position = 'relative'; img.style.styleFloat = 'right'; } var hourPicker = createHourDiv(); hourPicker.style.left = '130px'; //hourPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px'; hourPicker.style.width = '35px'; hourPicker.id = 'hourDropDown'; calendarDiv.appendChild(hourPicker); // Add Minute picker // Year selector var minuteDiv = document.createElement('DIV'); minuteDiv.onmouseover = highlightSelect; minuteDiv.onmouseout = highlightSelect; minuteDiv.onclick = showMinuteDropDown; minuteDiv.style.width = '30px'; var span = document.createElement('SPAN'); span.innerHTML = currentMinute; span.id = 'calendar_minute_txt'; minuteDiv.appendChild(span); timeBar.appendChild(minuteDiv); var img = document.createElement('IMG'); img.src = pathToImages + 'down_time.gif'; minuteDiv.appendChild(img); minuteDiv.className = 'selectBoxTime'; if(Opera){ minuteDiv.style.width = '30px'; img.style.cssText = 'float:right'; img.style.position = 'relative'; img.style.styleFloat = 'right'; } var minutePicker = createMinuteDiv(); minutePicker.style.left = '167px'; //minutePicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px'; minutePicker.style.width = '35px'; minutePicker.id = 'minuteDropDown'; calendarDiv.appendChild(minutePicker); return timeBar; } function writeBottomBar() { var d = new Date(); var bottomBar = document.createElement('DIV'); bottomBar.id = 'bottomBar'; bottomBar.style.cursor = 'pointer'; bottomBar.className = 'todaysDate'; // var todayStringFormat = '[todayString] [dayString] [day] [monthString] [year]'; ;; var subDiv = document.createElement('DIV'); subDiv.onclick = pickTodaysDate; subDiv.id = 'todaysDateString'; subDiv.style.width = (calendarDiv.offsetWidth - 95) + 'px'; var day = d.getDay(); if (! weekStartsOnSunday) { if(day==0)day = 7; day--; } var bottomString = todayStringFormat; bottomString = bottomString.replace('[monthString]',monthArrayShort[d.getMonth()]); bottomString = bottomString.replace('[day]',d.getDate()); bottomString = bottomString.replace('[year]',d.getFullYear()); bottomString = bottomString.replace('[dayString]',dayArray[day].toLowerCase()); bottomString = bottomString.replace('[UCFdayString]',dayArray[day]); bottomString = bottomString.replace('[todayString]',todayString); subDiv.innerHTML = todayString + ': ' + d.getDate() + '. ' + monthArrayShort[d.getMonth()] + ', ' + d.getFullYear() ; subDiv.innerHTML = bottomString ; bottomBar.appendChild(subDiv); var timeDiv = writeTimeBar(); bottomBar.appendChild(timeDiv); calendarDiv.appendChild(bottomBar); } function getTopPos(inputObj) { var returnValue = inputObj.offsetTop + inputObj.offsetHeight; while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop; return returnValue + calendar_offsetTop; } function getleftPos(inputObj) { var returnValue = inputObj.offsetLeft; while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft; return returnValue + calendar_offsetLeft; } function positionCalendar(inputObj) { calendarDiv.style.left = getleftPos(inputObj) + 'px'; calendarDiv.style.top = getTopPos(inputObj) + 'px'; if(iframeObj){ iframeObj.style.left = calendarDiv.style.left; iframeObj.style.top = calendarDiv.style.top; //// fix for EI frame problem on time dropdowns 09/30/2006 iframeObj2.style.left = calendarDiv.style.left; iframeObj2.style.top = calendarDiv.style.top; } } function initCalendar() { if(MSIE){ iframeObj = document.createElement('IFRAME'); iframeObj.style.filter = 'alpha(opacity=0)'; iframeObj.style.position = 'absolute'; iframeObj.border='0px'; iframeObj.style.border = '0px'; iframeObj.style.backgroundColor = '#FF0000'; //// fix for EI frame problem on time dropdowns 09/30/2006 iframeObj2 = document.createElement('IFRAME'); iframeObj2.style.position = 'absolute'; iframeObj2.border='0px'; iframeObj2.style.border = '0px'; iframeObj2.style.height = '1px'; iframeObj2.style.width = '1px'; //// fix for EI frame problem on time dropdowns 09/30/2006 // Added fixed for HTTPS iframeObj2.src = 'blank.html'; iframeObj.src = 'blank.html'; document.body.appendChild(iframeObj2); // gfb move this down AFTER the .src is set document.body.appendChild(iframeObj); } calendarDiv = document.createElement('DIV'); calendarDiv.id = 'calendarDiv'; calendarDiv.style.zIndex = 1000; slideCalendarSelectBox(); document.body.appendChild(calendarDiv); writeBottomBar(); writeTopBar(); if(!currentYear){ var d = new Date(); currentMonth = d.getMonth(); currentYear = d.getFullYear(); } writeCalendarContent(); } function setTimeProperties() { if(!calendarDisplayTime){ document.getElementById('timeBar').style.display='none'; document.getElementById('timeBar').style.visibility='hidden'; document.getElementById('todaysDateString').style.width = '100%'; }else{ document.getElementById('timeBar').style.display='block'; document.getElementById('timeBar').style.visibility='visible'; document.getElementById('hourDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px'; document.getElementById('minuteDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px'; document.getElementById('minuteDropDown').style.right = '50px'; document.getElementById('hourDropDown').style.right = '50px'; document.getElementById('todaysDateString').style.width = '115px'; } } function calendarSortItems(a,b) { return a/1 - b/1; } function displayCalendar(inputField,format,buttonObj,displayTime,imagesPath) { if(imagesPath) pathToImages = imagesPath; if(displayTime)calendarDisplayTime=true; else calendarDisplayTime = false; if(inputField.value.length>6){ //dates must have at least 6 digits... if(!inputField.value.match(/^[0-9]*?$/gi)){ var items = inputField.value.split(/[^0-9]/gi); var positionArray = new Object(); positionArray.m = format.indexOf('mm'); if(positionArray.m==-1)positionArray.m = format.indexOf('m'); positionArray.d = format.indexOf('dd'); if(positionArray.d==-1)positionArray.d = format.indexOf('d'); positionArray.y = format.indexOf('yyyy'); positionArray.h = format.indexOf('hh'); positionArray.i = format.indexOf('ii'); this.initialHour = '00'; this.initialMinute = '00'; var elements = ['y','m','d','h','i']; var properties = ['currentYear','currentMonth','inputDay','currentHour','currentMinute']; var propertyLength = [4,2,2,2,2]; for(var i=0;i<elements.length;i++) { if(positionArray[elements[i]]>=0) { window[properties[i]] = inputField.value.substr(positionArray[elements[i]],propertyLength[i])/1; } } currentMonth--; }else{ var monthPos = format.indexOf('mm'); currentMonth = inputField.value.substr(monthPos,2)/1 -1; var yearPos = format.indexOf('yyyy'); currentYear = inputField.value.substr(yearPos,4); var dayPos = format.indexOf('dd'); tmpDay = inputField.value.substr(dayPos,2); var hourPos = format.indexOf('hh'); if(hourPos>=0){ tmpHour = inputField.value.substr(hourPos,2); currentHour = tmpHour; }else{ currentHour = '00'; } var minutePos = format.indexOf('ii'); if(minutePos>=0){ tmpMinute = inputField.value.substr(minutePos,2); currentMinute = tmpMinute; }else{ currentMinute = '00'; } } }else{ var d = new Date(); currentMonth = d.getMonth(); currentYear = d.getFullYear(); currentHour = '08'; currentMinute = '00'; inputDay = d.getDate()/1; } if(currentMonth<0 || currentYear<0){ var d = new Date(); currentMonth = d.getMonth(); currentYear = d.getFullYear(); } inputYear = currentYear; inputMonth = currentMonth; if(!calendarDiv){ initCalendar(); }else{ if(calendarDiv.style.display=='block'){ closeCalendar(); return false; } writeCalendarContent(); } returnFormat = format; returnDateTo = inputField; positionCalendar(buttonObj); calendarDiv.style.visibility = 'visible'; calendarDiv.style.display = 'block'; if(iframeObj){ iframeObj.style.display = ''; iframeObj.style.height = '140px'; iframeObj.style.width = '195px'; iframeObj2.style.display = ''; iframeObj2.style.height = '140px'; iframeObj2.style.width = '195px'; } setTimeProperties(); updateYearDiv(); updateMonthDiv(); updateMinuteDiv(); updateHourDiv(); } function displayCalendarSelectBox(yearInput,monthInput,dayInput,hourInput,minuteInput,buttonObj) { if(!hourInput)calendarDisplayTime=false; else calendarDisplayTime = true; currentMonth = monthInput.options[monthInput.selectedIndex].value/1-1; currentYear = yearInput.options[yearInput.selectedIndex].value; if(hourInput){ currentHour = hourInput.options[hourInput.selectedIndex].value; inputHour = currentHour/1; } if(minuteInput){ currentMinute = minuteInput.options[minuteInput.selectedIndex].value; inputMinute = currentMinute/1; } inputYear = yearInput.options[yearInput.selectedIndex].value; inputMonth = monthInput.options[monthInput.selectedIndex].value/1 - 1; inputDay = dayInput.options[dayInput.selectedIndex].value/1; if(!calendarDiv){ initCalendar(); }else{ writeCalendarContent(); } returnDateToYear = yearInput; returnDateToMonth = monthInput; returnDateToDay = dayInput; returnDateToHour = hourInput; returnDateToMinute = minuteInput; returnFormat = false; returnDateTo = false; positionCalendar(buttonObj); calendarDiv.style.visibility = 'visible'; calendarDiv.style.display = 'block'; if(iframeObj){ iframeObj.style.display = ''; iframeObj.style.height = calendarDiv.offsetHeight + 'px'; iframeObj.style.width = calendarDiv.offsetWidth + 'px'; //// fix for EI frame problem on time dropdowns 09/30/2006 iframeObj2.style.display = ''; iframeObj2.style.height = calendarDiv.offsetHeight + 'px'; iframeObj2.style.width = calendarDiv.offsetWidth + 'px' } setTimeProperties(); updateYearDiv(); updateMonthDiv(); updateHourDiv(); updateMinuteDiv(); }
JavaScript
/*!---------------------------------------------------------------------------\ | Tab Pane 1.02 | |-----------------------------------------------------------------------------| | Created by Erik Arvidsson | | (http://webfx.eae.net/contact.html#erik) | | For WebFX (http://webfx.eae.net/) | |-----------------------------------------------------------------------------| | Copyright (c) 2002, 2003, 2006 Erik Arvidsson | |-----------------------------------------------------------------------------| | 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. | |-----------------------------------------------------------------------------| | 2002-01-?? | First working version | | 2002-02-17 | Cleaned up for 1.0 public version | | 2003-02-18 | Changed from javascript uri for anchors to return false | | 2003-03-03 | Added dispose methods to release IE memory | | 2006-05-28 | Changed license to Apache Software License 2.0. | |-----------------------------------------------------------------------------| | Dependencies: *.css a css file to define the layout | |-----------------------------------------------------------------------------| | Created 2002-01-?? | All changes are in the log above. | Updated 2006-05-28 | \----------------------------------------------------------------------------*/ // This function is used to define if the browser supports the needed // features function hasSupport() { if (typeof hasSupport.support != "undefined") return hasSupport.support; var ie55 = /msie 5\.[56789]/i.test( navigator.userAgent ); hasSupport.support = ( typeof document.implementation != "undefined" && document.implementation.hasFeature( "html", "1.0" ) || ie55 ) // IE55 has a serious DOM1 bug... Patch it! if ( ie55 ) { document._getElementsByTagName = document.getElementsByTagName; document.getElementsByTagName = function ( sTagName ) { if ( sTagName == "*" ) return document.all; else return document._getElementsByTagName( sTagName ); }; } return hasSupport.support; } /////////////////////////////////////////////////////////////////////////////////// // The constructor for tab panes // // el : HTMLElement The html element used to represent the tab pane // bUseCookie : Boolean Optional. Default is true. Used to determine whether to us // persistance using cookies or not // function WebFXTabPane( el, bUseCookie ) { if ( !hasSupport() || el == null ) return; this.element = el; this.element.tabPane = this; this.pages = []; this.selectedIndex = null; this.useCookie = bUseCookie != null ? bUseCookie : true; //added to have the tap not showing as long as it is not fully ready this.element.style.visibility = "visible"; // add class name tag to class name this.element.className = this.classNameTag + " " + this.element.className; // add tab row this.tabRow = document.createElement( "div" ); this.tabRow.className = "tab-row"; el.insertBefore( this.tabRow, el.firstChild ); var tabIndex = 0; if ( this.useCookie ) { tabIndex = Number( WebFXTabPane.getCookie( "webfxtab_" + this.element.id ) ); if ( isNaN( tabIndex ) ) tabIndex = 0; } this.selectedIndex = tabIndex; // loop through child nodes and add them var cs = el.childNodes; var n; for (var i = 0; i < cs.length; i++) { if (cs[i].nodeType == 1 && cs[i].className == "tab-page") { this.addTabPage( cs[i] ); } } } WebFXTabPane.prototype.classNameTag = "dynamic-tab-pane-control"; WebFXTabPane.prototype.setSelectedIndex = function ( n ) { if (this.selectedIndex != n) { if (this.selectedIndex != null && this.pages[ this.selectedIndex ] != null ) this.pages[ this.selectedIndex ].hide(); this.selectedIndex = n; this.pages[ this.selectedIndex ].show(); if ( this.useCookie ) WebFXTabPane.setCookie( "webfxtab_" + this.element.id, n ); // session cookie } }; WebFXTabPane.prototype.getSelectedIndex = function () { return this.selectedIndex; }; WebFXTabPane.prototype.addTabPage = function ( oElement ) { if ( !hasSupport() ) return; if ( oElement.tabPage == this ) // already added return oElement.tabPage; var n = this.pages.length; var tp = this.pages[n] = new WebFXTabPage( oElement, this, n ); tp.tabPane = this; // move the tab out of the box this.tabRow.appendChild( tp.tab ); if ( n == this.selectedIndex ) tp.show(); else tp.hide(); return tp; }; WebFXTabPane.prototype.dispose = function () { this.element.tabPane = null; this.element = null; this.tabRow = null; for (var i = 0; i < this.pages.length; i++) { this.pages[i].dispose(); this.pages[i] = null; } this.pages = null; }; // Cookie handling WebFXTabPane.setCookie = function ( sName, sValue, nDays ) { var expires = ""; if ( nDays ) { var d = new Date(); d.setTime( d.getTime() + nDays * 24 * 60 * 60 * 1000 ); expires = "; expires=" + d.toGMTString(); } document.cookie = sName + "=" + sValue + expires + "; path=/"; }; WebFXTabPane.getCookie = function (sName) { var re = new RegExp( "(\;|^)[^;]*(" + sName + ")\=([^;]*)(;|$)" ); var res = re.exec( document.cookie ); return res != null ? res[3] : null; }; WebFXTabPane.removeCookie = function ( name ) { setCookie( name, "", -1 ); }; /////////////////////////////////////////////////////////////////////////////////// // The constructor for tab pages. This one should not be used. // Use WebFXTabPage.addTabPage instead // // el : HTMLElement The html element used to represent the tab pane // tabPane : WebFXTabPane The parent tab pane // nindex : Number The index of the page in the parent pane page array // function WebFXTabPage( el, tabPane, nIndex ) { if ( !hasSupport() || el == null ) return; this.element = el; this.element.tabPage = this; this.index = nIndex; var cs = el.childNodes; for (var i = 0; i < cs.length; i++) { if (cs[i].nodeType == 1 && cs[i].className == "tab") { this.tab = cs[i]; break; } } // insert a tag around content to support keyboard navigation var a = document.createElement( "A" ); this.aElement = a; a.href = "#"; a.onclick = function () { return false; }; while (this.tab.hasChildNodes() ) a.appendChild( this.tab.firstChild ); this.tab.appendChild( a ); // hook up events, using DOM0 var oThis = this; this.tab.onclick = function () { oThis.select(); }; this.tab.onmouseover = function () { WebFXTabPage.tabOver( oThis ); }; this.tab.onmouseout = function () { WebFXTabPage.tabOut( oThis ); }; } WebFXTabPage.prototype.show = function () { var el = this.tab; var s = el.className + " selected"; s = s.replace(/ +/g, " "); el.className = s; this.element.style.display = "block"; //this.element.style.visibility = "visible"; }; WebFXTabPage.prototype.hide = function () { var el = this.tab; var s = el.className; s = s.replace(/ selected/g, ""); el.className = s; this.element.style.display = "none"; //this.element.style.visibility = "collapse"; }; WebFXTabPage.prototype.select = function () { this.tabPane.setSelectedIndex( this.index ); }; WebFXTabPage.prototype.dispose = function () { this.aElement.onclick = null; this.aElement = null; this.element.tabPage = null; this.tab.onclick = null; this.tab.onmouseover = null; this.tab.onmouseout = null; this.tab = null; this.tabPane = null; this.element = null; }; WebFXTabPage.tabOver = function ( tabpage ) { var el = tabpage.tab; var s = el.className + " hover"; s = s.replace(/ +/g, " "); el.className = s; }; WebFXTabPage.tabOut = function ( tabpage ) { var el = tabpage.tab; var s = el.className; s = s.replace(/ hover/g, ""); el.className = s; }; // This function initializes all uninitialized tab panes and tab pages function setupAllTabs() { if ( !hasSupport() ) return; var all = document.getElementsByTagName( "*" ); var l = all.length; var tabPaneRe = /tab\-pane/; var tabPageRe = /tab\-page/; var cn, el; var parentTabPane; for ( var i = 0; i < l; i++ ) { el = all[i] cn = el.className; // no className if ( cn == "" ) continue; // uninitiated tab pane if ( tabPaneRe.test( cn ) && !el.tabPane ) new WebFXTabPane( el ); // unitiated tab page wit a valid tab pane parent else if ( tabPageRe.test( cn ) && !el.tabPage && tabPaneRe.test( el.parentNode.className ) ) { el.parentNode.tabPane.addTabPage( el ); } } } function disposeAllTabs() { if ( !hasSupport() ) return; var all = document.getElementsByTagName( "*" ); var l = all.length; var tabPaneRe = /tab\-pane/; var cn, el; var tabPanes = []; for ( var i = 0; i < l; i++ ) { el = all[i] cn = el.className; // no className if ( cn == "" ) continue; // tab pane if ( tabPaneRe.test( cn ) && el.tabPane ) tabPanes[tabPanes.length] = el.tabPane; } for (var i = tabPanes.length - 1; i >= 0; i--) { tabPanes[i].dispose(); tabPanes[i] = null; } } // initialization hook up /* // DOM2 if ( typeof window.addEventListener != "undefined" ) window.addEventListener( "load", setupAllTabs, false ); // IE else if ( typeof window.attachEvent != "undefined" ) { window.attachEvent( "onload", setupAllTabs ); window.attachEvent( "onunload", disposeAllTabs ); } else { if ( window.onload != null ) { var oldOnload = window.onload; window.onload = function ( e ) { oldOnload( e ); setupAllTabs(); }; } else window.onload = setupAllTabs; }*/
JavaScript
/* http://www.JSON.org/json2.js 2008-03-24 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This file creates a global JSON object containing three methods: stringify, parse, and quote. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects without a toJSON method. It can be a function or an array. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the object holding the key. This is the toJSON method added to Dates: function toJSON(key) { return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; } You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If no replacer parameter is provided, then a default replacer will be used: function replacer(key, value) { return Object.hasOwnProperty.call(this, key) ? value : undefined; } The default replacer is passed the key and value for each item in the structure. It excludes inherited members. If the replacer parameter is an array, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representaions, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then then indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); JSON.quote(text) This method wraps a string in quotes, escaping some characters as needed. This is a reference implementation. You are free to copy, modify, or redistribute. USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD THIRD PARTY CODE INTO YOUR PAGES. */ /*jslint regexp: true, forin: true, evil: true */ /*global JSON */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, floor, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, length, parse, propertyIsEnumerable, prototype, push, quote, replace, stringify, test, toJSON, toString */ if (!this.JSON) { // Create a JSON object only if one does not already exist. We create the // object in a closure to avoid global variables. JSON = function () { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } Date.prototype.toJSON = function () { // Eventually, this method will be based on the date.toISOString method. return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. return escapeable.test(string) ? '"' + string.replace(escapeable, function (a) { var c = meta[a]; if (typeof c === 'string') { return c; } c = a.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // If the object has a dontEnum length property, we'll treat it as an array. if (typeof value.length === 'number' && !(value.propertyIsEnumerable('length'))) { // The object is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value, rep); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { v = str(k, value, rep); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // Return the JSON object containing the stringify, parse, and quote methods. return { stringify: function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; if (space) { // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } } // If there is no replacer parameter, use the default replacer. if (!replacer) { rep = function (key, value) { if (!Object.hasOwnProperty.call(this, key)) { return undefined; } return value; }; // The replacer can be a function or an array. Otherwise, throw an error. } else if (typeof replacer === 'function' || (typeof replacer === 'object' && typeof replacer.length === 'number')) { rep = replacer; } else { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }, parse: function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in three stages. In the first stage, we run the text against // regular expressions that look for non-JSON patterns. We are especially // concerned with '()' and 'new' because they can cause invocation, and '=' // because it can cause mutation. But just to be safe, we want to reject all // unexpected forms. // We split the first stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace all backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the second stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional third stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }, quote: quote }; }(); }
JavaScript
var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'locale': {} }; // Allow other JavaScript libraries to use $. jQuery.noConflict(); (function ($) { /** * Override jQuery.fn.init to guard against XSS attacks. * * See http://bugs.jquery.com/ticket/9521 */ var jquery_init = $.fn.init; $.fn.init = function (selector, context, rootjQuery) { // If the string contains a "#" before a "<", treat it as invalid HTML. if (selector && typeof selector === 'string') { var hash_position = selector.indexOf('#'); if (hash_position >= 0) { var bracket_position = selector.indexOf('<'); if (bracket_position > hash_position) { throw 'Syntax error, unrecognized expression: ' + selector; } } } return jquery_init.call(this, selector, context, rootjQuery); }; $.fn.init.prototype = jquery_init.prototype; /** * Attach all registered behaviors to a page element. * * Behaviors are event-triggered actions that attach to page elements, enhancing * default non-JavaScript UIs. Behaviors are registered in the Drupal.behaviors * object using the method 'attach' and optionally also 'detach' as follows: * @code * Drupal.behaviors.behaviorName = { * attach: function (context, settings) { * ... * }, * detach: function (context, settings, trigger) { * ... * } * }; * @endcode * * Drupal.attachBehaviors is added below to the jQuery ready event and so * runs on initial page load. Developers implementing AHAH/Ajax in their * solutions should also call this function after new page content has been * loaded, feeding in an element to be processed, in order to attach all * behaviors to the new content. * * Behaviors should use * @code * $(selector).once('behavior-name', function () { * ... * }); * @endcode * to ensure the behavior is attached only once to a given element. (Doing so * enables the reprocessing of given elements, which may be needed on occasion * despite the ability to limit behavior attachment to a particular element.) * * @param context * An element to attach behaviors to. If none is given, the document element * is used. * @param settings * An object containing settings for the current context. If none given, the * global Drupal.settings object is used. */ Drupal.attachBehaviors = function (context, settings) { context = context || document; settings = settings || Drupal.settings; // Execute all of them. $.each(Drupal.behaviors, function () { if ($.isFunction(this.attach)) { this.attach(context, settings); } }); }; /** * Detach registered behaviors from a page element. * * Developers implementing AHAH/Ajax in their solutions should call this * function before page content is about to be removed, feeding in an element * to be processed, in order to allow special behaviors to detach from the * content. * * Such implementations should look for the class name that was added in their * corresponding Drupal.behaviors.behaviorName.attach implementation, i.e. * behaviorName-processed, to ensure the behavior is detached only from * previously processed elements. * * @param context * An element to detach behaviors from. If none is given, the document element * is used. * @param settings * An object containing settings for the current context. If none given, the * global Drupal.settings object is used. * @param trigger * A string containing what's causing the behaviors to be detached. The * possible triggers are: * - unload: (default) The context element is being removed from the DOM. * - move: The element is about to be moved within the DOM (for example, * during a tabledrag row swap). After the move is completed, * Drupal.attachBehaviors() is called, so that the behavior can undo * whatever it did in response to the move. Many behaviors won't need to * do anything simply in response to the element being moved, but because * IFRAME elements reload their "src" when being moved within the DOM, * behaviors bound to IFRAME elements (like WYSIWYG editors) may need to * take some action. * - serialize: When an Ajax form is submitted, this is called with the * form as the context. This provides every behavior within the form an * opportunity to ensure that the field elements have correct content * in them before the form is serialized. The canonical use-case is so * that WYSIWYG editors can update the hidden textarea to which they are * bound. * * @see Drupal.attachBehaviors */ Drupal.detachBehaviors = function (context, settings, trigger) { context = context || document; settings = settings || Drupal.settings; trigger = trigger || 'unload'; // Execute all of them. $.each(Drupal.behaviors, function () { if ($.isFunction(this.detach)) { this.detach(context, settings, trigger); } }); }; /** * Encode special characters in a plain-text string for display as HTML. * * @ingroup sanitization */ Drupal.checkPlain = function (str) { var character, regex, replace = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' }; str = String(str); for (character in replace) { if (replace.hasOwnProperty(character)) { regex = new RegExp(character, 'g'); str = str.replace(regex, replace[character]); } } return str; }; /** * Replace placeholders with sanitized values in a string. * * @param str * A string with placeholders. * @param args * An object of replacements pairs to make. Incidences of any key in this * array are replaced with the corresponding value. Based on the first * character of the key, the value is escaped and/or themed: * - !variable: inserted as is * - @variable: escape plain text to HTML (Drupal.checkPlain) * - %variable: escape text and theme as a placeholder for user-submitted * content (checkPlain + Drupal.theme('placeholder')) * * @see Drupal.t() * @ingroup sanitization */ Drupal.formatString = function(str, args) { // Transform arguments before inserting them. for (var key in args) { switch (key.charAt(0)) { // Escaped only. case '@': args[key] = Drupal.checkPlain(args[key]); break; // Pass-through. case '!': break; // Escaped and placeholder. case '%': default: args[key] = Drupal.theme('placeholder', args[key]); break; } str = str.replace(key, args[key]); } return str; }; /** * Translate strings to the page language or a given language. * * See the documentation of the server-side t() function for further details. * * @param str * A string containing the English string to translate. * @param args * An object of replacements pairs to make after translation. Incidences * of any key in this array are replaced with the corresponding value. * See Drupal.formatString(). * * @param options * - 'context' (defaults to the empty context): The context the source string * belongs to. * * @return * The translated string. */ Drupal.t = function (str, args, options) { options = options || {}; options.context = options.context || ''; // Fetch the localized version of the string. if (Drupal.locale.strings && Drupal.locale.strings[options.context] && Drupal.locale.strings[options.context][str]) { str = Drupal.locale.strings[options.context][str]; } if (args) { str = Drupal.formatString(str, args); } return str; }; /** * Format a string containing a count of items. * * This function ensures that the string is pluralized correctly. Since Drupal.t() is * called by this function, make sure not to pass already-localized strings to it. * * See the documentation of the server-side format_plural() function for further details. * * @param count * The item count to display. * @param singular * The string for the singular case. Please make sure it is clear this is * singular, to ease translation (e.g. use "1 new comment" instead of "1 new"). * Do not use @count in the singular string. * @param plural * The string for the plural case. Please make sure it is clear this is plural, * to ease translation. Use @count in place of the item count, as in "@count * new comments". * @param args * An object of replacements pairs to make after translation. Incidences * of any key in this array are replaced with the corresponding value. * See Drupal.formatString(). * Note that you do not need to include @count in this array. * This replacement is done automatically for the plural case. * @param options * The options to pass to the Drupal.t() function. * @return * A translated string. */ Drupal.formatPlural = function (count, singular, plural, args, options) { var args = args || {}; args['@count'] = count; // Determine the index of the plural form. var index = Drupal.locale.pluralFormula ? Drupal.locale.pluralFormula(args['@count']) : ((args['@count'] == 1) ? 0 : 1); if (index == 0) { return Drupal.t(singular, args, options); } else if (index == 1) { return Drupal.t(plural, args, options); } else { args['@count[' + index + ']'] = args['@count']; delete args['@count']; return Drupal.t(plural.replace('@count', '@count[' + index + ']'), args, options); } }; /** * Generate the themed representation of a Drupal object. * * All requests for themed output must go through this function. It examines * the request and routes it to the appropriate theme function. If the current * theme does not provide an override function, the generic theme function is * called. * * For example, to retrieve the HTML for text that should be emphasized and * displayed as a placeholder inside a sentence, call * Drupal.theme('placeholder', text). * * @param func * The name of the theme function to call. * @param ... * Additional arguments to pass along to the theme function. * @return * Any data the theme function returns. This could be a plain HTML string, * but also a complex object. */ Drupal.theme = function (func) { var args = Array.prototype.slice.apply(arguments, [1]); return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args); }; /** * Freeze the current body height (as minimum height). Used to prevent * unnecessary upwards scrolling when doing DOM manipulations. */ Drupal.freezeHeight = function () { Drupal.unfreezeHeight(); $('<div id="freeze-height"></div>').css({ position: 'absolute', top: '0px', left: '0px', width: '1px', height: $('body').css('height') }).appendTo('body'); }; /** * Unfreeze the body height. */ Drupal.unfreezeHeight = function () { $('#freeze-height').remove(); }; /** * Encodes a Drupal path for use in a URL. * * For aesthetic reasons slashes are not escaped. */ Drupal.encodePath = function (item, uri) { uri = uri || location.href; return encodeURIComponent(item).replace(/%2F/g, '/'); }; /** * Get the text selection in a textarea. */ Drupal.getSelection = function (element) { if (typeof element.selectionStart != 'number' && document.selection) { // The current selection. var range1 = document.selection.createRange(); var range2 = range1.duplicate(); // Select all text. range2.moveToElementText(element); // Now move 'dummy' end point to end point of original range. range2.setEndPoint('EndToEnd', range1); // Now we can calculate start and end points. var start = range2.text.length - range1.text.length; var end = start + range1.text.length; return { 'start': start, 'end': end }; } return { 'start': element.selectionStart, 'end': element.selectionEnd }; }; /** * Build an error message from an Ajax response. */ Drupal.ajaxError = function (xmlhttp, uri) { var statusCode, statusText, pathText, responseText, readyStateText, message; if (xmlhttp.status) { statusCode = "\n" + Drupal.t("An AJAX HTTP error occurred.") + "\n" + Drupal.t("HTTP Result Code: !status", {'!status': xmlhttp.status}); } else { statusCode = "\n" + Drupal.t("An AJAX HTTP request terminated abnormally."); } statusCode += "\n" + Drupal.t("Debugging information follows."); pathText = "\n" + Drupal.t("Path: !uri", {'!uri': uri} ); statusText = ''; // In some cases, when statusCode == 0, xmlhttp.statusText may not be defined. // Unfortunately, testing for it with typeof, etc, doesn't seem to catch that // and the test causes an exception. So we need to catch the exception here. try { statusText = "\n" + Drupal.t("StatusText: !statusText", {'!statusText': $.trim(xmlhttp.statusText)}); } catch (e) {} responseText = ''; // Again, we don't have a way to know for sure whether accessing // xmlhttp.responseText is going to throw an exception. So we'll catch it. try { responseText = "\n" + Drupal.t("ResponseText: !responseText", {'!responseText': $.trim(xmlhttp.responseText) } ); } catch (e) {} // Make the responseText more readable by stripping HTML tags and newlines. responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,""); responseText = responseText.replace(/[\n]+\s+/g,"\n"); // We don't need readyState except for status == 0. readyStateText = xmlhttp.status == 0 ? ("\n" + Drupal.t("ReadyState: !readyState", {'!readyState': xmlhttp.readyState})) : ""; message = statusCode + pathText + statusText + responseText + readyStateText; return message; }; // Class indicating that JS is enabled; used for styling purpose. $('html').addClass('js'); // 'js enabled' cookie. document.cookie = 'has_js=1; path=/'; /** * Additions to jQuery.support. */ $(function () { /** * Boolean indicating whether or not position:fixed is supported. */ if (jQuery.support.positionFixed === undefined) { var el = $('<div style="position:fixed; top:10px" />').appendTo(document.body); jQuery.support.positionFixed = el[0].offsetTop === 10; el.remove(); } }); //Attach all behaviors. $(function () { Drupal.attachBehaviors(document, Drupal.settings); }); /** * The default themes. */ Drupal.theme.prototype = { /** * Formats text for emphasized display in a placeholder inside a sentence. * * @param str * The text to format (plain-text). * @return * The formatted text (html). */ placeholder: function (str) { return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>'; } }; })(jQuery);
JavaScript
(function ($) { /** * Drag and drop table rows with field manipulation. * * Using the drupal_add_tabledrag() function, any table with weights or parent * relationships may be made into draggable tables. Columns containing a field * may optionally be hidden, providing a better user experience. * * Created tableDrag instances may be modified with custom behaviors by * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods. * See blocks.js for an example of adding additional functionality to tableDrag. */ Drupal.behaviors.tableDrag = { attach: function (context, settings) { for (var base in settings.tableDrag) { $('#' + base, context).once('tabledrag', function () { // Create the new tableDrag instance. Save in the Drupal variable // to allow other scripts access to the object. Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]); }); } } }; /** * Constructor for the tableDrag object. Provides table and field manipulation. * * @param table * DOM object for the table to be made draggable. * @param tableSettings * Settings for the table added via drupal_add_dragtable(). */ Drupal.tableDrag = function (table, tableSettings) { var self = this; // Required object variables. this.table = table; this.tableSettings = tableSettings; this.dragObject = null; // Used to hold information about a current drag operation. this.rowObject = null; // Provides operations for row manipulation. this.oldRowElement = null; // Remember the previous element. this.oldY = 0; // Used to determine up or down direction from last mouse move. this.changed = false; // Whether anything in the entire table has changed. this.maxDepth = 0; // Maximum amount of allowed parenting. this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table. // Configure the scroll settings. this.scrollSettings = { amount: 4, interval: 50, trigger: 70 }; this.scrollInterval = null; this.scrollY = 0; this.windowHeight = 0; // Check this table's settings to see if there are parent relationships in // this table. For efficiency, large sections of code can be skipped if we // don't need to track horizontal movement and indentations. this.indentEnabled = false; for (var group in tableSettings) { for (var n in tableSettings[group]) { if (tableSettings[group][n].relationship == 'parent') { this.indentEnabled = true; } if (tableSettings[group][n].limit > 0) { this.maxDepth = tableSettings[group][n].limit; } } } if (this.indentEnabled) { this.indentCount = 1; // Total width of indents, set in makeDraggable. // Find the width of indentations to measure mouse movements against. // Because the table doesn't need to start with any indentations, we // manually append 2 indentations in the first draggable row, measure // the offset, then remove. var indent = Drupal.theme('tableDragIndentation'); var testRow = $('<tr/>').addClass('draggable').appendTo(table); var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent); this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft; testRow.remove(); } // Make each applicable row draggable. // Match immediate children of the parent element to allow nesting. $('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); }); // Add a link before the table for users to show or hide weight columns. $(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>') .attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.')) .click(function () { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { self.hideColumns(); } else { self.showColumns(); } return false; }) .wrap('<div class="tabledrag-toggle-weight-wrapper"></div>') .parent() ); // Initialize the specified columns (for example, weight or parent columns) // to show or hide according to user preference. This aids accessibility // so that, e.g., screen reader users can choose to enter weight values and // manipulate form elements directly, rather than using drag-and-drop.. self.initColumns(); // Add mouse bindings to the document. The self variable is passed along // as event handlers do not have direct access to the tableDrag object. $(document).bind('mousemove', function (event) { return self.dragRow(event, self); }); $(document).bind('mouseup', function (event) { return self.dropRow(event, self); }); }; /** * Initialize columns containing form elements to be hidden by default, * according to the settings for this tableDrag instance. * * Identify and mark each cell with a CSS class so we can easily toggle * show/hide it. Finally, hide columns if user does not have a * 'Drupal.tableDrag.showWeight' cookie. */ Drupal.tableDrag.prototype.initColumns = function () { for (var group in this.tableSettings) { // Find the first field in this group. for (var d in this.tableSettings[group]) { var field = $('.' + this.tableSettings[group][d].target + ':first', this.table); if (field.length && this.tableSettings[group][d].hidden) { var hidden = this.tableSettings[group][d].hidden; var cell = field.closest('td'); break; } } // Mark the column containing this field so it can be hidden. if (hidden && cell[0]) { // Add 1 to our indexes. The nth-child selector is 1 based, not 0 based. // Match immediate children of the parent element to allow nesting. var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1; $('> thead > tr, > tbody > tr, > tr', this.table).each(function () { // Get the columnIndex and adjust for any colspans in this row. var index = columnIndex; var cells = $(this).children(); cells.each(function (n) { if (n < index && this.colSpan && this.colSpan > 1) { index -= this.colSpan - 1; } }); if (index > 0) { cell = cells.filter(':nth-child(' + index + ')'); if (cell[0].colSpan && cell[0].colSpan > 1) { // If this cell has a colspan, mark it so we can reduce the colspan. cell.addClass('tabledrag-has-colspan'); } else { // Mark this cell so we can hide it. cell.addClass('tabledrag-hide'); } } }); } } // Now hide cells and reduce colspans unless cookie indicates previous choice. // Set a cookie if it is not already present. if ($.cookie('Drupal.tableDrag.showWeight') === null) { $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); this.hideColumns(); } // Check cookie value and show/hide weight columns accordingly. else { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { this.showColumns(); } else { this.hideColumns(); } } }; /** * Hide the columns containing weight/parent form elements. * Undo showColumns(). */ Drupal.tableDrag.prototype.hideColumns = function () { // Hide weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none'); // Show TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', ''); // Reduce the colspan of any effected multi-span columns. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan - 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'hide'); }; /** * Show the columns containing weight/parent form elements * Undo hideColumns(). */ Drupal.tableDrag.prototype.showColumns = function () { // Show weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', ''); // Hide TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none'); // Increase the colspan for any columns where it was previously reduced. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan + 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 1, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'show'); }; /** * Find the target used within a particular row and group. */ Drupal.tableDrag.prototype.rowSettings = function (group, row) { var field = $('.' + group, row); for (var delta in this.tableSettings[group]) { var targetClass = this.tableSettings[group][delta].target; if (field.is('.' + targetClass)) { // Return a copy of the row settings. var rowSettings = {}; for (var n in this.tableSettings[group][delta]) { rowSettings[n] = this.tableSettings[group][delta][n]; } return rowSettings; } } }; /** * Take an item and add event handlers to make it become draggable. */ Drupal.tableDrag.prototype.makeDraggable = function (item) { var self = this; // Create the handle. var handle = $('<a href="#" class="tabledrag-handle"><div class="handle">&nbsp;</div></a>').attr('title', Drupal.t('Drag to re-order')); // Insert the handle after indentations (if any). if ($('td:first .indentation:last', item).length) { $('td:first .indentation:last', item).after(handle); // Update the total width of indentation in this entire table. self.indentCount = Math.max($('.indentation', item).length, self.indentCount); } else { $('td:first', item).prepend(handle); } // Add hover action for the handle. handle.hover(function () { self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null; }, function () { self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null; }); // Add the mousedown action for the handle. handle.mousedown(function (event) { // Create a new dragObject recording the event information. self.dragObject = {}; self.dragObject.initMouseOffset = self.getMouseOffset(item, event); self.dragObject.initMouseCoords = self.mouseCoords(event); if (self.indentEnabled) { self.dragObject.indentMousePos = self.dragObject.initMouseCoords; } // If there's a lingering row object from the keyboard, remove its focus. if (self.rowObject) { $('a.tabledrag-handle', self.rowObject.element).blur(); } // Create a new rowObject for manipulation of this row. self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true); // Save the position of the table. self.table.topY = $(self.table).offset().top; self.table.bottomY = self.table.topY + self.table.offsetHeight; // Add classes to the handle and row. $(this).addClass('tabledrag-handle-hover'); $(item).addClass('drag'); // Set the document to use the move cursor during drag. $('body').addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'none'); } // Hack for Konqueror, prevent the blur handler from firing. // Konqueror always gives links focus, even after returning false on mousedown. self.safeBlur = false; // Call optional placeholder function. self.onDrag(); return false; }); // Prevent the anchor tag from jumping us to the top of the page. handle.click(function () { return false; }); // Similar to the hover event, add a class when the handle is focused. handle.focus(function () { $(this).addClass('tabledrag-handle-hover'); self.safeBlur = true; }); // Remove the handle class on blur and fire the same function as a mouseup. handle.blur(function (event) { $(this).removeClass('tabledrag-handle-hover'); if (self.rowObject && self.safeBlur) { self.dropRow(event, self); } }); // Add arrow-key support to the handle. handle.keydown(function (event) { // If a rowObject doesn't yet exist and this isn't the tab key. if (event.keyCode != 9 && !self.rowObject) { self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true); } var keyChange = false; switch (event.keyCode) { case 37: // Left arrow. case 63234: // Safari left arrow. keyChange = true; self.rowObject.indent(-1 * self.rtl); break; case 38: // Up arrow. case 63232: // Safari up arrow. var previousRow = $(self.rowObject.element).prev('tr').get(0); while (previousRow && $(previousRow).is(':hidden')) { previousRow = $(previousRow).prev('tr').get(0); } if (previousRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'up'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the previous top-level row. var groupHeight = 0; while (previousRow && $('.indentation', previousRow).length) { previousRow = $(previousRow).prev('tr').get(0); groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight; } if (previousRow) { self.rowObject.swap('before', previousRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, -groupHeight); } } else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) { // Swap with the previous row (unless previous row is the first one // and undraggable). self.rowObject.swap('before', previousRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, -parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; case 39: // Right arrow. case 63235: // Safari right arrow. keyChange = true; self.rowObject.indent(1 * self.rtl); break; case 40: // Down arrow. case 63233: // Safari down arrow. var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0); while (nextRow && $(nextRow).is(':hidden')) { nextRow = $(nextRow).next('tr').get(0); } if (nextRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'down'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the next group (necessarily a top-level one). var groupHeight = 0; var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false); if (nextGroup) { $(nextGroup.group).each(function () { groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight; }); var nextGroupRow = $(nextGroup.group).filter(':last').get(0); self.rowObject.swap('after', nextGroupRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, parseInt(groupHeight, 10)); } } else { // Swap with the next row. self.rowObject.swap('after', nextRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; } if (self.rowObject && self.rowObject.changed == true) { $(item).addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } self.oldRowElement = item; self.restripeTable(); self.onDrag(); } // Returning false if we have an arrow key to prevent scrolling. if (keyChange) { return false; } }); // Compatibility addition, return false on keypress to prevent unwanted scrolling. // IE and Safari will suppress scrolling on keydown, but all other browsers // need to return false on keypress. http://www.quirksmode.org/js/keys.html handle.keypress(function (event) { switch (event.keyCode) { case 37: // Left arrow. case 38: // Up arrow. case 39: // Right arrow. case 40: // Down arrow. return false; } }); }; /** * Mousemove event handler, bound to document. */ Drupal.tableDrag.prototype.dragRow = function (event, self) { if (self.dragObject) { self.currentMouseCoords = self.mouseCoords(event); var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y; var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x; // Check for row swapping and vertical scrolling. if (y != self.oldY) { self.rowObject.direction = y > self.oldY ? 'down' : 'up'; self.oldY = y; // Update the old value. // Check if the window should be scrolled (and how fast). var scrollAmount = self.checkScroll(self.currentMouseCoords.y); // Stop any current scrolling. clearInterval(self.scrollInterval); // Continue scrolling if the mouse has moved in the scroll direction. if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') { self.setScroll(scrollAmount); } // If we have a valid target, perform the swap and restripe the table. var currentRow = self.findDropTargetRow(x, y); if (currentRow) { if (self.rowObject.direction == 'down') { self.rowObject.swap('after', currentRow, self); } else { self.rowObject.swap('before', currentRow, self); } self.restripeTable(); } } // Similar to row swapping, handle indentations. if (self.indentEnabled) { var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x; // Set the number of indentations the mouse has been moved left or right. var indentDiff = Math.round(xDiff / self.indentAmount * self.rtl); // Indent the row with our estimated diff, which may be further // restricted according to the rows around this row. var indentChange = self.rowObject.indent(indentDiff); // Update table and mouse indentations. self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl; self.indentCount = Math.max(self.indentCount, self.rowObject.indents); } return false; } }; /** * Mouseup event handler, bound to document. * Blur event handler, bound to drag handle for keyboard support. */ Drupal.tableDrag.prototype.dropRow = function (event, self) { // Drop row functionality shared between mouseup and blur events. if (self.rowObject != null) { var droppedRow = self.rowObject.element; // The row is already in the right place so we just release it. if (self.rowObject.changed == true) { // Update the fields in the dropped row. self.updateFields(droppedRow); // If a setting exists for affecting the entire group, update all the // fields in the entire dragged group. for (var group in self.tableSettings) { var rowSettings = self.rowSettings(group, droppedRow); if (rowSettings.relationship == 'group') { for (var n in self.rowObject.children) { self.updateField(self.rowObject.children[n], group); } } } self.rowObject.markChanged(); if (self.changed == false) { $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow'); self.changed = true; } } if (self.indentEnabled) { self.rowObject.removeIndentClasses(); } if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } $(droppedRow).removeClass('drag').addClass('drag-previous'); self.oldRowElement = droppedRow; self.onDrop(); self.rowObject = null; } // Functionality specific only to mouseup event. if (self.dragObject != null) { $('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover'); self.dragObject = null; $('body').removeClass('drag'); clearInterval(self.scrollInterval); // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'block'); } } }; /** * Get the mouse coordinates from the event (allowing for browser differences). */ Drupal.tableDrag.prototype.mouseCoords = function (event) { if (event.pageX || event.pageY) { return { x: event.pageX, y: event.pageY }; } return { x: event.clientX + document.body.scrollLeft - document.body.clientLeft, y: event.clientY + document.body.scrollTop - document.body.clientTop }; }; /** * Given a target element and a mouse event, get the mouse offset from that * element. To do this we need the element's position and the mouse position. */ Drupal.tableDrag.prototype.getMouseOffset = function (target, event) { var docPos = $(target).offset(); var mousePos = this.mouseCoords(event); return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top }; }; /** * Find the row the mouse is currently over. This row is then taken and swapped * with the one being dragged. * * @param x * The x coordinate of the mouse on the page (not the screen). * @param y * The y coordinate of the mouse on the page (not the screen). */ Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) { var rows = $(this.table.tBodies[0].rows).not(':hidden'); for (var n = 0; n < rows.length; n++) { var row = rows[n]; var indentDiff = 0; var rowY = $(row).offset().top; // Because Safari does not report offsetHeight on table rows, but does on // table cells, grab the firstChild of the row and use that instead. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari. if (row.offsetHeight == 0) { var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2; } // Other browsers. else { var rowHeight = parseInt(row.offsetHeight, 10) / 2; } // Because we always insert before, we need to offset the height a bit. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) { if (this.indentEnabled) { // Check that this row is not a child of the row being dragged. for (var n in this.rowObject.group) { if (this.rowObject.group[n] == row) { return null; } } } else { // Do not allow a row to be swapped with itself. if (row == this.rowObject.element) { return null; } } // Check that swapping with this row is allowed. if (!this.rowObject.isValidSwap(row)) { return null; } // We may have found the row the mouse just passed over, but it doesn't // take into account hidden rows. Skip backwards until we find a draggable // row. while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) { row = $(row).prev('tr').get(0); } return row; } } return null; }; /** * After the row is dropped, update the table fields according to the settings * set for this table. * * @param changedRow * DOM object for the row that was just dropped. */ Drupal.tableDrag.prototype.updateFields = function (changedRow) { for (var group in this.tableSettings) { // Each group may have a different setting for relationship, so we find // the source rows for each separately. this.updateField(changedRow, group); } }; /** * After the row is dropped, update a single table field according to specific * settings. * * @param changedRow * DOM object for the row that was just dropped. * @param group * The settings group on which field updates will occur. */ Drupal.tableDrag.prototype.updateField = function (changedRow, group) { var rowSettings = this.rowSettings(group, changedRow); // Set the row as its own target. if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') { var sourceRow = changedRow; } // Siblings are easy, check previous and next rows. else if (rowSettings.relationship == 'sibling') { var previousRow = $(changedRow).prev('tr').get(0); var nextRow = $(changedRow).next('tr').get(0); var sourceRow = changedRow; if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) { if (this.indentEnabled) { if ($('.indentations', previousRow).length == $('.indentations', changedRow)) { sourceRow = previousRow; } } else { sourceRow = previousRow; } } else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) { if (this.indentEnabled) { if ($('.indentations', nextRow).length == $('.indentations', changedRow)) { sourceRow = nextRow; } } else { sourceRow = nextRow; } } } // Parents, look up the tree until we find a field not in this group. // Go up as many parents as indentations in the changed row. else if (rowSettings.relationship == 'parent') { var previousRow = $(changedRow).prev('tr'); while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) { previousRow = previousRow.prev('tr'); } // If we found a row. if (previousRow.length) { sourceRow = previousRow[0]; } // Otherwise we went all the way to the left of the table without finding // a parent, meaning this item has been placed at the root level. else { // Use the first row in the table as source, because it's guaranteed to // be at the root level. Find the first item, then compare this row // against it as a sibling. sourceRow = $(this.table).find('tr.draggable:first').get(0); if (sourceRow == this.rowObject.element) { sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0); } var useSibling = true; } } // Because we may have moved the row from one category to another, // take a look at our sibling and borrow its sources and targets. this.copyDragClasses(sourceRow, changedRow, group); rowSettings = this.rowSettings(group, changedRow); // In the case that we're looking for a parent, but the row is at the top // of the tree, copy our sibling's values. if (useSibling) { rowSettings.relationship = 'sibling'; rowSettings.source = rowSettings.target; } var targetClass = '.' + rowSettings.target; var targetElement = $(targetClass, changedRow).get(0); // Check if a target element exists in this row. if (targetElement) { var sourceClass = '.' + rowSettings.source; var sourceElement = $(sourceClass, sourceRow).get(0); switch (rowSettings.action) { case 'depth': // Get the depth of the target row. targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length; break; case 'match': // Update the value. targetElement.value = sourceElement.value; break; case 'order': var siblings = this.rowObject.findSiblings(rowSettings); if ($(targetElement).is('select')) { // Get a list of acceptable values. var values = []; $('option', targetElement).each(function () { values.push(this.value); }); var maxVal = values[values.length - 1]; // Populate the values in the siblings. $(targetClass, siblings).each(function () { // If there are more items than possible values, assign the maximum value to the row. if (values.length > 0) { this.value = values.shift(); } else { this.value = maxVal; } }); } else { // Assume a numeric input field. var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0; $(targetClass, siblings).each(function () { this.value = weight; weight++; }); } break; } } }; /** * Copy all special tableDrag classes from one row's form elements to a * different one, removing any special classes that the destination row * may have had. */ Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) { var sourceElement = $('.' + group, sourceRow); var targetElement = $('.' + group, targetRow); if (sourceElement.length && targetElement.length) { targetElement[0].className = sourceElement[0].className; } }; Drupal.tableDrag.prototype.checkScroll = function (cursorY) { var de = document.documentElement; var b = document.body; var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight); var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY)); var trigger = this.scrollSettings.trigger; var delta = 0; // Return a scroll speed relative to the edge of the screen. if (cursorY - scrollY > windowHeight - trigger) { delta = trigger / (windowHeight + scrollY - cursorY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return delta * this.scrollSettings.amount; } else if (cursorY - scrollY < trigger) { delta = trigger / (cursorY - scrollY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return -delta * this.scrollSettings.amount; } }; Drupal.tableDrag.prototype.setScroll = function (scrollAmount) { var self = this; this.scrollInterval = setInterval(function () { // Update the scroll values stored in the object. self.checkScroll(self.currentMouseCoords.y); var aboveTable = self.scrollY > self.table.topY; var belowTable = self.scrollY + self.windowHeight < self.table.bottomY; if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) { window.scrollBy(0, scrollAmount); } }, this.scrollSettings.interval); }; Drupal.tableDrag.prototype.restripeTable = function () { // :even and :odd are reversed because jQuery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table) .removeClass('odd even') .filter(':odd').addClass('even').end() .filter(':even').addClass('odd'); }; /** * Stub function. Allows a custom handler when a row begins dragging. */ Drupal.tableDrag.prototype.onDrag = function () { return null; }; /** * Stub function. Allows a custom handler when a row is dropped. */ Drupal.tableDrag.prototype.onDrop = function () { return null; }; /** * Constructor to make a new object to manipulate a table row. * * @param tableRow * The DOM element for the table row we will be manipulating. * @param method * The method in which this row is being moved. Either 'keyboard' or 'mouse'. * @param indentEnabled * Whether the containing table uses indentations. Used for optimizations. * @param maxDepth * The maximum amount of indentations this row may contain. * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) { this.element = tableRow; this.method = method; this.group = [tableRow]; this.groupDepth = $('.indentation', tableRow).length; this.changed = false; this.table = $(tableRow).closest('table').get(0); this.indentEnabled = indentEnabled; this.maxDepth = maxDepth; this.direction = ''; // Direction the row is being moved. if (this.indentEnabled) { this.indents = $('.indentation', tableRow).length; this.children = this.findChildren(addClasses); this.group = $.merge(this.group, this.children); // Find the depth of this entire group. for (var n = 0; n < this.group.length; n++) { this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth); } } }; /** * Find all children of rowObject by indentation. * * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) { var parentIndentation = this.indents; var currentRow = $(this.element, this.table).next('tr.draggable'); var rows = []; var child = 0; while (currentRow.length) { var rowIndentation = $('.indentation', currentRow).length; // A greater indentation indicates this is a child. if (rowIndentation > parentIndentation) { child++; rows.push(currentRow[0]); if (addClasses) { $('.indentation', currentRow).each(function (indentNum) { if (child == 1 && (indentNum == parentIndentation)) { $(this).addClass('tree-child-first'); } if (indentNum == parentIndentation) { $(this).addClass('tree-child'); } else if (indentNum > parentIndentation) { $(this).addClass('tree-child-horizontal'); } }); } } else { break; } currentRow = currentRow.next('tr.draggable'); } if (addClasses && rows.length) { $('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last'); } return rows; }; /** * Ensure that two rows are allowed to be swapped. * * @param row * DOM object for the row being considered for swapping. */ Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) { if (this.indentEnabled) { var prevRow, nextRow; if (this.direction == 'down') { prevRow = row; nextRow = $(row).next('tr').get(0); } else { prevRow = $(row).prev('tr').get(0); nextRow = row; } this.interval = this.validIndentInterval(prevRow, nextRow); // We have an invalid swap if the valid indentations interval is empty. if (this.interval.min > this.interval.max) { return false; } } // Do not let an un-draggable first row have anything put before it. if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) { return false; } return true; }; /** * Perform the swap between two rows. * * @param position * Whether the swap will occur 'before' or 'after' the given row. * @param row * DOM element what will be swapped with the row group. */ Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) { Drupal.detachBehaviors(this.group, Drupal.settings, 'move'); $(row)[position](this.group); Drupal.attachBehaviors(this.group, Drupal.settings); this.changed = true; this.onSwap(row); }; /** * Determine the valid indentations interval for the row at a given position * in the table. * * @param prevRow * DOM object for the row before the tested position * (or null for first position in the table). * @param nextRow * DOM object for the row after the tested position * (or null for last position in the table). */ Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) { var minIndent, maxIndent; // Minimum indentation: // Do not orphan the next row. minIndent = nextRow ? $('.indentation', nextRow).length : 0; // Maximum indentation: if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) { // Do not indent: // - the first row in the table, // - rows dragged below a non-draggable row, // - 'root' rows. maxIndent = 0; } else { // Do not go deeper than as a child of the previous row. maxIndent = $('.indentation', prevRow).length + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1); // Limit by the maximum allowed depth for the table. if (this.maxDepth) { maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents)); } } return { 'min': minIndent, 'max': maxIndent }; }; /** * Indent a row within the legal bounds of the table. * * @param indentDiff * The number of additional indentations proposed for the row (can be * positive or negative). This number will be adjusted to nearest valid * indentation level for the row. */ Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) { // Determine the valid indentations interval if not available yet. if (!this.interval) { var prevRow = $(this.element).prev('tr').get(0); var nextRow = $(this.group).filter(':last').next('tr').get(0); this.interval = this.validIndentInterval(prevRow, nextRow); } // Adjust to the nearest valid indentation. var indent = this.indents + indentDiff; indent = Math.max(indent, this.interval.min); indent = Math.min(indent, this.interval.max); indentDiff = indent - this.indents; for (var n = 1; n <= Math.abs(indentDiff); n++) { // Add or remove indentations. if (indentDiff < 0) { $('.indentation:first', this.group).remove(); this.indents--; } else { $('td:first', this.group).prepend(Drupal.theme('tableDragIndentation')); this.indents++; } } if (indentDiff) { // Update indentation for this row. this.changed = true; this.groupDepth += indentDiff; this.onIndent(); } return indentDiff; }; /** * Find all siblings for a row, either according to its subgroup or indentation. * Note that the passed-in row is included in the list of siblings. * * @param settings * The field settings we're using to identify what constitutes a sibling. */ Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) { var siblings = []; var directions = ['prev', 'next']; var rowIndentation = this.indents; for (var d = 0; d < directions.length; d++) { var checkRow = $(this.element)[directions[d]](); while (checkRow.length) { // Check that the sibling contains a similar target field. if ($('.' + rowSettings.target, checkRow)) { // Either add immediately if this is a flat table, or check to ensure // that this row has the same level of indentation. if (this.indentEnabled) { var checkRowIndentation = $('.indentation', checkRow).length; } if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) { siblings.push(checkRow[0]); } else if (checkRowIndentation < rowIndentation) { // No need to keep looking for siblings when we get to a parent. break; } } else { break; } checkRow = $(checkRow)[directions[d]](); } // Since siblings are added in reverse order for previous, reverse the // completed list of previous siblings. Add the current row and continue. if (directions[d] == 'prev') { siblings.reverse(); siblings.push(this.element); } } return siblings; }; /** * Remove indentation helper classes from the current row group. */ Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () { for (var n in this.children) { $('.indentation', this.children[n]) .removeClass('tree-child') .removeClass('tree-child-first') .removeClass('tree-child-last') .removeClass('tree-child-horizontal'); } }; /** * Add an asterisk or other marker to the changed row. */ Drupal.tableDrag.prototype.row.prototype.markChanged = function () { var marker = Drupal.theme('tableDragChangedMarker'); var cell = $('td:first', this.element); if ($('span.tabledrag-changed', cell).length == 0) { cell.append(marker); } }; /** * Stub function. Allows a custom handler when a row is indented. */ Drupal.tableDrag.prototype.row.prototype.onIndent = function () { return null; }; /** * Stub function. Allows a custom handler when a row is swapped. */ Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) { return null; }; Drupal.theme.prototype.tableDragChangedMarker = function () { return '<span class="warning tabledrag-changed">*</span>'; }; Drupal.theme.prototype.tableDragIndentation = function () { return '<div class="indentation">&nbsp;</div>'; }; Drupal.theme.prototype.tableDragChangedWarning = function () { return '<div class="tabledrag-changed-warning messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('Changes made in this table will not be saved until the form is submitted.') + '</div>'; }; })(jQuery);
JavaScript
(function ($) { /** * A progressbar object. Initialized with the given id. Must be inserted into * the DOM afterwards through progressBar.element. * * method is the function which will perform the HTTP request to get the * progress bar state. Either "GET" or "POST". * * e.g. pb = new progressBar('myProgressBar'); * some_element.appendChild(pb.element); */ Drupal.progressBar = function (id, updateCallback, method, errorCallback) { var pb = this; this.id = id; this.method = method || 'GET'; this.updateCallback = updateCallback; this.errorCallback = errorCallback; // The WAI-ARIA setting aria-live="polite" will announce changes after users // have completed their current activity and not interrupt the screen reader. this.element = $('<div class="progress" aria-live="polite"></div>').attr('id', id); this.element.html('<div class="bar"><div class="filled"></div></div>' + '<div class="percentage"></div>' + '<div class="message">&nbsp;</div>'); }; /** * Set the percentage and status message for the progressbar. */ Drupal.progressBar.prototype.setProgress = function (percentage, message) { if (percentage >= 0 && percentage <= 100) { $('div.filled', this.element).css('width', percentage + '%'); $('div.percentage', this.element).html(percentage + '%'); } $('div.message', this.element).html(message); if (this.updateCallback) { this.updateCallback(percentage, message, this); } }; /** * Start monitoring progress via Ajax. */ Drupal.progressBar.prototype.startMonitoring = function (uri, delay) { this.delay = delay; this.uri = uri; this.sendPing(); }; /** * Stop monitoring progress via Ajax. */ Drupal.progressBar.prototype.stopMonitoring = function () { clearTimeout(this.timer); // This allows monitoring to be stopped from within the callback. this.uri = null; }; /** * Request progress data from server. */ Drupal.progressBar.prototype.sendPing = function () { if (this.timer) { clearTimeout(this.timer); } if (this.uri) { var pb = this; // When doing a post request, you need non-null data. Otherwise a // HTTP 411 or HTTP 406 (with Apache mod_security) error may result. $.ajax({ type: this.method, url: this.uri, data: '', dataType: 'json', success: function (progress) { // Display errors. if (progress.status == 0) { pb.displayError(progress.data); return; } // Update display. pb.setProgress(progress.percentage, progress.message); // Schedule next timer. pb.timer = setTimeout(function () { pb.sendPing(); }, pb.delay); }, error: function (xmlhttp) { pb.displayError(Drupal.ajaxError(xmlhttp, pb.uri)); } }); } }; /** * Display errors on the page. */ Drupal.progressBar.prototype.displayError = function (string) { var error = $('<div class="messages error"></div>').html(string); $(this.element).before(error).hide(); if (this.errorCallback) { this.errorCallback(this); } }; })(jQuery);
JavaScript
(function ($) { /** * Attach the machine-readable name form element behavior. */ Drupal.behaviors.machineName = { /** * Attaches the behavior. * * @param settings.machineName * A list of elements to process, keyed by the HTML ID of the form element * containing the human-readable value. Each element is an object defining * the following properties: * - target: The HTML ID of the machine name form element. * - suffix: The HTML ID of a container to show the machine name preview in * (usually a field suffix after the human-readable name form element). * - label: The label to show for the machine name preview. * - replace_pattern: A regular expression (without modifiers) matching * disallowed characters in the machine name; e.g., '[^a-z0-9]+'. * - replace: A character to replace disallowed characters with; e.g., '_' * or '-'. * - standalone: Whether the preview should stay in its own element rather * than the suffix of the source element. * - field_prefix: The #field_prefix of the form element. * - field_suffix: The #field_suffix of the form element. */ attach: function (context, settings) { var self = this; $.each(settings.machineName, function (source_id, options) { var $source = $(source_id, context).addClass('machine-name-source'); var $target = $(options.target, context).addClass('machine-name-target'); var $suffix = $(options.suffix, context); var $wrapper = $target.closest('.form-item'); // All elements have to exist. if (!$source.length || !$target.length || !$suffix.length || !$wrapper.length) { return; } // Skip processing upon a form validation error on the machine name. if ($target.hasClass('error')) { return; } // Figure out the maximum length for the machine name. options.maxlength = $target.attr('maxlength'); // Hide the form item container of the machine name form element. $wrapper.hide(); // Determine the initial machine name value. Unless the machine name form // element is disabled or not empty, the initial default value is based on // the human-readable form element value. if ($target.is(':disabled') || $target.val() != '') { var machine = $target.val(); } else { var machine = self.transliterate($source.val(), options); } // Append the machine name preview to the source field. var $preview = $('<span class="machine-name-value">' + options.field_prefix + Drupal.checkPlain(machine) + options.field_suffix + '</span>'); $suffix.empty(); if (options.label) { $suffix.append(' ').append('<span class="machine-name-label">' + options.label + ':</span>'); } $suffix.append(' ').append($preview); // If the machine name cannot be edited, stop further processing. if ($target.is(':disabled')) { return; } // If it is editable, append an edit link. var $link = $('<span class="admin-link"><a href="#">' + Drupal.t('Edit') + '</a></span>') .click(function () { $wrapper.show(); $target.focus(); $suffix.hide(); $source.unbind('.machineName'); return false; }); $suffix.append(' ').append($link); // Preview the machine name in realtime when the human-readable name // changes, but only if there is no machine name yet; i.e., only upon // initial creation, not when editing. if ($target.val() == '') { $source.bind('keyup.machineName change.machineName', function () { machine = self.transliterate($(this).val(), options); // Set the machine name to the transliterated value. if (machine != '') { if (machine != options.replace) { $target.val(machine); $preview.html(options.field_prefix + Drupal.checkPlain(machine) + options.field_suffix); } $suffix.show(); } else { $suffix.hide(); $target.val(machine); $preview.empty(); } }); // Initialize machine name preview. $source.keyup(); } }); }, /** * Transliterate a human-readable name to a machine name. * * @param source * A string to transliterate. * @param settings * The machine name settings for the corresponding field, containing: * - replace_pattern: A regular expression (without modifiers) matching * disallowed characters in the machine name; e.g., '[^a-z0-9]+'. * - replace: A character to replace disallowed characters with; e.g., '_' * or '-'. * - maxlength: The maximum length of the machine name. * * @return * The transliterated source string. */ transliterate: function (source, settings) { var rx = new RegExp(settings.replace_pattern, 'g'); return source.toLowerCase().replace(rx, settings.replace).substr(0, settings.maxlength); } }; })(jQuery);
JavaScript
(function ($) { Drupal.behaviors.tableSelect = { attach: function (context, settings) { // Select the inner-most table in case of nested tables. $('th.select-all', context).closest('table').once('table-select', Drupal.tableSelect); } }; Drupal.tableSelect = function () { // Do not add a "Select all" checkbox if there are no rows with checkboxes in the table if ($('td input:checkbox', this).length == 0) { return; } // Keep track of the table, which checkbox is checked and alias the settings. var table = this, checkboxes, lastChecked; var strings = { 'selectAll': Drupal.t('Select all rows in this table'), 'selectNone': Drupal.t('Deselect all rows in this table') }; var updateSelectAll = function (state) { // Update table's select-all checkbox (and sticky header's if available). $(table).prev('table.sticky-header').andSelf().find('th.select-all input:checkbox').each(function() { $(this).attr('title', state ? strings.selectNone : strings.selectAll); this.checked = state; }); }; // Find all <th> with class select-all, and insert the check all checkbox. $('th.select-all', table).prepend($('<input type="checkbox" class="form-checkbox" />').attr('title', strings.selectAll)).click(function (event) { if ($(event.target).is('input:checkbox')) { // Loop through all checkboxes and set their state to the select all checkbox' state. checkboxes.each(function () { this.checked = event.target.checked; // Either add or remove the selected class based on the state of the check all checkbox. $(this).closest('tr').toggleClass('selected', this.checked); }); // Update the title and the state of the check all box. updateSelectAll(event.target.checked); } }); // For each of the checkboxes within the table that are not disabled. checkboxes = $('td input:checkbox:enabled', table).click(function (e) { // Either add or remove the selected class based on the state of the check all checkbox. $(this).closest('tr').toggleClass('selected', this.checked); // If this is a shift click, we need to highlight everything in the range. // Also make sure that we are actually checking checkboxes over a range and // that a checkbox has been checked or unchecked before. if (e.shiftKey && lastChecked && lastChecked != e.target) { // We use the checkbox's parent TR to do our range searching. Drupal.tableSelectRange($(e.target).closest('tr')[0], $(lastChecked).closest('tr')[0], e.target.checked); } // If all checkboxes are checked, make sure the select-all one is checked too, otherwise keep unchecked. updateSelectAll((checkboxes.length == $(checkboxes).filter(':checked').length)); // Keep track of the last checked checkbox. lastChecked = e.target; }); }; Drupal.tableSelectRange = function (from, to, state) { // We determine the looping mode based on the the order of from and to. var mode = from.rowIndex > to.rowIndex ? 'previousSibling' : 'nextSibling'; // Traverse through the sibling nodes. for (var i = from[mode]; i; i = i[mode]) { // Make sure that we're only dealing with elements. if (i.nodeType != 1) { continue; } // Either add or remove the selected class based on the state of the target checkbox. $(i).toggleClass('selected', state); $('input:checkbox', i).each(function () { this.checked = state; }); if (to.nodeType) { // If we are at the end of the range, stop. if (i == to) { break; } } // A faster alternative to doing $(i).filter(to).length. else if ($.filter(to, [i]).r.length) { break; } } }; })(jQuery);
JavaScript
/** * jQuery Once Plugin v1.2 * http://plugins.jquery.com/project/once * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function ($) { var cache = {}, uuid = 0; /** * Filters elements by whether they have not yet been processed. * * @param id * (Optional) If this is a string, then it will be used as the CSS class * name that is applied to the elements for determining whether it has * already been processed. The elements will get a class in the form of * "id-processed". * * If the id parameter is a function, it will be passed off to the fn * parameter and the id will become a unique identifier, represented as a * number. * * When the id is neither a string or a function, it becomes a unique * identifier, depicted as a number. The element's class will then be * represented in the form of "jquery-once-#-processed". * * Take note that the id must be valid for usage as an element's class name. * @param fn * (Optional) If given, this function will be called for each element that * has not yet been processed. The function's return value follows the same * logic as $.each(). Returning true will continue to the next matched * element in the set, while returning false will entirely break the * iteration. */ $.fn.once = function (id, fn) { if (typeof id != 'string') { // Generate a numeric ID if the id passed can't be used as a CSS class. if (!(id in cache)) { cache[id] = ++uuid; } // When the fn parameter is not passed, we interpret it from the id. if (!fn) { fn = id; } id = 'jquery-once-' + cache[id]; } // Remove elements from the set that have already been processed. var name = id + '-processed'; var elements = this.not('.' + name).addClass(name); return $.isFunction(fn) ? elements.each(fn) : elements; }; /** * Filters elements that have been processed once already. * * @param id * A required string representing the name of the class which should be used * when filtering the elements. This only filters elements that have already * been processed by the once function. The id should be the same id that * was originally passed to the once() function. * @param fn * (Optional) If given, this function will be called for each element that * has not yet been processed. The function's return value follows the same * logic as $.each(). Returning true will continue to the next matched * element in the set, while returning false will entirely break the * iteration. */ $.fn.removeOnce = function (id, fn) { var name = id + '-processed'; var elements = this.filter('.' + name).removeClass(name); return $.isFunction(fn) ? elements.each(fn) : elements; }; })(jQuery);
JavaScript
/** * @file * Conditionally hide or show the appropriate settings and saved defaults * on the file transfer connection settings form used by authorize.php. */ (function ($) { Drupal.behaviors.authorizeFileTransferForm = { attach: function(context) { $('#edit-connection-settings-authorize-filetransfer-default').change(function() { $('.filetransfer').hide().filter('.filetransfer-' + $(this).val()).show(); }); $('.filetransfer').hide().filter('.filetransfer-' + $('#edit-connection-settings-authorize-filetransfer-default').val()).show(); // Removes the float on the select box (used for non-JS interface). if ($('.connection-settings-update-filetransfer-default-wrapper').length > 0) { $('.connection-settings-update-filetransfer-default-wrapper').css('float', 'none'); } // Hides the submit button for non-js users. $('#edit-submit-connection').hide(); $('#edit-submit-process').show(); } }; })(jQuery);
JavaScript
(function ($) { /** * Retrieves the summary for the first element. */ $.fn.drupalGetSummary = function () { var callback = this.data('summaryCallback'); return (this[0] && callback) ? $.trim(callback(this[0])) : ''; }; /** * Sets the summary for all matched elements. * * @param callback * Either a function that will be called each time the summary is * retrieved or a string (which is returned each time). */ $.fn.drupalSetSummary = function (callback) { var self = this; // To facilitate things, the callback should always be a function. If it's // not, we wrap it into an anonymous function which just returns the value. if (typeof callback != 'function') { var val = callback; callback = function () { return val; }; } return this .data('summaryCallback', callback) // To prevent duplicate events, the handlers are first removed and then // (re-)added. .unbind('formUpdated.summary') .bind('formUpdated.summary', function () { self.trigger('summaryUpdated'); }) // The actual summaryUpdated handler doesn't fire when the callback is // changed, so we have to do this manually. .trigger('summaryUpdated'); }; /** * Sends a 'formUpdated' event each time a form element is modified. */ Drupal.behaviors.formUpdated = { attach: function (context) { // These events are namespaced so that we can remove them later. var events = 'change.formUpdated click.formUpdated blur.formUpdated keyup.formUpdated'; $(context) // Since context could be an input element itself, it's added back to // the jQuery object and filtered again. .find(':input').andSelf().filter(':input') // To prevent duplicate events, the handlers are first removed and then // (re-)added. .unbind(events).bind(events, function () { $(this).trigger('formUpdated'); }); } }; /** * Prepopulate form fields with information from the visitor cookie. */ Drupal.behaviors.fillUserInfoFromCookie = { attach: function (context, settings) { $('form.user-info-from-cookie').once('user-info-from-cookie', function () { var formContext = this; $.each(['name', 'mail', 'homepage'], function () { var $element = $('[name=' + this + ']', formContext); var cookie = $.cookie('Drupal.visitor.' + this); if ($element.length && cookie) { $element.val(cookie); } }); }); } }; })(jQuery);
JavaScript
(function ($) { /** * The base States namespace. * * Having the local states variable allows us to use the States namespace * without having to always declare "Drupal.states". */ var states = Drupal.states = { // An array of functions that should be postponed. postponed: [] }; /** * Attaches the states. */ Drupal.behaviors.states = { attach: function (context, settings) { var $context = $(context); for (var selector in settings.states) { for (var state in settings.states[selector]) { new states.Dependent({ element: $context.find(selector), state: states.State.sanitize(state), constraints: settings.states[selector][state] }); } } // Execute all postponed functions now. while (states.postponed.length) { (states.postponed.shift())(); } } }; /** * Object representing an element that depends on other elements. * * @param args * Object with the following keys (all of which are required): * - element: A jQuery object of the dependent element * - state: A State object describing the state that is dependent * - constraints: An object with dependency specifications. Lists all elements * that this element depends on. It can be nested and can contain arbitrary * AND and OR clauses. */ states.Dependent = function (args) { $.extend(this, { values: {}, oldValue: null }, args); this.dependees = this.getDependees(); for (var selector in this.dependees) { this.initializeDependee(selector, this.dependees[selector]); } }; /** * Comparison functions for comparing the value of an element with the * specification from the dependency settings. If the object type can't be * found in this list, the === operator is used by default. */ states.Dependent.comparisons = { 'RegExp': function (reference, value) { return reference.test(value); }, 'Function': function (reference, value) { // The "reference" variable is a comparison function. return reference(value); }, 'Number': function (reference, value) { // If "reference" is a number and "value" is a string, then cast reference // as a string before applying the strict comparison in compare(). Otherwise // numeric keys in the form's #states array fail to match string values // returned from jQuery's val(). return (typeof value === 'string') ? compare(reference.toString(), value) : compare(reference, value); } }; states.Dependent.prototype = { /** * Initializes one of the elements this dependent depends on. * * @param selector * The CSS selector describing the dependee. * @param dependeeStates * The list of states that have to be monitored for tracking the * dependee's compliance status. */ initializeDependee: function (selector, dependeeStates) { var state; // Cache for the states of this dependee. this.values[selector] = {}; for (var i in dependeeStates) { if (dependeeStates.hasOwnProperty(i)) { state = dependeeStates[i]; // Make sure we're not initializing this selector/state combination twice. if ($.inArray(state, dependeeStates) === -1) { continue; } state = states.State.sanitize(state); // Initialize the value of this state. this.values[selector][state.name] = null; // Monitor state changes of the specified state for this dependee. $(selector).bind('state:' + state, $.proxy(function (e) { this.update(selector, state, e.value); }, this)); // Make sure the event we just bound ourselves to is actually fired. new states.Trigger({ selector: selector, state: state }); } } }, /** * Compares a value with a reference value. * * @param reference * The value used for reference. * @param selector * CSS selector describing the dependee. * @param state * A State object describing the dependee's updated state. * * @return * true or false. */ compare: function (reference, selector, state) { var value = this.values[selector][state.name]; if (reference.constructor.name in states.Dependent.comparisons) { // Use a custom compare function for certain reference value types. return states.Dependent.comparisons[reference.constructor.name](reference, value); } else { // Do a plain comparison otherwise. return compare(reference, value); } }, /** * Update the value of a dependee's state. * * @param selector * CSS selector describing the dependee. * @param state * A State object describing the dependee's updated state. * @param value * The new value for the dependee's updated state. */ update: function (selector, state, value) { // Only act when the 'new' value is actually new. if (value !== this.values[selector][state.name]) { this.values[selector][state.name] = value; this.reevaluate(); } }, /** * Triggers change events in case a state changed. */ reevaluate: function () { // Check whether any constraint for this dependent state is satisifed. var value = this.verifyConstraints(this.constraints); // Only invoke a state change event when the value actually changed. if (value !== this.oldValue) { // Store the new value so that we can compare later whether the value // actually changed. this.oldValue = value; // Normalize the value to match the normalized state name. value = invert(value, this.state.invert); // By adding "trigger: true", we ensure that state changes don't go into // infinite loops. this.element.trigger({ type: 'state:' + this.state, value: value, trigger: true }); } }, /** * Evaluates child constraints to determine if a constraint is satisfied. * * @param constraints * A constraint object or an array of constraints. * @param selector * The selector for these constraints. If undefined, there isn't yet a * selector that these constraints apply to. In that case, the keys of the * object are interpreted as the selector if encountered. * * @return * true or false, depending on whether these constraints are satisfied. */ verifyConstraints: function(constraints, selector) { var result; if ($.isArray(constraints)) { // This constraint is an array (OR or XOR). var hasXor = $.inArray('xor', constraints) === -1; for (var i = 0, len = constraints.length; i < len; i++) { if (constraints[i] != 'xor') { var constraint = this.checkConstraints(constraints[i], selector, i); // Return if this is OR and we have a satisfied constraint or if this // is XOR and we have a second satisfied constraint. if (constraint && (hasXor || result)) { return hasXor; } result = result || constraint; } } } // Make sure we don't try to iterate over things other than objects. This // shouldn't normally occur, but in case the condition definition is bogus, // we don't want to end up with an infinite loop. else if ($.isPlainObject(constraints)) { // This constraint is an object (AND). for (var n in constraints) { if (constraints.hasOwnProperty(n)) { result = ternary(result, this.checkConstraints(constraints[n], selector, n)); // False and anything else will evaluate to false, so return when any // false condition is found. if (result === false) { return false; } } } } return result; }, /** * Checks whether the value matches the requirements for this constraint. * * @param value * Either the value of a state or an array/object of constraints. In the * latter case, resolving the constraint continues. * @param selector * The selector for this constraint. If undefined, there isn't yet a * selector that this constraint applies to. In that case, the state key is * propagates to a selector and resolving continues. * @param state * The state to check for this constraint. If undefined, resolving * continues. * If both selector and state aren't undefined and valid non-numeric * strings, a lookup for the actual value of that selector's state is * performed. This parameter is not a State object but a pristine state * string. * * @return * true or false, depending on whether this constraint is satisfied. */ checkConstraints: function(value, selector, state) { // Normalize the last parameter. If it's non-numeric, we treat it either as // a selector (in case there isn't one yet) or as a trigger/state. if (typeof state !== 'string' || (/[0-9]/).test(state[0])) { state = null; } else if (typeof selector === 'undefined') { // Propagate the state to the selector when there isn't one yet. selector = state; state = null; } if (state !== null) { // constraints is the actual constraints of an element to check for. state = states.State.sanitize(state); return invert(this.compare(value, selector, state), state.invert); } else { // Resolve this constraint as an AND/OR operator. return this.verifyConstraints(value, selector); } }, /** * Gathers information about all required triggers. */ getDependees: function() { var cache = {}; // Swivel the lookup function so that we can record all available selector- // state combinations for initialization. var _compare = this.compare; this.compare = function(reference, selector, state) { (cache[selector] || (cache[selector] = [])).push(state.name); // Return nothing (=== undefined) so that the constraint loops are not // broken. }; // This call doesn't actually verify anything but uses the resolving // mechanism to go through the constraints array, trying to look up each // value. Since we swivelled the compare function, this comparison returns // undefined and lookup continues until the very end. Instead of lookup up // the value, we record that combination of selector and state so that we // can initialize all triggers. this.verifyConstraints(this.constraints); // Restore the original function. this.compare = _compare; return cache; } }; states.Trigger = function (args) { $.extend(this, args); if (this.state in states.Trigger.states) { this.element = $(this.selector); // Only call the trigger initializer when it wasn't yet attached to this // element. Otherwise we'd end up with duplicate events. if (!this.element.data('trigger:' + this.state)) { this.initialize(); } } }; states.Trigger.prototype = { initialize: function () { var trigger = states.Trigger.states[this.state]; if (typeof trigger == 'function') { // We have a custom trigger initialization function. trigger.call(window, this.element); } else { for (var event in trigger) { if (trigger.hasOwnProperty(event)) { this.defaultTrigger(event, trigger[event]); } } } // Mark this trigger as initialized for this element. this.element.data('trigger:' + this.state, true); }, defaultTrigger: function (event, valueFn) { var oldValue = valueFn.call(this.element); // Attach the event callback. this.element.bind(event, $.proxy(function (e) { var value = valueFn.call(this.element, e); // Only trigger the event if the value has actually changed. if (oldValue !== value) { this.element.trigger({ type: 'state:' + this.state, value: value, oldValue: oldValue }); oldValue = value; } }, this)); states.postponed.push($.proxy(function () { // Trigger the event once for initialization purposes. this.element.trigger({ type: 'state:' + this.state, value: oldValue, oldValue: null }); }, this)); } }; /** * This list of states contains functions that are used to monitor the state * of an element. Whenever an element depends on the state of another element, * one of these trigger functions is added to the dependee so that the * dependent element can be updated. */ states.Trigger.states = { // 'empty' describes the state to be monitored empty: { // 'keyup' is the (native DOM) event that we watch for. 'keyup': function () { // The function associated to that trigger returns the new value for the // state. return this.val() == ''; } }, checked: { 'change': function () { return this.attr('checked'); } }, // For radio buttons, only return the value if the radio button is selected. value: { 'keyup': function () { // Radio buttons share the same :input[name="key"] selector. if (this.length > 1) { // Initial checked value of radios is undefined, so we return false. return this.filter(':checked').val() || false; } return this.val(); }, 'change': function () { // Radio buttons share the same :input[name="key"] selector. if (this.length > 1) { // Initial checked value of radios is undefined, so we return false. return this.filter(':checked').val() || false; } return this.val(); } }, collapsed: { 'collapsed': function(e) { return (typeof e !== 'undefined' && 'value' in e) ? e.value : this.is('.collapsed'); } } }; /** * A state object is used for describing the state and performing aliasing. */ states.State = function(state) { // We may need the original unresolved name later. this.pristine = this.name = state; // Normalize the state name. while (true) { // Iteratively remove exclamation marks and invert the value. while (this.name.charAt(0) == '!') { this.name = this.name.substring(1); this.invert = !this.invert; } // Replace the state with its normalized name. if (this.name in states.State.aliases) { this.name = states.State.aliases[this.name]; } else { break; } } }; /** * Creates a new State object by sanitizing the passed value. */ states.State.sanitize = function (state) { if (state instanceof states.State) { return state; } else { return new states.State(state); } }; /** * This list of aliases is used to normalize states and associates negated names * with their respective inverse state. */ states.State.aliases = { 'enabled': '!disabled', 'invisible': '!visible', 'invalid': '!valid', 'untouched': '!touched', 'optional': '!required', 'filled': '!empty', 'unchecked': '!checked', 'irrelevant': '!relevant', 'expanded': '!collapsed', 'readwrite': '!readonly' }; states.State.prototype = { invert: false, /** * Ensures that just using the state object returns the name. */ toString: function() { return this.name; } }; /** * Global state change handlers. These are bound to "document" to cover all * elements whose state changes. Events sent to elements within the page * bubble up to these handlers. We use this system so that themes and modules * can override these state change handlers for particular parts of a page. */ $(document).bind('state:disabled', function(e) { // Only act when this change was triggered by a dependency and not by the // element monitoring itself. if (e.trigger) { $(e.target) .attr('disabled', e.value) .closest('.form-item, .form-submit, .form-wrapper').toggleClass('form-disabled', e.value) .find('select, input, textarea').attr('disabled', e.value); // Note: WebKit nightlies don't reflect that change correctly. // See https://bugs.webkit.org/show_bug.cgi?id=23789 } }); $(document).bind('state:required', function(e) { if (e.trigger) { if (e.value) { $(e.target).closest('.form-item, .form-wrapper').find('label').append('<span class="form-required">*</span>'); } else { $(e.target).closest('.form-item, .form-wrapper').find('label .form-required').remove(); } } }); $(document).bind('state:visible', function(e) { if (e.trigger) { $(e.target).closest('.form-item, .form-submit, .form-wrapper').toggle(e.value); } }); $(document).bind('state:checked', function(e) { if (e.trigger) { $(e.target).attr('checked', e.value); } }); $(document).bind('state:collapsed', function(e) { if (e.trigger) { if ($(e.target).is('.collapsed') !== e.value) { $('> legend a', e.target).click(); } } }); /** * These are helper functions implementing addition "operators" and don't * implement any logic that is particular to states. */ // Bitwise AND with a third undefined state. function ternary (a, b) { return typeof a === 'undefined' ? b : (typeof b === 'undefined' ? a : a && b); } // Inverts a (if it's not undefined) when invert is true. function invert (a, invert) { return (invert && typeof a !== 'undefined') ? !a : a; } // Compares two values while ignoring undefined values. function compare (a, b) { return (a === b) ? (typeof a === 'undefined' ? a : true) : (typeof a === 'undefined' || typeof b === 'undefined'); } })(jQuery);
JavaScript
(function ($) { /** * Attaches the batch behavior to progress bars. */ Drupal.behaviors.batch = { attach: function (context, settings) { $('#progress', context).once('batch', function () { var holder = $(this); // Success: redirect to the summary. var updateCallback = function (progress, status, pb) { if (progress == 100) { pb.stopMonitoring(); window.location = settings.batch.uri + '&op=finished'; } }; var errorCallback = function (pb) { holder.prepend($('<p class="error"></p>').html(settings.batch.errorMessage)); $('#wait').hide(); }; var progress = new Drupal.progressBar('updateprogress', updateCallback, 'POST', errorCallback); progress.setProgress(-1, settings.batch.initMessage); holder.append(progress.element); progress.startMonitoring(settings.batch.uri + '&op=do', 10); }); } }; })(jQuery);
JavaScript
(function ($) { Drupal.behaviors.textarea = { attach: function (context, settings) { $('.form-textarea-wrapper.resizable', context).once('textarea', function () { var staticOffset = null; var textarea = $(this).addClass('resizable-textarea').find('textarea'); var grippie = $('<div class="grippie"></div>').mousedown(startDrag); grippie.insertAfter(textarea); function startDrag(e) { staticOffset = textarea.height() - e.pageY; textarea.css('opacity', 0.25); $(document).mousemove(performDrag).mouseup(endDrag); return false; } function performDrag(e) { textarea.height(Math.max(32, staticOffset + e.pageY) + 'px'); return false; } function endDrag(e) { $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag); textarea.css('opacity', 1); } }); } }; })(jQuery);
JavaScript