code
stringlengths
1
2.08M
language
stringclasses
1 value
#!/usr/bin/env node /* * jQuery File Upload Plugin Node.js Example 2.1.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2012, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /* jshint nomen:false */ /* global require, __dirname, unescape, console */ (function (port) { 'use strict'; var path = require('path'), fs = require('fs'), // Since Node 0.8, .existsSync() moved from path to fs: _existsSync = fs.existsSync || path.existsSync, formidable = require('formidable'), nodeStatic = require('node-static'), imageMagick = require('imagemagick'), options = { tmpDir: __dirname + '/tmp', publicDir: __dirname + '/public', uploadDir: __dirname + '/public/files', uploadUrl: '/files/', maxPostSize: 11000000000, // 11 GB minFileSize: 1, maxFileSize: 10000000000, // 10 GB acceptFileTypes: /.+/i, // Files not matched by this regular expression force a download dialog, // to prevent executing any scripts in the context of the service domain: inlineFileTypes: /\.(gif|jpe?g|png)$/i, imageTypes: /\.(gif|jpe?g|png)$/i, imageVersions: { 'thumbnail': { width: 80, height: 80 } }, accessControl: { allowOrigin: '*', allowMethods: 'OPTIONS, HEAD, GET, POST, PUT, DELETE', allowHeaders: 'Content-Type, Content-Range, Content-Disposition' }, /* Uncomment and edit this section to provide the service via HTTPS: ssl: { key: fs.readFileSync('/Applications/XAMPP/etc/ssl.key/server.key'), cert: fs.readFileSync('/Applications/XAMPP/etc/ssl.crt/server.crt') }, */ nodeStatic: { cache: 3600 // seconds to cache served files } }, utf8encode = function (str) { return unescape(encodeURIComponent(str)); }, fileServer = new nodeStatic.Server(options.publicDir, options.nodeStatic), nameCountRegexp = /(?:(?: \(([\d]+)\))?(\.[^.]+))?$/, nameCountFunc = function (s, index, ext) { return ' (' + ((parseInt(index, 10) || 0) + 1) + ')' + (ext || ''); }, FileInfo = function (file) { this.name = file.name; this.size = file.size; this.type = file.type; this.deleteType = 'DELETE'; }, UploadHandler = function (req, res, callback) { this.req = req; this.res = res; this.callback = callback; }, serve = function (req, res) { res.setHeader( 'Access-Control-Allow-Origin', options.accessControl.allowOrigin ); res.setHeader( 'Access-Control-Allow-Methods', options.accessControl.allowMethods ); res.setHeader( 'Access-Control-Allow-Headers', options.accessControl.allowHeaders ); var handleResult = function (result, redirect) { if (redirect) { res.writeHead(302, { 'Location': redirect.replace( /%s/, encodeURIComponent(JSON.stringify(result)) ) }); res.end(); } else { res.writeHead(200, { 'Content-Type': req.headers.accept .indexOf('application/json') !== -1 ? 'application/json' : 'text/plain' }); res.end(JSON.stringify(result)); } }, setNoCacheHeaders = function () { res.setHeader('Pragma', 'no-cache'); res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate'); res.setHeader('Content-Disposition', 'inline; filename="files.json"'); }, handler = new UploadHandler(req, res, handleResult); switch (req.method) { case 'OPTIONS': res.end(); break; case 'HEAD': case 'GET': if (req.url === '/') { setNoCacheHeaders(); if (req.method === 'GET') { handler.get(); } else { res.end(); } } else { fileServer.serve(req, res); } break; case 'POST': setNoCacheHeaders(); handler.post(); break; case 'DELETE': handler.destroy(); break; default: res.statusCode = 405; res.end(); } }; fileServer.respond = function (pathname, status, _headers, files, stat, req, res, finish) { // Prevent browsers from MIME-sniffing the content-type: _headers['X-Content-Type-Options'] = 'nosniff'; if (!options.inlineFileTypes.test(files[0])) { // Force a download dialog for unsafe file extensions: _headers['Content-Type'] = 'application/octet-stream'; _headers['Content-Disposition'] = 'attachment; filename="' + utf8encode(path.basename(files[0])) + '"'; } nodeStatic.Server.prototype.respond .call(this, pathname, status, _headers, files, stat, req, res, finish); }; FileInfo.prototype.validate = function () { if (options.minFileSize && options.minFileSize > this.size) { this.error = 'File is too small'; } else if (options.maxFileSize && options.maxFileSize < this.size) { this.error = 'File is too big'; } else if (!options.acceptFileTypes.test(this.name)) { this.error = 'Filetype not allowed'; } return !this.error; }; FileInfo.prototype.safeName = function () { // Prevent directory traversal and creating hidden system files: this.name = path.basename(this.name).replace(/^\.+/, ''); // Prevent overwriting existing files: while (_existsSync(options.uploadDir + '/' + this.name)) { this.name = this.name.replace(nameCountRegexp, nameCountFunc); } }; FileInfo.prototype.initUrls = function (req) { if (!this.error) { var that = this, baseUrl = (options.ssl ? 'https:' : 'http:') + '//' + req.headers.host + options.uploadUrl; this.url = this.deleteUrl = baseUrl + encodeURIComponent(this.name); Object.keys(options.imageVersions).forEach(function (version) { if (_existsSync( options.uploadDir + '/' + version + '/' + that.name )) { that[version + 'Url'] = baseUrl + version + '/' + encodeURIComponent(that.name); } }); } }; UploadHandler.prototype.get = function () { var handler = this, files = []; fs.readdir(options.uploadDir, function (err, list) { list.forEach(function (name) { var stats = fs.statSync(options.uploadDir + '/' + name), fileInfo; if (stats.isFile() && name[0] !== '.') { fileInfo = new FileInfo({ name: name, size: stats.size }); fileInfo.initUrls(handler.req); files.push(fileInfo); } }); handler.callback({files: files}); }); }; UploadHandler.prototype.post = function () { var handler = this, form = new formidable.IncomingForm(), tmpFiles = [], files = [], map = {}, counter = 1, redirect, finish = function () { counter -= 1; if (!counter) { files.forEach(function (fileInfo) { fileInfo.initUrls(handler.req); }); handler.callback({files: files}, redirect); } }; form.uploadDir = options.tmpDir; form.on('fileBegin', function (name, file) { tmpFiles.push(file.path); var fileInfo = new FileInfo(file, handler.req, true); fileInfo.safeName(); map[path.basename(file.path)] = fileInfo; files.push(fileInfo); }).on('field', function (name, value) { if (name === 'redirect') { redirect = value; } }).on('file', function (name, file) { var fileInfo = map[path.basename(file.path)]; fileInfo.size = file.size; if (!fileInfo.validate()) { fs.unlink(file.path); return; } fs.renameSync(file.path, options.uploadDir + '/' + fileInfo.name); if (options.imageTypes.test(fileInfo.name)) { Object.keys(options.imageVersions).forEach(function (version) { counter += 1; var opts = options.imageVersions[version]; imageMagick.resize({ width: opts.width, height: opts.height, srcPath: options.uploadDir + '/' + fileInfo.name, dstPath: options.uploadDir + '/' + version + '/' + fileInfo.name }, finish); }); } }).on('aborted', function () { tmpFiles.forEach(function (file) { fs.unlink(file); }); }).on('error', function (e) { console.log(e); }).on('progress', function (bytesReceived) { if (bytesReceived > options.maxPostSize) { handler.req.connection.destroy(); } }).on('end', finish).parse(handler.req); }; UploadHandler.prototype.destroy = function () { var handler = this, fileName; if (handler.req.url.slice(0, options.uploadUrl.length) === options.uploadUrl) { fileName = path.basename(decodeURIComponent(handler.req.url)); if (fileName[0] !== '.') { fs.unlink(options.uploadDir + '/' + fileName, function (ex) { Object.keys(options.imageVersions).forEach(function (version) { fs.unlink(options.uploadDir + '/' + version + '/' + fileName); }); handler.callback({success: !ex}); }); return; } } handler.callback({success: false}); }; if (options.ssl) { require('https').createServer(options.ssl, serve).listen(port); } else { require('http').createServer(serve).listen(port); } }(8888));
JavaScript
/** * @license Input Mask plugin for jquery * http://github.com/RobinHerbots/jquery.inputmask * Copyright (c) 2010 - 2014 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 2.4.18 */ (function ($) { if ($.fn.inputmask === undefined) { //helper functions function isInputEventSupported(eventName) { var el = document.createElement('input'), eventName = 'on' + eventName, isSupported = (eventName in el); if (!isSupported) { el.setAttribute(eventName, 'return;'); isSupported = typeof el[eventName] == 'function'; } el = null; return isSupported; } function resolveAlias(aliasStr, options, opts) { var aliasDefinition = opts.aliases[aliasStr]; if (aliasDefinition) { if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias $.extend(true, opts, aliasDefinition); //merge alias definition in the options $.extend(true, opts, options); //reapply extra given options return true; } return false; } function generateMaskSets(opts) { var ms = []; var genmasks = []; //used to keep track of the masks that where processed, to avoid duplicates function getMaskTemplate(mask) { if (opts.numericInput) { mask = mask.split('').reverse().join(''); } var escaped = false, outCount = 0, greedy = opts.greedy, repeat = opts.repeat; if (repeat == "*") greedy = false; //if (greedy == true && opts.placeholder == "") opts.placeholder = " "; if (mask.length == 1 && greedy == false && repeat != 0) { opts.placeholder = ""; } //hide placeholder with single non-greedy mask var singleMask = $.map(mask.split(""), function (element, index) { var outElem = []; if (element == opts.escapeChar) { escaped = true; } else if ((element != opts.optionalmarker.start && element != opts.optionalmarker.end) || escaped) { var maskdef = opts.definitions[element]; if (maskdef && !escaped) { for (var i = 0; i < maskdef.cardinality; i++) { outElem.push(opts.placeholder.charAt((outCount + i) % opts.placeholder.length)); } } else { outElem.push(element); escaped = false; } outCount += outElem.length; return outElem; } }); //allocate repetitions var repeatedMask = singleMask.slice(); for (var i = 1; i < repeat && greedy; i++) { repeatedMask = repeatedMask.concat(singleMask.slice()); } return { "mask": repeatedMask, "repeat": repeat, "greedy": greedy }; } //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, offset: int, casing: null/upper/lower, def: definitionSymbol} function getTestingChain(mask) { if (opts.numericInput) { mask = mask.split('').reverse().join(''); } var isOptional = false, escaped = false; var newBlockMarker = false; //indicates wheter the begin/ending of a block should be indicated return $.map(mask.split(""), function (element, index) { var outElem = []; if (element == opts.escapeChar) { escaped = true; } else if (element == opts.optionalmarker.start && !escaped) { isOptional = true; newBlockMarker = true; } else if (element == opts.optionalmarker.end && !escaped) { isOptional = false; newBlockMarker = true; } else { var maskdef = opts.definitions[element]; if (maskdef && !escaped) { var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0; for (var i = 1; i < maskdef.cardinality; i++) { var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"]; outElem.push({ fn: validator ? typeof validator == 'string' ? new RegExp(validator) : new function () { this.test = validator; } : new RegExp("."), cardinality: cardinality ? cardinality : 1, optionality: isOptional, newBlockMarker: isOptional == true ? newBlockMarker : false, offset: 0, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element }); if (isOptional == true) //reset newBlockMarker newBlockMarker = false; } outElem.push({ fn: maskdef.validator ? typeof maskdef.validator == 'string' ? new RegExp(maskdef.validator) : new function () { this.test = maskdef.validator; } : new RegExp("."), cardinality: maskdef.cardinality, optionality: isOptional, newBlockMarker: newBlockMarker, offset: 0, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element }); } else { outElem.push({ fn: null, cardinality: 0, optionality: isOptional, newBlockMarker: newBlockMarker, offset: 0, casing: null, def: element }); escaped = false; } //reset newBlockMarker newBlockMarker = false; return outElem; } }); } function markOptional(maskPart) { //needed for the clearOptionalTail functionality return opts.optionalmarker.start + maskPart + opts.optionalmarker.end; } function splitFirstOptionalEndPart(maskPart) { var optionalStartMarkers = 0, optionalEndMarkers = 0, mpl = maskPart.length; for (var i = 0; i < mpl; i++) { if (maskPart.charAt(i) == opts.optionalmarker.start) { optionalStartMarkers++; } if (maskPart.charAt(i) == opts.optionalmarker.end) { optionalEndMarkers++; } if (optionalStartMarkers > 0 && optionalStartMarkers == optionalEndMarkers) break; } var maskParts = [maskPart.substring(0, i)]; if (i < mpl) { maskParts.push(maskPart.substring(i + 1, mpl)); } return maskParts; } function splitFirstOptionalStartPart(maskPart) { var mpl = maskPart.length; for (var i = 0; i < mpl; i++) { if (maskPart.charAt(i) == opts.optionalmarker.start) { break; } } var maskParts = [maskPart.substring(0, i)]; if (i < mpl) { maskParts.push(maskPart.substring(i + 1, mpl)); } return maskParts; } function generateMask(maskPrefix, maskPart, metadata) { var maskParts = splitFirstOptionalEndPart(maskPart); var newMask, maskTemplate; var masks = splitFirstOptionalStartPart(maskParts[0]); if (masks.length > 1) { newMask = maskPrefix + masks[0] + markOptional(masks[1]) + (maskParts.length > 1 ? maskParts[1] : ""); if ($.inArray(newMask, genmasks) == -1 && newMask != "") { genmasks.push(newMask); maskTemplate = getMaskTemplate(newMask); ms.push({ "mask": newMask, "_buffer": maskTemplate["mask"], "buffer": maskTemplate["mask"].slice(), "tests": getTestingChain(newMask), "lastValidPosition": -1, "greedy": maskTemplate["greedy"], "repeat": maskTemplate["repeat"], "metadata": metadata }); } newMask = maskPrefix + masks[0] + (maskParts.length > 1 ? maskParts[1] : ""); if ($.inArray(newMask, genmasks) == -1 && newMask != "") { genmasks.push(newMask); maskTemplate = getMaskTemplate(newMask); ms.push({ "mask": newMask, "_buffer": maskTemplate["mask"], "buffer": maskTemplate["mask"].slice(), "tests": getTestingChain(newMask), "lastValidPosition": -1, "greedy": maskTemplate["greedy"], "repeat": maskTemplate["repeat"], "metadata": metadata }); } if (splitFirstOptionalStartPart(masks[1]).length > 1) { //optional contains another optional generateMask(maskPrefix + masks[0], masks[1] + maskParts[1], metadata); } if (maskParts.length > 1 && splitFirstOptionalStartPart(maskParts[1]).length > 1) { generateMask(maskPrefix + masks[0] + markOptional(masks[1]), maskParts[1], metadata); generateMask(maskPrefix + masks[0], maskParts[1], metadata); } } else { newMask = maskPrefix + maskParts; if ($.inArray(newMask, genmasks) == -1 && newMask != "") { genmasks.push(newMask); maskTemplate = getMaskTemplate(newMask); ms.push({ "mask": newMask, "_buffer": maskTemplate["mask"], "buffer": maskTemplate["mask"].slice(), "tests": getTestingChain(newMask), "lastValidPosition": -1, "greedy": maskTemplate["greedy"], "repeat": maskTemplate["repeat"], "metadata": metadata }); } } } if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask opts.mask = opts.mask.call(this, opts); } if ($.isArray(opts.mask)) { $.each(opts.mask, function (ndx, msk) { if (msk["mask"] != undefined) { generateMask("", msk["mask"].toString(), msk); } else generateMask("", msk.toString()); }); } else generateMask("", opts.mask.toString()); return opts.greedy ? ms : ms.sort(function (a, b) { return a["mask"].length - b["mask"].length; }); } var msie10 = navigator.userAgent.match(new RegExp("msie 10", "i")) !== null, iphone = navigator.userAgent.match(new RegExp("iphone", "i")) !== null, android = navigator.userAgent.match(new RegExp("android.*safari.*", "i")) !== null, androidchrome = navigator.userAgent.match(new RegExp("android.*chrome.*", "i")) !== null, pasteEvent = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange"; //masking scope //actionObj definition see below function maskScope(masksets, activeMasksetIndex, opts, actionObj) { var isRTL = false, valueOnFocus = getActiveBuffer().join(''), $el, chromeValueOnInput, skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround skipInputEvent = false, //skip when triggered from within inputmask ignorable = false; //maskset helperfunctions function getActiveMaskSet() { return masksets[activeMasksetIndex]; } function getActiveTests() { return getActiveMaskSet()['tests']; } function getActiveBufferTemplate() { return getActiveMaskSet()['_buffer']; } function getActiveBuffer() { return getActiveMaskSet()['buffer']; } function isValid(pos, c, strict) { //strict true ~ no correction or autofill strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions function _isValid(position, activeMaskset, c, strict) { var testPos = determineTestPosition(position), loopend = c ? 1 : 0, chrs = '', buffer = activeMaskset["buffer"]; for (var i = activeMaskset['tests'][testPos].cardinality; i > loopend; i--) { chrs += getBufferElement(buffer, testPos - (i - 1)); } if (c) { chrs += c; } //return is false or a json object => { pos: ??, c: ??} or true return activeMaskset['tests'][testPos].fn != null ? activeMaskset['tests'][testPos].fn.test(chrs, buffer, position, strict, opts) : (c == getBufferElement(activeMaskset['_buffer'], position, true) || c == opts.skipOptionalPartCharacter) ? { "refresh": true, c: getBufferElement(activeMaskset['_buffer'], position, true), pos: position } : false; } function PostProcessResults(maskForwards, results) { var hasValidActual = false; $.each(results, function (ndx, rslt) { hasValidActual = $.inArray(rslt["activeMasksetIndex"], maskForwards) == -1 && rslt["result"] !== false; if (hasValidActual) return false; }); if (hasValidActual) { //strip maskforwards results = $.map(results, function (rslt, ndx) { if ($.inArray(rslt["activeMasksetIndex"], maskForwards) == -1) { return rslt; } else { masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = actualLVP; } }); } else { //keep maskforwards with the least forward var lowestPos = -1, lowestIndex = -1, rsltValid; $.each(results, function (ndx, rslt) { if ($.inArray(rslt["activeMasksetIndex"], maskForwards) != -1 && rslt["result"] !== false & (lowestPos == -1 || lowestPos > rslt["result"]["pos"])) { lowestPos = rslt["result"]["pos"]; lowestIndex = rslt["activeMasksetIndex"]; } }); results = $.map(results, function (rslt, ndx) { if ($.inArray(rslt["activeMasksetIndex"], maskForwards) != -1) { if (rslt["result"]["pos"] == lowestPos) { return rslt; } else if (rslt["result"] !== false) { for (var i = pos; i < lowestPos; i++) { rsltValid = _isValid(i, masksets[rslt["activeMasksetIndex"]], masksets[lowestIndex]["buffer"][i], true); if (rsltValid === false) { masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = lowestPos - 1; break; } else { setBufferElement(masksets[rslt["activeMasksetIndex"]]["buffer"], i, masksets[lowestIndex]["buffer"][i], true); masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = i; } } //also check check for the lowestpos with the new input rsltValid = _isValid(lowestPos, masksets[rslt["activeMasksetIndex"]], c, true); if (rsltValid !== false) { setBufferElement(masksets[rslt["activeMasksetIndex"]]["buffer"], lowestPos, c, true); masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = lowestPos; } //console.log("ndx " + rslt["activeMasksetIndex"] + " validate " + masksets[rslt["activeMasksetIndex"]]["buffer"].join('') + " lv " + masksets[rslt["activeMasksetIndex"]]['lastValidPosition']); return rslt; } } }); } return results; } if (strict) { var result = _isValid(pos, getActiveMaskSet(), c, strict); //only check validity in current mask when validating strict if (result === true) { result = { "pos": pos }; //always take a possible corrected maskposition into account } return result; } var results = [], result = false, currentActiveMasksetIndex = activeMasksetIndex, actualBuffer = getActiveBuffer().slice(), actualLVP = getActiveMaskSet()["lastValidPosition"], actualPrevious = seekPrevious(pos), maskForwards = []; $.each(masksets, function (index, value) { if (typeof (value) == "object") { activeMasksetIndex = index; var maskPos = pos; var lvp = getActiveMaskSet()['lastValidPosition'], rsltValid; if (lvp == actualLVP) { if ((maskPos - actualLVP) > 1) { for (var i = lvp == -1 ? 0 : lvp; i < maskPos; i++) { rsltValid = _isValid(i, getActiveMaskSet(), actualBuffer[i], true); if (rsltValid === false) { break; } else { setBufferElement(getActiveBuffer(), i, actualBuffer[i], true); if (rsltValid === true) { rsltValid = { "pos": i }; //always take a possible corrected maskposition into account } var newValidPosition = rsltValid.pos || i; if (getActiveMaskSet()['lastValidPosition'] < newValidPosition) getActiveMaskSet()['lastValidPosition'] = newValidPosition; //set new position from isValid } } } //does the input match on a further position? if (!isMask(maskPos) && !_isValid(maskPos, getActiveMaskSet(), c, strict)) { var maxForward = seekNext(maskPos) - maskPos; for (var fw = 0; fw < maxForward; fw++) { if (_isValid(++maskPos, getActiveMaskSet(), c, strict) !== false) break; } maskForwards.push(activeMasksetIndex); //console.log('maskforward ' + activeMasksetIndex + " pos " + pos + " maskPos " + maskPos); } } if (getActiveMaskSet()['lastValidPosition'] >= actualLVP || activeMasksetIndex == currentActiveMasksetIndex) { if (maskPos >= 0 && maskPos < getMaskLength()) { result = _isValid(maskPos, getActiveMaskSet(), c, strict); if (result !== false) { if (result === true) { result = { "pos": maskPos }; //always take a possible corrected maskposition into account } var newValidPosition = result.pos || maskPos; if (getActiveMaskSet()['lastValidPosition'] < newValidPosition) getActiveMaskSet()['lastValidPosition'] = newValidPosition; //set new position from isValid } //console.log("pos " + pos + " ndx " + activeMasksetIndex + " validate " + getActiveBuffer().join('') + " lv " + getActiveMaskSet()['lastValidPosition']); results.push({ "activeMasksetIndex": index, "result": result }); } } } }); activeMasksetIndex = currentActiveMasksetIndex; //reset activeMasksetIndex return PostProcessResults(maskForwards, results); //return results of the multiple mask validations } function determineActiveMasksetIndex() { var currentMasksetIndex = activeMasksetIndex, highestValid = { "activeMasksetIndex": 0, "lastValidPosition": -1, "next": -1 }; $.each(masksets, function (index, value) { if (typeof (value) == "object") { activeMasksetIndex = index; if (getActiveMaskSet()['lastValidPosition'] > highestValid['lastValidPosition']) { highestValid["activeMasksetIndex"] = index; highestValid["lastValidPosition"] = getActiveMaskSet()['lastValidPosition']; highestValid["next"] = seekNext(getActiveMaskSet()['lastValidPosition']); } else if (getActiveMaskSet()['lastValidPosition'] == highestValid['lastValidPosition'] && (highestValid['next'] == -1 || highestValid['next'] > seekNext(getActiveMaskSet()['lastValidPosition']))) { highestValid["activeMasksetIndex"] = index; highestValid["lastValidPosition"] = getActiveMaskSet()['lastValidPosition']; highestValid["next"] = seekNext(getActiveMaskSet()['lastValidPosition']); } } }); activeMasksetIndex = highestValid["lastValidPosition"] != -1 && masksets[currentMasksetIndex]["lastValidPosition"] == highestValid["lastValidPosition"] ? currentMasksetIndex : highestValid["activeMasksetIndex"]; if (currentMasksetIndex != activeMasksetIndex) { clearBuffer(getActiveBuffer(), seekNext(highestValid["lastValidPosition"]), getMaskLength()); getActiveMaskSet()["writeOutBuffer"] = true; } $el.data('_inputmask')['activeMasksetIndex'] = activeMasksetIndex; //store the activeMasksetIndex } function isMask(pos) { var testPos = determineTestPosition(pos); var test = getActiveTests()[testPos]; return test != undefined ? test.fn : false; } function determineTestPosition(pos) { return pos % getActiveTests().length; } function getMaskLength() { return opts.getMaskLength(getActiveBufferTemplate(), getActiveMaskSet()['greedy'], getActiveMaskSet()['repeat'], getActiveBuffer(), opts); } //pos: from position function seekNext(pos) { var maskL = getMaskLength(); if (pos >= maskL) return maskL; var position = pos; while (++position < maskL && !isMask(position)) { } return position; } //pos: from position function seekPrevious(pos) { var position = pos; if (position <= 0) return 0; while (--position > 0 && !isMask(position)) { } ; return position; } function setBufferElement(buffer, position, element, autoPrepare) { if (autoPrepare) position = prepareBuffer(buffer, position); var test = getActiveTests()[determineTestPosition(position)]; var elem = element; if (elem != undefined && test != undefined) { switch (test.casing) { case "upper": elem = element.toUpperCase(); break; case "lower": elem = element.toLowerCase(); break; } } buffer[position] = elem; } function getBufferElement(buffer, position, autoPrepare) { if (autoPrepare) position = prepareBuffer(buffer, position); return buffer[position]; } //needed to handle the non-greedy mask repetitions function prepareBuffer(buffer, position) { var j; while (buffer[position] == undefined && buffer.length < getMaskLength()) { j = 0; while (getActiveBufferTemplate()[j] !== undefined) { //add a new buffer buffer.push(getActiveBufferTemplate()[j++]); } } return position; } function writeBuffer(input, buffer, caretPos) { input._valueSet(buffer.join('')); if (caretPos != undefined) { caret(input, caretPos); } } function clearBuffer(buffer, start, end, stripNomasks) { for (var i = start, maskL = getMaskLength() ; i < end && i < maskL; i++) { if (stripNomasks === true) { if (!isMask(i)) setBufferElement(buffer, i, ""); } else setBufferElement(buffer, i, getBufferElement(getActiveBufferTemplate().slice(), i, true)); } } function setReTargetPlaceHolder(buffer, pos) { var testPos = determineTestPosition(pos); setBufferElement(buffer, pos, getBufferElement(getActiveBufferTemplate(), testPos)); } function getPlaceHolder(pos) { return opts.placeholder.charAt(pos % opts.placeholder.length); } function checkVal(input, writeOut, strict, nptvl, intelliCheck) { var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split(''); $.each(masksets, function (ndx, ms) { if (typeof (ms) == "object") { ms["buffer"] = ms["_buffer"].slice(); ms["lastValidPosition"] = -1; ms["p"] = -1; } }); if (strict !== true) activeMasksetIndex = 0; if (writeOut) input._valueSet(""); //initial clear var ml = getMaskLength(); $.each(inputValue, function (ndx, charCode) { if (intelliCheck === true) { var p = getActiveMaskSet()["p"], lvp = p == -1 ? p : seekPrevious(p), pos = lvp == -1 ? ndx : seekNext(lvp); if ($.inArray(charCode, getActiveBufferTemplate().slice(lvp + 1, pos)) == -1) { keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx); } } else { keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx); } }); if (strict === true && getActiveMaskSet()["p"] != -1) { getActiveMaskSet()["lastValidPosition"] = seekPrevious(getActiveMaskSet()["p"]); } } function escapeRegex(str) { return $.inputmask.escapeRegex.call(this, str); } function truncateInput(inputValue) { return inputValue.replace(new RegExp("(" + escapeRegex(getActiveBufferTemplate().join('')) + ")*$"), ""); } function clearOptionalTail(input) { var buffer = getActiveBuffer(), tmpBuffer = buffer.slice(), testPos, pos; for (var pos = tmpBuffer.length - 1; pos >= 0; pos--) { var testPos = determineTestPosition(pos); if (getActiveTests()[testPos].optionality) { if (!isMask(pos) || !isValid(pos, buffer[pos], true)) tmpBuffer.pop(); else break; } else break; } writeBuffer(input, tmpBuffer); } function unmaskedvalue($input, skipDatepickerCheck) { if (getActiveTests() && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) { //checkVal(input, false, true); var umValue = $.map(getActiveBuffer(), function (element, index) { return isMask(index) && isValid(index, element, true) ? element : null; }); var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join(''); return opts.onUnMask != undefined ? opts.onUnMask.call(this, getActiveBuffer().join(''), unmaskedValue) : unmaskedValue; } else { return $input[0]._valueGet(); } } function TranslatePosition(pos) { if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) { var bffrLght = getActiveBuffer().length; pos = bffrLght - pos; } return pos; } function caret(input, begin, end) { var npt = input.jquery && input.length > 0 ? input[0] : input, range; if (typeof begin == 'number') { begin = TranslatePosition(begin); end = TranslatePosition(end); if (!$(input).is(':visible')) { return; } end = (typeof end == 'number') ? end : begin; npt.scrollLeft = npt.scrollWidth; if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode if (npt.setSelectionRange) { npt.selectionStart = begin; npt.selectionEnd = android ? begin : end; } else if (npt.createTextRange) { range = npt.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } } else { if (!$(input).is(':visible')) { return { "begin": 0, "end": 0 }; } if (npt.setSelectionRange) { begin = npt.selectionStart; end = npt.selectionEnd; } else if (document.selection && document.selection.createRange) { range = document.selection.createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } begin = TranslatePosition(begin); end = TranslatePosition(end); return { "begin": begin, "end": end }; } } function isComplete(buffer) { //return true / false / undefined (repeat *) if (opts.repeat == "*") return undefined; var complete = false, highestValidPosition = 0, currentActiveMasksetIndex = activeMasksetIndex; $.each(masksets, function (ndx, ms) { if (typeof (ms) == "object") { activeMasksetIndex = ndx; var aml = seekPrevious(getMaskLength()); if (ms["lastValidPosition"] >= highestValidPosition && ms["lastValidPosition"] == aml) { var msComplete = true; for (var i = 0; i <= aml; i++) { var mask = isMask(i), testPos = determineTestPosition(i); if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceHolder(i))) || (!mask && buffer[i] != getActiveBufferTemplate()[testPos])) { msComplete = false; break; } } complete = complete || msComplete; if (complete) //break loop return false; } highestValidPosition = ms["lastValidPosition"]; } }); activeMasksetIndex = currentActiveMasksetIndex; //reset activeMaskset return complete; } function isSelection(begin, end) { return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) : (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode); } //private functions function installEventRuler(npt) { var events = $._data(npt).events; $.each(events, function (eventType, eventHandlers) { $.each(eventHandlers, function (ndx, eventHandler) { if (eventHandler.namespace == "inputmask") { if (eventHandler.type != "setvalue") { var handler = eventHandler.handler; eventHandler.handler = function (e) { if (this.readOnly || this.disabled) e.preventDefault; else return handler.apply(this, arguments); }; } } }); }); } function patchValueProperty(npt) { var valueProperty; if (Object.getOwnPropertyDescriptor) valueProperty = Object.getOwnPropertyDescriptor(npt, "value"); if (valueProperty && valueProperty.get) { if (!npt._valueGet) { var valueGet = valueProperty.get; var valueSet = valueProperty.set; npt._valueGet = function () { return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this); }; npt._valueSet = function (value) { valueSet.call(this, isRTL ? value.split('').reverse().join('') : value); }; Object.defineProperty(npt, "value", { get: function () { var $self = $(this), inputData = $(this).data('_inputmask'), masksets = inputData['masksets'], activeMasksetIndex = inputData['activeMasksetIndex']; return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != masksets[activeMasksetIndex]['_buffer'].join('') ? valueGet.call(this) : ''; }, set: function (value) { valueSet.call(this, value); $(this).triggerHandler('setvalue.inputmask'); } }); } } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) { if (!npt._valueGet) { var valueGet = npt.__lookupGetter__("value"); var valueSet = npt.__lookupSetter__("value"); npt._valueGet = function () { return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this); }; npt._valueSet = function (value) { valueSet.call(this, isRTL ? value.split('').reverse().join('') : value); }; npt.__defineGetter__("value", function () { var $self = $(this), inputData = $(this).data('_inputmask'), masksets = inputData['masksets'], activeMasksetIndex = inputData['activeMasksetIndex']; return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != masksets[activeMasksetIndex]['_buffer'].join('') ? valueGet.call(this) : ''; }); npt.__defineSetter__("value", function (value) { valueSet.call(this, value); $(this).triggerHandler('setvalue.inputmask'); }); } } else { if (!npt._valueGet) { npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; }; npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; }; } if ($.valHooks.text == undefined || $.valHooks.text.inputmaskpatch != true) { var valueGet = $.valHooks.text && $.valHooks.text.get ? $.valHooks.text.get : function (elem) { return elem.value; }; var valueSet = $.valHooks.text && $.valHooks.text.set ? $.valHooks.text.set : function (elem, value) { elem.value = value; return elem; }; jQuery.extend($.valHooks, { text: { get: function (elem) { var $elem = $(elem); if ($elem.data('_inputmask')) { if ($elem.data('_inputmask')['opts'].autoUnmask) return $elem.inputmask('unmaskedvalue'); else { var result = valueGet(elem), inputData = $elem.data('_inputmask'), masksets = inputData['masksets'], activeMasksetIndex = inputData['activeMasksetIndex']; return result != masksets[activeMasksetIndex]['_buffer'].join('') ? result : ''; } } else return valueGet(elem); }, set: function (elem, value) { var $elem = $(elem); var result = valueSet(elem, value); if ($elem.data('_inputmask')) $elem.triggerHandler('setvalue.inputmask'); return result; }, inputmaskpatch: true } }); } } } //shift chars to left from start to end and put c at end position if defined function shiftL(start, end, c, maskJumps) { var buffer = getActiveBuffer(); if (maskJumps !== false) //jumping over nonmask position while (!isMask(start) && start - 1 >= 0) start--; for (var i = start; i < end && i < getMaskLength() ; i++) { if (isMask(i)) { setReTargetPlaceHolder(buffer, i); var j = seekNext(i); var p = getBufferElement(buffer, j); if (p != getPlaceHolder(j)) { if (j < getMaskLength() && isValid(i, p, true) !== false && getActiveTests()[determineTestPosition(i)].def == getActiveTests()[determineTestPosition(j)].def) { setBufferElement(buffer, i, p, true); } else { if (isMask(i)) break; } } } else { setReTargetPlaceHolder(buffer, i); } } if (c != undefined) setBufferElement(buffer, seekPrevious(end), c); if (getActiveMaskSet()["greedy"] == false) { var trbuffer = truncateInput(buffer.join('')).split(''); buffer.length = trbuffer.length; for (var i = 0, bl = buffer.length; i < bl; i++) { buffer[i] = trbuffer[i]; } if (buffer.length == 0) getActiveMaskSet()["buffer"] = getActiveBufferTemplate().slice(); } return start; //return the used start position } function shiftR(start, end, c) { var buffer = getActiveBuffer(); if (getBufferElement(buffer, start, true) != getPlaceHolder(start)) { for (var i = seekPrevious(end) ; i > start && i >= 0; i--) { if (isMask(i)) { var j = seekPrevious(i); var t = getBufferElement(buffer, j); if (t != getPlaceHolder(j)) { if (isValid(j, t, true) !== false && getActiveTests()[determineTestPosition(i)].def == getActiveTests()[determineTestPosition(j)].def) { setBufferElement(buffer, i, t, true); setReTargetPlaceHolder(buffer, j); } //else break; } } else setReTargetPlaceHolder(buffer, i); } } if (c != undefined && getBufferElement(buffer, start) == getPlaceHolder(start)) setBufferElement(buffer, start, c); var lengthBefore = buffer.length; if (getActiveMaskSet()["greedy"] == false) { var trbuffer = truncateInput(buffer.join('')).split(''); buffer.length = trbuffer.length; for (var i = 0, bl = buffer.length; i < bl; i++) { buffer[i] = trbuffer[i]; } if (buffer.length == 0) getActiveMaskSet()["buffer"] = getActiveBufferTemplate().slice(); } return end - (lengthBefore - buffer.length); //return new start position } ; function HandleRemove(input, k, pos) { if (opts.numericInput || isRTL) { switch (k) { case opts.keyCode.BACKSPACE: k = opts.keyCode.DELETE; break; case opts.keyCode.DELETE: k = opts.keyCode.BACKSPACE; break; } if (isRTL) { var pend = pos.end; pos.end = pos.begin; pos.begin = pend; } } var isSelection = true; if (pos.begin == pos.end) { var posBegin = k == opts.keyCode.BACKSPACE ? pos.begin - 1 : pos.begin; if (opts.isNumeric && opts.radixPoint != "" && getActiveBuffer()[posBegin] == opts.radixPoint) { pos.begin = (getActiveBuffer().length - 1 == posBegin) /* radixPoint is latest? delete it */ ? pos.begin : k == opts.keyCode.BACKSPACE ? posBegin : seekNext(posBegin); pos.end = pos.begin; } isSelection = false; if (k == opts.keyCode.BACKSPACE) pos.begin--; else if (k == opts.keyCode.DELETE) pos.end++; } else if (pos.end - pos.begin == 1 && !opts.insertMode) { isSelection = false; if (k == opts.keyCode.BACKSPACE) pos.begin--; } clearBuffer(getActiveBuffer(), pos.begin, pos.end); var ml = getMaskLength(); if (opts.greedy == false) { shiftL(pos.begin, ml, undefined, !isRTL && (k == opts.keyCode.BACKSPACE && !isSelection)); } else { var newpos = pos.begin; for (var i = pos.begin; i < pos.end; i++) { //seeknext to skip placeholders at start in selection if (isMask(i) || !isSelection) newpos = shiftL(pos.begin, ml, undefined, !isRTL && (k == opts.keyCode.BACKSPACE && !isSelection)); } if (!isSelection) pos.begin = newpos; } var firstMaskPos = seekNext(-1); clearBuffer(getActiveBuffer(), pos.begin, pos.end, true); checkVal(input, false, masksets[1] == undefined || firstMaskPos >= pos.end, getActiveBuffer()); if (getActiveMaskSet()['lastValidPosition'] < firstMaskPos) { getActiveMaskSet()["lastValidPosition"] = -1; getActiveMaskSet()["p"] = firstMaskPos; } else { getActiveMaskSet()["p"] = pos.begin; } } function keydownEvent(e) { //Safari 5.1.x - modal dialog fires keypress twice workaround skipKeyPressEvent = false; var input = this, $input = $(input), k = e.keyCode, pos = caret(input); //backspace, delete, and escape get special treatment if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127) || e.ctrlKey && k == 88) { //backspace/delete e.preventDefault(); //stop default action but allow propagation if (k == 88) valueOnFocus = getActiveBuffer().join(''); HandleRemove(input, k, pos); determineActiveMasksetIndex(); writeBuffer(input, getActiveBuffer(), getActiveMaskSet()["p"]); if (input._valueGet() == getActiveBufferTemplate().join('')) $input.trigger('cleared'); if (opts.showTooltip) { //update tooltip $input.prop("title", getActiveMaskSet()["mask"]); } } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch setTimeout(function () { var caretPos = seekNext(getActiveMaskSet()["lastValidPosition"]); if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--; caret(input, e.shiftKey ? pos.begin : caretPos, caretPos); }, 0); } else if ((k == opts.keyCode.HOME && !e.shiftKey) || k == opts.keyCode.PAGE_UP) { //Home or page_up caret(input, 0, e.shiftKey ? pos.begin : 0); } else if (k == opts.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo checkVal(input, true, false, valueOnFocus.split('')); $input.click(); } else if (k == opts.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert opts.insertMode = !opts.insertMode; caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin); } else if (opts.insertMode == false && !e.shiftKey) { if (k == opts.keyCode.RIGHT) { setTimeout(function () { var caretPos = caret(input); caret(input, caretPos.begin); }, 0); } else if (k == opts.keyCode.LEFT) { setTimeout(function () { var caretPos = caret(input); caret(input, caretPos.begin - 1); }, 0); } } var currentCaretPos = caret(input); if (opts.onKeyDown.call(this, e, getActiveBuffer(), opts) === true) //extra stuff to execute on keydown caret(input, currentCaretPos.begin, currentCaretPos.end); ignorable = $.inArray(k, opts.ignorables) != -1; } function keypressEvent(e, checkval, k, writeOut, strict, ndx) { //Safari 5.1.x - modal dialog fires keypress twice workaround if (k == undefined && skipKeyPressEvent) return false; skipKeyPressEvent = true; var input = this, $input = $(input); e = e || window.event; var k = checkval ? k : (e.which || e.charCode || e.keyCode); if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) { return true; } else { if (k) { //special treat the decimal separator if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44; var pos, results, result, c = String.fromCharCode(k); if (checkval) { var pcaret = strict ? ndx : getActiveMaskSet()["lastValidPosition"] + 1; pos = { begin: pcaret, end: pcaret }; } else { pos = caret(input); } //should we clear a possible selection?? var isSlctn = isSelection(pos.begin, pos.end), redetermineLVP = false, initialIndex = activeMasksetIndex; if (isSlctn) { activeMasksetIndex = initialIndex; $.each(masksets, function (ndx, lmnt) { //init undobuffer for recovery when not valid if (typeof (lmnt) == "object") { activeMasksetIndex = ndx; getActiveMaskSet()["undoBuffer"] = getActiveBuffer().join(''); } }); HandleRemove(input, opts.keyCode.DELETE, pos); if (!opts.insertMode) { //preserve some space $.each(masksets, function (ndx, lmnt) { if (typeof (lmnt) == "object") { activeMasksetIndex = ndx; shiftR(pos.begin, getMaskLength()); getActiveMaskSet()["lastValidPosition"] = seekNext(getActiveMaskSet()["lastValidPosition"]); } }); } activeMasksetIndex = initialIndex; //restore index } var radixPosition = getActiveBuffer().join('').indexOf(opts.radixPoint); if (opts.isNumeric && checkval !== true && radixPosition != -1) { if (opts.greedy && pos.begin <= radixPosition) { pos.begin = seekPrevious(pos.begin); pos.end = pos.begin; } else if (c == opts.radixPoint) { pos.begin = radixPosition; pos.end = pos.begin; } } var p = pos.begin; results = isValid(p, c, strict); if (strict === true) results = [{ "activeMasksetIndex": activeMasksetIndex, "result": results }]; var minimalForwardPosition = -1; $.each(results, function (index, result) { activeMasksetIndex = result["activeMasksetIndex"]; getActiveMaskSet()["writeOutBuffer"] = true; var np = result["result"]; if (np !== false) { var refresh = false, buffer = getActiveBuffer(); if (np !== true) { refresh = np["refresh"]; //only rewrite buffer from isValid p = np.pos != undefined ? np.pos : p; //set new position from isValid c = np.c != undefined ? np.c : c; //set new char from isValid } if (refresh !== true) { if (opts.insertMode == true) { var lastUnmaskedPosition = getMaskLength(); var bfrClone = buffer.slice(); while (getBufferElement(bfrClone, lastUnmaskedPosition, true) != getPlaceHolder(lastUnmaskedPosition) && lastUnmaskedPosition >= p) { lastUnmaskedPosition = lastUnmaskedPosition == 0 ? -1 : seekPrevious(lastUnmaskedPosition); } if (lastUnmaskedPosition >= p) { shiftR(p, getMaskLength(), c); //shift the lvp if needed var lvp = getActiveMaskSet()["lastValidPosition"], nlvp = seekNext(lvp); if (nlvp != getMaskLength() && lvp >= p && (getBufferElement(getActiveBuffer(), nlvp, true) != getPlaceHolder(nlvp))) { getActiveMaskSet()["lastValidPosition"] = nlvp; } } else getActiveMaskSet()["writeOutBuffer"] = false; } else setBufferElement(buffer, p, c, true); if (minimalForwardPosition == -1 || minimalForwardPosition > seekNext(p)) { minimalForwardPosition = seekNext(p); } } else if (!strict) { var nextPos = p < getMaskLength() ? p + 1 : p; if (minimalForwardPosition == -1 || minimalForwardPosition > nextPos) { minimalForwardPosition = nextPos; } } if (minimalForwardPosition > getActiveMaskSet()["p"]) getActiveMaskSet()["p"] = minimalForwardPosition; //needed for checkval strict } }); if (strict !== true) { activeMasksetIndex = initialIndex; determineActiveMasksetIndex(); } if (writeOut !== false) { $.each(results, function (ndx, rslt) { if (rslt["activeMasksetIndex"] == activeMasksetIndex) { result = rslt; return false; } }); if (result != undefined) { var self = this; setTimeout(function () { opts.onKeyValidation.call(self, result["result"], opts); }, 0); if (getActiveMaskSet()["writeOutBuffer"] && result["result"] !== false) { var buffer = getActiveBuffer(); var newCaretPosition; if (checkval) { newCaretPosition = undefined; } else if (opts.numericInput) { if (p > radixPosition) { newCaretPosition = seekPrevious(minimalForwardPosition); } else if (c == opts.radixPoint) { newCaretPosition = minimalForwardPosition - 1; } else newCaretPosition = seekPrevious(minimalForwardPosition - 1); } else { newCaretPosition = minimalForwardPosition; } writeBuffer(input, buffer, newCaretPosition); if (checkval !== true) { setTimeout(function () { //timeout needed for IE if (isComplete(buffer) === true) $input.trigger("complete"); skipInputEvent = true; $input.trigger("input"); }, 0); } } else if (isSlctn) { getActiveMaskSet()["buffer"] = getActiveMaskSet()["undoBuffer"].split(''); } } } if (opts.showTooltip) { //update tooltip $input.prop("title", getActiveMaskSet()["mask"]); } if (e) e.preventDefault(); } } } function keyupEvent(e) { var $input = $(this), input = this, k = e.keyCode, buffer = getActiveBuffer(); if (androidchrome && k == opts.keyCode.BACKSPACE) { if (chromeValueOnInput == input._valueGet()) keydownEvent.call(this, e); } opts.onKeyUp.call(this, e, buffer, opts); //extra stuff to execute on keyup if (k == opts.keyCode.TAB && opts.showMaskOnFocus) { if ($input.hasClass('focus.inputmask') && input._valueGet().length == 0) { buffer = getActiveBufferTemplate().slice(); writeBuffer(input, buffer); caret(input, 0); valueOnFocus = getActiveBuffer().join(''); } else { writeBuffer(input, buffer); if (buffer.join('') == getActiveBufferTemplate().join('') && $.inArray(opts.radixPoint, buffer) != -1) { caret(input, TranslatePosition(0)); $input.click(); } else caret(input, TranslatePosition(0), TranslatePosition(getMaskLength())); } } } function inputEvent(e) { if (skipInputEvent === true) { skipInputEvent = false; return true; } var input = this, $input = $(input); chromeValueOnInput = getActiveBuffer().join(''); checkVal(input, false, false); writeBuffer(input, getActiveBuffer()); if (isComplete(getActiveBuffer()) === true) $input.trigger("complete"); $input.click(); } function mask(el) { $el = $(el); if ($el.is(":input")) { //store tests & original buffer in the input element - used to get the unmasked value $el.data('_inputmask', { 'masksets': masksets, 'activeMasksetIndex': activeMasksetIndex, 'opts': opts, 'isRTL': false }); //show tooltip if (opts.showTooltip) { $el.prop("title", getActiveMaskSet()["mask"]); } //correct greedy setting if needed getActiveMaskSet()['greedy'] = getActiveMaskSet()['greedy'] ? getActiveMaskSet()['greedy'] : getActiveMaskSet()['repeat'] == 0; //handle maxlength attribute if ($el.attr("maxLength") != null) //only when the attribute is set { var maxLength = $el.prop('maxLength'); if (maxLength > -1) { //handle *-repeat $.each(masksets, function (ndx, ms) { if (typeof (ms) == "object") { if (ms["repeat"] == "*") { ms["repeat"] = maxLength; } } }); } if (getMaskLength() >= maxLength && maxLength > -1) { //FF sets no defined max length to -1 if (maxLength < getActiveBufferTemplate().length) getActiveBufferTemplate().length = maxLength; if (getActiveMaskSet()['greedy'] == false) { getActiveMaskSet()['repeat'] = Math.round(maxLength / getActiveBufferTemplate().length); } $el.prop('maxLength', getMaskLength() * 2); } } patchValueProperty(el); if (opts.numericInput) opts.isNumeric = opts.numericInput; if (el.dir == "rtl" || (opts.numericInput && opts.rightAlignNumerics) || (opts.isNumeric && opts.rightAlignNumerics)) $el.css("text-align", "right"); if (el.dir == "rtl" || opts.numericInput) { el.dir = "ltr"; $el.removeAttr("dir"); var inputData = $el.data('_inputmask'); inputData['isRTL'] = true; $el.data('_inputmask', inputData); isRTL = true; } //unbind all events - to make sure that no other mask will interfere when re-masking $el.unbind(".inputmask"); $el.removeClass('focus.inputmask'); //bind events $el.closest('form').bind("submit", function () { //trigger change on submit if any if (valueOnFocus != getActiveBuffer().join('')) { $el.change(); } }).bind('reset', function () { setTimeout(function () { $el.trigger("setvalue"); }, 0); }); $el.bind("mouseenter.inputmask", function () { var $input = $(this), input = this; if (!$input.hasClass('focus.inputmask') && opts.showMaskOnHover) { if (input._valueGet() != getActiveBuffer().join('')) { writeBuffer(input, getActiveBuffer()); } } }).bind("blur.inputmask", function () { var $input = $(this), input = this, nptValue = input._valueGet(), buffer = getActiveBuffer(); $input.removeClass('focus.inputmask'); if (valueOnFocus != getActiveBuffer().join('')) { $input.change(); } if (opts.clearMaskOnLostFocus && nptValue != '') { if (nptValue == getActiveBufferTemplate().join('')) input._valueSet(''); else { //clearout optional tail of the mask clearOptionalTail(input); } } if (isComplete(buffer) === false) { $input.trigger("incomplete"); if (opts.clearIncomplete) { $.each(masksets, function (ndx, ms) { if (typeof (ms) == "object") { ms["buffer"] = ms["_buffer"].slice(); ms["lastValidPosition"] = -1; } }); activeMasksetIndex = 0; if (opts.clearMaskOnLostFocus) input._valueSet(''); else { buffer = getActiveBufferTemplate().slice(); writeBuffer(input, buffer); } } } }).bind("focus.inputmask", function () { var $input = $(this), input = this, nptValue = input._valueGet(); if (opts.showMaskOnFocus && !$input.hasClass('focus.inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) { if (input._valueGet() != getActiveBuffer().join('')) { writeBuffer(input, getActiveBuffer(), seekNext(getActiveMaskSet()["lastValidPosition"])); } } $input.addClass('focus.inputmask'); valueOnFocus = getActiveBuffer().join(''); }).bind("mouseleave.inputmask", function () { var $input = $(this), input = this; if (opts.clearMaskOnLostFocus) { if (!$input.hasClass('focus.inputmask') && input._valueGet() != $input.attr("placeholder")) { if (input._valueGet() == getActiveBufferTemplate().join('') || input._valueGet() == '') input._valueSet(''); else { //clearout optional tail of the mask clearOptionalTail(input); } } } }).bind("click.inputmask", function () { var input = this; setTimeout(function () { var selectedCaret = caret(input), buffer = getActiveBuffer(); if (selectedCaret.begin == selectedCaret.end) { var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin, lvp = getActiveMaskSet()["lastValidPosition"], lastPosition; if (opts.isNumeric) { lastPosition = opts.skipRadixDance === false && opts.radixPoint != "" && $.inArray(opts.radixPoint, buffer) != -1 ? (opts.numericInput ? seekNext($.inArray(opts.radixPoint, buffer)) : $.inArray(opts.radixPoint, buffer)) : seekNext(lvp); } else { lastPosition = seekNext(lvp); } if (clickPosition < lastPosition) { if (isMask(clickPosition)) caret(input, clickPosition); else caret(input, seekNext(clickPosition)); } else caret(input, lastPosition); } }, 0); }).bind('dblclick.inputmask', function () { var input = this; setTimeout(function () { caret(input, 0, seekNext(getActiveMaskSet()["lastValidPosition"])); }, 0); }).bind(pasteEvent + ".inputmask dragdrop.inputmask drop.inputmask", function (e) { if (skipInputEvent === true) { skipInputEvent = false; return true; } var input = this, $input = $(input); //paste event for IE8 and lower I guess ;-) if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) { return true; } setTimeout(function () { var pasteValue = opts.onBeforePaste != undefined ? opts.onBeforePaste.call(this, input._valueGet()) : input._valueGet(); checkVal(input, true, false, pasteValue.split(''), true); if (isComplete(getActiveBuffer()) === true) $input.trigger("complete"); $input.click(); }, 0); }).bind('setvalue.inputmask', function () { var input = this; checkVal(input, true); valueOnFocus = getActiveBuffer().join(''); if (input._valueGet() == getActiveBufferTemplate().join('')) input._valueSet(''); }).bind('complete.inputmask', opts.oncomplete ).bind('incomplete.inputmask', opts.onincomplete ).bind('cleared.inputmask', opts.oncleared ).bind("keyup.inputmask", keyupEvent); if (androidchrome) { $el.bind("input.inputmask", inputEvent); } else { $el.bind("keydown.inputmask", keydownEvent ).bind("keypress.inputmask", keypressEvent); } if (msie10) $el.bind("input.inputmask", inputEvent); //apply mask checkVal(el, true, false); valueOnFocus = getActiveBuffer().join(''); // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame. var activeElement; try { activeElement = document.activeElement; } catch (e) { } if (activeElement === el) { //position the caret when in focus $el.addClass('focus.inputmask'); caret(el, seekNext(getActiveMaskSet()["lastValidPosition"])); } else if (opts.clearMaskOnLostFocus) { if (getActiveBuffer().join('') == getActiveBufferTemplate().join('')) { el._valueSet(''); } else { clearOptionalTail(el); } } else { writeBuffer(el, getActiveBuffer()); } installEventRuler(el); } } //action object if (actionObj != undefined) { switch (actionObj["action"]) { case "isComplete": return isComplete(actionObj["buffer"]); case "unmaskedvalue": isRTL = actionObj["$input"].data('_inputmask')['isRTL']; return unmaskedvalue(actionObj["$input"], actionObj["skipDatepickerCheck"]); case "mask": mask(actionObj["el"]); break; case "format": $el = $({}); $el.data('_inputmask', { 'masksets': masksets, 'activeMasksetIndex': activeMasksetIndex, 'opts': opts, 'isRTL': opts.numericInput }); if (opts.numericInput) { opts.isNumeric = opts.numericInput; isRTL = true; } checkVal($el, false, false, actionObj["value"].split(''), true); return getActiveBuffer().join(''); } } }; $.inputmask = { //options default defaults: { placeholder: "_", optionalmarker: { start: "[", end: "]" }, quantifiermarker: { start: "{", end: "}" }, groupmarker: { start: "(", end: ")" }, escapeChar: "\\", mask: null, oncomplete: $.noop, //executes when the mask is complete onincomplete: $.noop, //executes when the mask is incomplete and focus is lost oncleared: $.noop, //executes when the mask is cleared repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor clearMaskOnLostFocus: true, insertMode: true, //insert the input or overwrite the input clearIncomplete: false, //clear the incomplete input on blur aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js onKeyUp: $.noop, //override to implement autocomplete on certain keys for example onKeyDown: $.noop, //override to implement autocomplete on certain keys for example onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue => return processedValue onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue showMaskOnFocus: true, //show the mask-placeholder when the input has focus showMaskOnHover: true, //show the mask-placeholder when hovering the empty input onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask showTooltip: false, //show the activemask as tooltip numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position) //numeric basic properties isNumeric: false, //enable numeric features radixPoint: "", //".", // | "," skipRadixDance: false, //disable radixpoint caret positioning rightAlignNumerics: true, //align numerics to the right //numeric basic properties definitions: { '9': { validator: "[0-9]", cardinality: 1 }, 'a': { validator: "[A-Za-z\u0410-\u044F\u0401\u0451]", cardinality: 1 }, '*': { validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]", cardinality: 1 } }, keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, 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 }, //specify keycodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF ignorables: [8, 9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123], getMaskLength: function (buffer, greedy, repeat, currentBuffer, opts) { var calculatedLength = buffer.length; if (!greedy) { if (repeat == "*") { calculatedLength = currentBuffer.length + 1; } else if (repeat > 1) { calculatedLength += (buffer.length * (repeat - 1)); } } return calculatedLength; } }, escapeRegex: function (str) { var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\']; return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1'); }, format: function (value, options) { var opts = $.extend(true, {}, $.inputmask.defaults, options); resolveAlias(opts.alias, options, opts); return maskScope(generateMaskSets(opts), 0, opts, { "action": "format", "value": value }); } }; $.fn.inputmask = function (fn, options) { var opts = $.extend(true, {}, $.inputmask.defaults, options), masksets, activeMasksetIndex = 0; if (typeof fn === "string") { switch (fn) { case "mask": //resolve possible aliases given by options resolveAlias(opts.alias, options, opts); masksets = generateMaskSets(opts); if (masksets.length == 0) { return this; } return this.each(function () { maskScope($.extend(true, {}, masksets), 0, opts, { "action": "mask", "el": this }); }); case "unmaskedvalue": var $input = $(this), input = this; if ($input.data('_inputmask')) { masksets = $input.data('_inputmask')['masksets']; activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex']; opts = $input.data('_inputmask')['opts']; return maskScope(masksets, activeMasksetIndex, opts, { "action": "unmaskedvalue", "$input": $input }); } else return $input.val(); case "remove": return this.each(function () { var $input = $(this), input = this; if ($input.data('_inputmask')) { masksets = $input.data('_inputmask')['masksets']; activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex']; opts = $input.data('_inputmask')['opts']; //writeout the unmaskedvalue input._valueSet(maskScope(masksets, activeMasksetIndex, opts, { "action": "unmaskedvalue", "$input": $input, "skipDatepickerCheck": true })); //clear data $input.removeData('_inputmask'); //unbind all events $input.unbind(".inputmask"); $input.removeClass('focus.inputmask'); //restore the value property var valueProperty; if (Object.getOwnPropertyDescriptor) valueProperty = Object.getOwnPropertyDescriptor(input, "value"); if (valueProperty && valueProperty.get) { if (input._valueGet) { Object.defineProperty(input, "value", { get: input._valueGet, set: input._valueSet }); } } else if (document.__lookupGetter__ && input.__lookupGetter__("value")) { if (input._valueGet) { input.__defineGetter__("value", input._valueGet); input.__defineSetter__("value", input._valueSet); } } try { //try catch needed for IE7 as it does not supports deleting fns delete input._valueGet; delete input._valueSet; } catch (e) { input._valueGet = undefined; input._valueSet = undefined; } } }); break; case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation if (this.data('_inputmask')) { masksets = this.data('_inputmask')['masksets']; activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex']; return masksets[activeMasksetIndex]['_buffer'].join(''); } else return ""; case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value return this.data('_inputmask') ? !this.data('_inputmask')['opts'].autoUnmask : false; case "isComplete": masksets = this.data('_inputmask')['masksets']; activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex']; opts = this.data('_inputmask')['opts']; return maskScope(masksets, activeMasksetIndex, opts, { "action": "isComplete", "buffer": this[0]._valueGet().split('') }); case "getmetadata": //return mask metadata if exists if (this.data('_inputmask')) { masksets = this.data('_inputmask')['masksets']; activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex']; return masksets[activeMasksetIndex]['metadata']; } else return undefined; default: //check if the fn is an alias if (!resolveAlias(fn, options, opts)) { //maybe fn is a mask so we try //set mask opts.mask = fn; } masksets = generateMaskSets(opts); if (masksets.length == 0) { return this; } return this.each(function () { maskScope($.extend(true, {}, masksets), activeMasksetIndex, opts, { "action": "mask", "el": this }); }); break; } } else if (typeof fn == "object") { opts = $.extend(true, {}, $.inputmask.defaults, fn); resolveAlias(opts.alias, fn, opts); //resolve aliases masksets = generateMaskSets(opts); if (masksets.length == 0) { return this; } return this.each(function () { maskScope($.extend(true, {}, masksets), activeMasksetIndex, opts, { "action": "mask", "el": this }); }); } else if (fn == undefined) { //look for data-inputmask atribute - the attribute should only contain optipns return this.each(function () { var attrOptions = $(this).attr("data-inputmask"); if (attrOptions && attrOptions != "") { try { attrOptions = attrOptions.replace(new RegExp("'", "g"), '"'); var dataoptions = $.parseJSON("{" + attrOptions + "}"); $.extend(true, dataoptions, options); opts = $.extend(true, {}, $.inputmask.defaults, dataoptions); resolveAlias(opts.alias, dataoptions, opts); opts.alias = undefined; $(this).inputmask(opts); } catch (ex) { } //need a more relax parseJSON } }); } }; } })(jQuery); /* Input Mask plugin extensions http://github.com/RobinHerbots/jquery.inputmask Copyright (c) 2010 - 2014 Robin Herbots Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) Version: 2.4.18 Optional extensions on the jquery.inputmask base */ (function ($) { //extra definitions $.extend($.inputmask.defaults.definitions, { 'A': { validator: "[A-Za-z]", cardinality: 1, casing: "upper" //auto uppercasing }, '#': { validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]", cardinality: 1, casing: "upper" } }); $.extend($.inputmask.defaults.aliases, { 'url': { mask: "ir", placeholder: "", separator: "", defaultPrefix: "http://", regex: { urlpre1: new RegExp("[fh]"), urlpre2: new RegExp("(ft|ht)"), urlpre3: new RegExp("(ftp|htt)"), urlpre4: new RegExp("(ftp:|http|ftps)"), urlpre5: new RegExp("(ftp:/|ftps:|http:|https)"), urlpre6: new RegExp("(ftp://|ftps:/|http:/|https:)"), urlpre7: new RegExp("(ftp://|ftps://|http://|https:/)"), urlpre8: new RegExp("(ftp://|ftps://|http://|https://)") }, definitions: { 'i': { validator: function (chrs, buffer, pos, strict, opts) { return true; }, cardinality: 8, prevalidator: (function () { var result = [], prefixLimit = 8; for (var i = 0; i < prefixLimit; i++) { result[i] = (function () { var j = i; return { validator: function (chrs, buffer, pos, strict, opts) { if (opts.regex["urlpre" + (j + 1)]) { var tmp = chrs, k; if (((j + 1) - chrs.length) > 0) { tmp = buffer.join('').substring(0, ((j + 1) - chrs.length)) + "" + tmp; } var isValid = opts.regex["urlpre" + (j + 1)].test(tmp); if (!strict && !isValid) { pos = pos - j; for (k = 0; k < opts.defaultPrefix.length; k++) { buffer[pos] = opts.defaultPrefix[k]; pos++; } for (k = 0; k < tmp.length - 1; k++) { buffer[pos] = tmp[k]; pos++; } return { "pos": pos }; } return isValid; } else { return false; } }, cardinality: j }; })(); } return result; })() }, "r": { validator: ".", cardinality: 50 } }, insertMode: false, autoUnmask: false }, "ip": { //ip-address mask mask: ["[[x]y]z.[[x]y]z.[[x]y]z.x[yz]", "[[x]y]z.[[x]y]z.[[x]y]z.[[x]y][z]"], definitions: { 'x': { validator: "[012]", cardinality: 1, definitionSymbol: "i" }, 'y': { validator: function (chrs, buffer, pos, strict, opts) { if (pos - 1 > -1 && buffer[pos - 1] != ".") chrs = buffer[pos - 1] + chrs; else chrs = "0" + chrs; return new RegExp("2[0-5]|[01][0-9]").test(chrs); }, cardinality: 1, definitionSymbol: "i" }, 'z': { validator: function (chrs, buffer, pos, strict, opts) { if (pos - 1 > -1 && buffer[pos - 1] != ".") { chrs = buffer[pos - 1] + chrs; if (pos - 2 > -1 && buffer[pos - 2] != ".") { chrs = buffer[pos - 2] + chrs; } else chrs = "0" + chrs; } else chrs = "00" + chrs; return new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]").test(chrs); }, cardinality: 1, definitionSymbol: "i" } } } }); })(jQuery); /* Input Mask plugin extensions http://github.com/RobinHerbots/jquery.inputmask Copyright (c) 2010 - 2014 Robin Herbots Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) Version: 2.4.18 Optional extensions on the jquery.inputmask base */ (function ($) { //date & time aliases $.extend($.inputmask.defaults.definitions, { 'h': { //hours validator: "[01][0-9]|2[0-3]", cardinality: 2, prevalidator: [{ validator: "[0-2]", cardinality: 1 }] }, 's': { //seconds || minutes validator: "[0-5][0-9]", cardinality: 2, prevalidator: [{ validator: "[0-5]", cardinality: 1 }] }, 'd': { //basic day validator: "0[1-9]|[12][0-9]|3[01]", cardinality: 2, prevalidator: [{ validator: "[0-3]", cardinality: 1 }] }, 'm': { //basic month validator: "0[1-9]|1[012]", cardinality: 2, prevalidator: [{ validator: "[01]", cardinality: 1 }] }, 'y': { //basic year validator: "(19|20)\\d{2}", cardinality: 4, prevalidator: [ { validator: "[12]", cardinality: 1 }, { validator: "(19|20)", cardinality: 2 }, { validator: "(19|20)\\d", cardinality: 3 } ] } }); $.extend($.inputmask.defaults.aliases, { 'dd/mm/yyyy': { mask: "1/2/y", placeholder: "dd/mm/yyyy", regex: { val1pre: new RegExp("[0-3]"), //daypre val1: new RegExp("0[1-9]|[12][0-9]|3[01]"), //day val2pre: function (separator) { var escapedSeparator = $.inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|[12][0-9]|3[01])" + escapedSeparator + "[01])"); }, //monthpre val2: function (separator) { var escapedSeparator = $.inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|[12][0-9])" + escapedSeparator + "(0[1-9]|1[012]))|(30" + escapedSeparator + "(0[13-9]|1[012]))|(31" + escapedSeparator + "(0[13578]|1[02]))"); }//month }, leapday: "29/02/", separator: '/', yearrange: { minyear: 1900, maxyear: 2099 }, isInYearRange: function (chrs, minyear, maxyear) { var enteredyear = parseInt(chrs.concat(minyear.toString().slice(chrs.length))); var enteredyear2 = parseInt(chrs.concat(maxyear.toString().slice(chrs.length))); return (enteredyear != NaN ? minyear <= enteredyear && enteredyear <= maxyear : false) || (enteredyear2 != NaN ? minyear <= enteredyear2 && enteredyear2 <= maxyear : false); }, determinebaseyear: function (minyear, maxyear, hint) { var currentyear = (new Date()).getFullYear(); if (minyear > currentyear) return minyear; if (maxyear < currentyear) { var maxYearPrefix = maxyear.toString().slice(0, 2); var maxYearPostfix = maxyear.toString().slice(2, 4); while (maxyear < maxYearPrefix + hint) { maxYearPrefix--; } var maxxYear = maxYearPrefix + maxYearPostfix; return minyear > maxxYear ? minyear : maxxYear; } return currentyear; }, onKeyUp: function (e, buffer, opts) { var $input = $(this); if (e.ctrlKey && e.keyCode == opts.keyCode.RIGHT) { var today = new Date(); $input.val(today.getDate().toString() + (today.getMonth() + 1).toString() + today.getFullYear().toString()); } }, definitions: { '1': { //val1 ~ day or month validator: function (chrs, buffer, pos, strict, opts) { var isValid = opts.regex.val1.test(chrs); if (!strict && !isValid) { if (chrs.charAt(1) == opts.separator || "-./".indexOf(chrs.charAt(1)) != -1) { isValid = opts.regex.val1.test("0" + chrs.charAt(0)); if (isValid) { buffer[pos - 1] = "0"; return { "pos": pos, "c": chrs.charAt(0) }; } } } return isValid; }, cardinality: 2, prevalidator: [{ validator: function (chrs, buffer, pos, strict, opts) { var isValid = opts.regex.val1pre.test(chrs); if (!strict && !isValid) { isValid = opts.regex.val1.test("0" + chrs); if (isValid) { buffer[pos] = "0"; pos++; return { "pos": pos }; } } return isValid; }, cardinality: 1 }] }, '2': { //val2 ~ day or month validator: function (chrs, buffer, pos, strict, opts) { var frontValue = buffer.join('').substr(0, 3); if (frontValue.indexOf(opts.placeholder[0]) != -1) frontValue = "01" + opts.separator; var isValid = opts.regex.val2(opts.separator).test(frontValue + chrs); if (!strict && !isValid) { if (chrs.charAt(1) == opts.separator || "-./".indexOf(chrs.charAt(1)) != -1) { isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs.charAt(0)); if (isValid) { buffer[pos - 1] = "0"; return { "pos": pos, "c": chrs.charAt(0) }; } } } return isValid; }, cardinality: 2, prevalidator: [{ validator: function (chrs, buffer, pos, strict, opts) { var frontValue = buffer.join('').substr(0, 3); if (frontValue.indexOf(opts.placeholder[0]) != -1) frontValue = "01" + opts.separator; var isValid = opts.regex.val2pre(opts.separator).test(frontValue + chrs); if (!strict && !isValid) { isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs); if (isValid) { buffer[pos] = "0"; pos++; return { "pos": pos }; } } return isValid; }, cardinality: 1 }] }, 'y': { //year validator: function (chrs, buffer, pos, strict, opts) { if (opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) { var dayMonthValue = buffer.join('').substr(0, 6); if (dayMonthValue != opts.leapday) return true; else { var year = parseInt(chrs, 10);//detect leap year if (year % 4 === 0) if (year % 100 === 0) if (year % 400 === 0) return true; else return false; else return true; else return false; } } else return false; }, cardinality: 4, prevalidator: [ { validator: function (chrs, buffer, pos, strict, opts) { var isValid = opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); if (!strict && !isValid) { var yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs + "0").toString().slice(0, 1); isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear); if (isValid) { buffer[pos++] = yearPrefix[0]; return { "pos": pos }; } yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs + "0").toString().slice(0, 2); isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear); if (isValid) { buffer[pos++] = yearPrefix[0]; buffer[pos++] = yearPrefix[1]; return { "pos": pos }; } } return isValid; }, cardinality: 1 }, { validator: function (chrs, buffer, pos, strict, opts) { var isValid = opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); if (!strict && !isValid) { var yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs).toString().slice(0, 2); isValid = opts.isInYearRange(chrs[0] + yearPrefix[1] + chrs[1], opts.yearrange.minyear, opts.yearrange.maxyear); if (isValid) { buffer[pos++] = yearPrefix[1]; return { "pos": pos }; } yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs).toString().slice(0, 2); if (opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) { var dayMonthValue = buffer.join('').substr(0, 6); if (dayMonthValue != opts.leapday) isValid = true; else { var year = parseInt(chrs, 10);//detect leap year if (year % 4 === 0) if (year % 100 === 0) if (year % 400 === 0) isValid = true; else isValid = false; else isValid = true; else isValid = false; } } else isValid = false; if (isValid) { buffer[pos - 1] = yearPrefix[0]; buffer[pos++] = yearPrefix[1]; buffer[pos++] = chrs[0]; return { "pos": pos }; } } return isValid; }, cardinality: 2 }, { validator: function (chrs, buffer, pos, strict, opts) { return opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); }, cardinality: 3 } ] } }, insertMode: false, autoUnmask: false }, 'mm/dd/yyyy': { placeholder: "mm/dd/yyyy", alias: "dd/mm/yyyy", //reuse functionality of dd/mm/yyyy alias regex: { val2pre: function (separator) { var escapedSeparator = $.inputmask.escapeRegex.call(this, separator); return new RegExp("((0[13-9]|1[012])" + escapedSeparator + "[0-3])|(02" + escapedSeparator + "[0-2])"); }, //daypre val2: function (separator) { var escapedSeparator = $.inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[13-9]|1[012])" + escapedSeparator + "30)|((0[13578]|1[02])" + escapedSeparator + "31)"); }, //day val1pre: new RegExp("[01]"), //monthpre val1: new RegExp("0[1-9]|1[012]") //month }, leapday: "02/29/", onKeyUp: function (e, buffer, opts) { var $input = $(this); if (e.ctrlKey && e.keyCode == opts.keyCode.RIGHT) { var today = new Date(); $input.val((today.getMonth() + 1).toString() + today.getDate().toString() + today.getFullYear().toString()); } } }, 'yyyy/mm/dd': { mask: "y/1/2", placeholder: "yyyy/mm/dd", alias: "mm/dd/yyyy", leapday: "/02/29", onKeyUp: function (e, buffer, opts) { var $input = $(this); if (e.ctrlKey && e.keyCode == opts.keyCode.RIGHT) { var today = new Date(); $input.val(today.getFullYear().toString() + (today.getMonth() + 1).toString() + today.getDate().toString()); } }, definitions: { '2': { //val2 ~ day or month validator: function (chrs, buffer, pos, strict, opts) { var frontValue = buffer.join('').substr(5, 3); if (frontValue.indexOf(opts.placeholder[5]) != -1) frontValue = "01" + opts.separator; var isValid = opts.regex.val2(opts.separator).test(frontValue + chrs); if (!strict && !isValid) { if (chrs.charAt(1) == opts.separator || "-./".indexOf(chrs.charAt(1)) != -1) { isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs.charAt(0)); if (isValid) { buffer[pos - 1] = "0"; return { "pos": pos, "c": chrs.charAt(0) }; } } } //check leap yeap if (isValid) { var dayMonthValue = buffer.join('').substr(4, 4) + chrs; if (dayMonthValue != opts.leapday) return true; else { var year = parseInt(buffer.join('').substr(0, 4), 10); //detect leap year if (year % 4 === 0) if (year % 100 === 0) if (year % 400 === 0) return true; else return false; else return true; else return false; } } return isValid; }, cardinality: 2, prevalidator: [{ validator: function (chrs, buffer, pos, strict, opts) { var frontValue = buffer.join('').substr(5, 3); if (frontValue.indexOf(opts.placeholder[5]) != -1) frontValue = "01" + opts.separator; var isValid = opts.regex.val2pre(opts.separator).test(frontValue + chrs); if (!strict && !isValid) { isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs); if (isValid) { buffer[pos] = "0"; pos++; return { "pos": pos }; } } return isValid; }, cardinality: 1 }] } } }, 'dd.mm.yyyy': { mask: "1.2.y", placeholder: "dd.mm.yyyy", leapday: "29.02.", separator: '.', alias: "dd/mm/yyyy" }, 'dd-mm-yyyy': { mask: "1-2-y", placeholder: "dd-mm-yyyy", leapday: "29-02-", separator: '-', alias: "dd/mm/yyyy" }, 'mm.dd.yyyy': { mask: "1.2.y", placeholder: "mm.dd.yyyy", leapday: "02.29.", separator: '.', alias: "mm/dd/yyyy" }, 'mm-dd-yyyy': { mask: "1-2-y", placeholder: "mm-dd-yyyy", leapday: "02-29-", separator: '-', alias: "mm/dd/yyyy" }, 'yyyy.mm.dd': { mask: "y.1.2", placeholder: "yyyy.mm.dd", leapday: ".02.29", separator: '.', alias: "yyyy/mm/dd" }, 'yyyy-mm-dd': { mask: "y-1-2", placeholder: "yyyy-mm-dd", leapday: "-02-29", separator: '-', alias: "yyyy/mm/dd" }, 'datetime': { mask: "1/2/y h:s", placeholder: "dd/mm/yyyy hh:mm", alias: "dd/mm/yyyy", regex: { hrspre: new RegExp("[012]"), //hours pre hrs24: new RegExp("2[0-9]|1[3-9]"), hrs: new RegExp("[01][0-9]|2[0-3]"), //hours ampm: new RegExp("^[a|p|A|P][m|M]") }, timeseparator: ':', hourFormat: "24", // or 12 definitions: { 'h': { //hours validator: function (chrs, buffer, pos, strict, opts) { var isValid = opts.regex.hrs.test(chrs); if (!strict && !isValid) { if (chrs.charAt(1) == opts.timeseparator || "-.:".indexOf(chrs.charAt(1)) != -1) { isValid = opts.regex.hrs.test("0" + chrs.charAt(0)); if (isValid) { buffer[pos - 1] = "0"; buffer[pos] = chrs.charAt(0); pos++; return { "pos": pos }; } } } if (isValid && opts.hourFormat !== "24" && opts.regex.hrs24.test(chrs)) { var tmp = parseInt(chrs, 10); if (tmp == 24) { buffer[pos + 5] = "a"; buffer[pos + 6] = "m"; } else { buffer[pos + 5] = "p"; buffer[pos + 6] = "m"; } tmp = tmp - 12; if (tmp < 10) { buffer[pos] = tmp.toString(); buffer[pos - 1] = "0"; } else { buffer[pos] = tmp.toString().charAt(1); buffer[pos - 1] = tmp.toString().charAt(0); } return { "pos": pos, "c": buffer[pos] }; } return isValid; }, cardinality: 2, prevalidator: [{ validator: function (chrs, buffer, pos, strict, opts) { var isValid = opts.regex.hrspre.test(chrs); if (!strict && !isValid) { isValid = opts.regex.hrs.test("0" + chrs); if (isValid) { buffer[pos] = "0"; pos++; return { "pos": pos }; } } return isValid; }, cardinality: 1 }] }, 't': { //am/pm validator: function (chrs, buffer, pos, strict, opts) { return opts.regex.ampm.test(chrs + "m"); }, casing: "lower", cardinality: 1 } }, insertMode: false, autoUnmask: false }, 'datetime12': { mask: "1/2/y h:s t\\m", placeholder: "dd/mm/yyyy hh:mm xm", alias: "datetime", hourFormat: "12" }, 'hh:mm t': { mask: "h:s t\\m", placeholder: "hh:mm xm", alias: "datetime", hourFormat: "12" }, 'h:s t': { mask: "h:s t\\m", placeholder: "hh:mm xm", alias: "datetime", hourFormat: "12" }, 'hh:mm:ss': { mask: "h:s:s", autoUnmask: false }, 'hh:mm': { mask: "h:s", autoUnmask: false }, 'date': { alias: "dd/mm/yyyy" // "mm/dd/yyyy" }, 'mm/yyyy': { mask: "1/y", placeholder: "mm/yyyy", leapday: "donotuse", separator: '/', alias: "mm/dd/yyyy" } }); })(jQuery); /* Input Mask plugin extensions http://github.com/RobinHerbots/jquery.inputmask Copyright (c) 2010 - 2014 Robin Herbots Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) Version: 2.4.18 Optional extensions on the jquery.inputmask base */ (function ($) { //number aliases $.extend($.inputmask.defaults.aliases, { 'decimal': { mask: "~", placeholder: "", repeat: "*", greedy: false, numericInput: false, isNumeric: true, digits: "*", //number of fractionalDigits groupSeparator: "",//",", // | "." radixPoint: ".", groupSize: 3, autoGroup: false, allowPlus: true, allowMinus: true, //todo integerDigits: "*", //number of integerDigits defaultValue: "", prefix: "", suffix: "", //todo getMaskLength: function (buffer, greedy, repeat, currentBuffer, opts) { //custom getMaskLength to take the groupSeparator into account var calculatedLength = buffer.length; if (!greedy) { if (repeat == "*") { calculatedLength = currentBuffer.length + 1; } else if (repeat > 1) { calculatedLength += (buffer.length * (repeat - 1)); } } var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator); var escapedRadixPoint = $.inputmask.escapeRegex.call(this, opts.radixPoint); var currentBufferStr = currentBuffer.join(''), strippedBufferStr = currentBufferStr.replace(new RegExp(escapedGroupSeparator, "g"), "").replace(new RegExp(escapedRadixPoint), ""), groupOffset = currentBufferStr.length - strippedBufferStr.length; return calculatedLength + groupOffset; }, postFormat: function (buffer, pos, reformatOnly, opts) { if (opts.groupSeparator == "") return pos; var cbuf = buffer.slice(), radixPos = $.inArray(opts.radixPoint, buffer); if (!reformatOnly) { cbuf.splice(pos, 0, "?"); //set position indicator } var bufVal = cbuf.join(''); if (opts.autoGroup || (reformatOnly && bufVal.indexOf(opts.groupSeparator) != -1)) { var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator); bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), ''); var radixSplit = bufVal.split(opts.radixPoint); bufVal = radixSplit[0]; var reg = new RegExp('([-\+]?[\\d\?]+)([\\d\?]{' + opts.groupSize + '})'); while (reg.test(bufVal)) { bufVal = bufVal.replace(reg, '$1' + opts.groupSeparator + '$2'); bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator); } if (radixSplit.length > 1) bufVal += opts.radixPoint + radixSplit[1]; } buffer.length = bufVal.length; //align the length for (var i = 0, l = bufVal.length; i < l; i++) { buffer[i] = bufVal.charAt(i); } var newPos = $.inArray("?", buffer); if (!reformatOnly) buffer.splice(newPos, 1); return reformatOnly ? pos : newPos; }, regex: { number: function (opts) { var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator); var escapedRadixPoint = $.inputmask.escapeRegex.call(this, opts.radixPoint); var digitExpression = isNaN(opts.digits) ? opts.digits : '{0,' + opts.digits + '}'; var signedExpression = opts.allowPlus || opts.allowMinus ? "[" + (opts.allowPlus ? "\+" : "") + (opts.allowMinus ? "-" : "") + "]?" : ""; return new RegExp("^" + signedExpression + "(\\d+|\\d{1," + opts.groupSize + "}((" + escapedGroupSeparator + "\\d{" + opts.groupSize + "})?)+)(" + escapedRadixPoint + "\\d" + digitExpression + ")?$"); } }, onKeyDown: function (e, buffer, opts) { var $input = $(this), input = this; if (e.keyCode == opts.keyCode.TAB) { var radixPosition = $.inArray(opts.radixPoint, buffer); if (radixPosition != -1) { var masksets = $input.data('_inputmask')['masksets']; var activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex']; for (var i = 1; i <= opts.digits && i < opts.getMaskLength(masksets[activeMasksetIndex]["_buffer"], masksets[activeMasksetIndex]["greedy"], masksets[activeMasksetIndex]["repeat"], buffer, opts) ; i++) { if (buffer[radixPosition + i] == undefined || buffer[radixPosition + i] == "") buffer[radixPosition + i] = "0"; } input._valueSet(buffer.join('')); } } else if (e.keyCode == opts.keyCode.DELETE || e.keyCode == opts.keyCode.BACKSPACE) { opts.postFormat(buffer, 0, true, opts); input._valueSet(buffer.join('')); return true; } }, definitions: { '~': { //real number validator: function (chrs, buffer, pos, strict, opts) { if (chrs == "") return false; if (!strict && pos <= 1 && buffer[0] === '0' && new RegExp("[\\d-]").test(chrs) && buffer.join('').length == 1) { //handle first char buffer[0] = ""; return { "pos": 0 }; } var cbuf = strict ? buffer.slice(0, pos) : buffer.slice(); cbuf.splice(pos, 0, chrs); var bufferStr = cbuf.join(''); //strip groupseparator var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator); bufferStr = bufferStr.replace(new RegExp(escapedGroupSeparator, "g"), ''); var isValid = opts.regex.number(opts).test(bufferStr); if (!isValid) { //let's help the regex a bit bufferStr += "0"; isValid = opts.regex.number(opts).test(bufferStr); if (!isValid) { //make a valid group var lastGroupSeparator = bufferStr.lastIndexOf(opts.groupSeparator); for (var i = bufferStr.length - lastGroupSeparator; i <= 3; i++) { bufferStr += "0"; } isValid = opts.regex.number(opts).test(bufferStr); if (!isValid && !strict) { if (chrs == opts.radixPoint) { isValid = opts.regex.number(opts).test("0" + bufferStr + "0"); if (isValid) { buffer[pos] = "0"; pos++; return { "pos": pos }; } } } } } if (isValid != false && !strict && chrs != opts.radixPoint) { var newPos = opts.postFormat(buffer, pos, false, opts); return { "pos": newPos }; } return isValid; }, cardinality: 1, prevalidator: null } }, insertMode: true, autoUnmask: false }, 'integer': { regex: { number: function (opts) { var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator); var signedExpression = opts.allowPlus || opts.allowMinus ? "[" + (opts.allowPlus ? "\+" : "") + (opts.allowMinus ? "-" : "") + "]?" : ""; return new RegExp("^" + signedExpression + "(\\d+|\\d{1," + opts.groupSize + "}((" + escapedGroupSeparator + "\\d{" + opts.groupSize + "})?)+)$"); } }, alias: "decimal" } }); })(jQuery); /* Input Mask plugin extensions http://github.com/RobinHerbots/jquery.inputmask Copyright (c) 2010 - 2014 Robin Herbots Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) Version: 2.4.18 Regex extensions on the jquery.inputmask base Allows for using regular expressions as a mask */ (function ($) { $.extend($.inputmask.defaults.aliases, { // $(selector).inputmask("Regex", { regex: "[0-9]*"} 'Regex': { mask: "r", greedy: false, repeat: "*", regex: null, regexTokens: null, //Thx to https://github.com/slevithan/regex-colorizer for the tokenizer regex tokenizer: /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g, quantifierFilter: /[0-9]+[^,]/, definitions: { 'r': { validator: function (chrs, buffer, pos, strict, opts) { function regexToken() { this.matches = []; this.isGroup = false; this.isQuantifier = false; this.isLiteral = false; } function analyseRegex() { var currentToken = new regexToken(), match, m, opengroups = []; opts.regexTokens = []; // The tokenizer regex does most of the tokenization grunt work while (match = opts.tokenizer.exec(opts.regex)) { m = match[0]; switch (m.charAt(0)) { case "[": // Character class case "\\": // Escape or backreference if (opengroups.length > 0) { opengroups[opengroups.length - 1]["matches"].push(m); } else { currentToken.matches.push(m); } break; case "(": // Group opening if (!currentToken.isGroup && currentToken.matches.length > 0) opts.regexTokens.push(currentToken); currentToken = new regexToken(); currentToken.isGroup = true; opengroups.push(currentToken); break; case ")": // Group closing var groupToken = opengroups.pop(); if (opengroups.length > 0) { opengroups[opengroups.length - 1]["matches"].push(groupToken); } else { opts.regexTokens.push(groupToken); currentToken = new regexToken(); } break; case "{": //Quantifier var quantifier = new regexToken(); quantifier.isQuantifier = true; quantifier.matches.push(m); if (opengroups.length > 0) { opengroups[opengroups.length - 1]["matches"].push(quantifier); } else { currentToken.matches.push(quantifier); } break; default: // Vertical bar (alternator) // ^ or $ anchor // Dot (.) // Literal character sequence var literal = new regexToken(); literal.isLiteral = true; literal.matches.push(m); if (opengroups.length > 0) { opengroups[opengroups.length - 1]["matches"].push(literal); } else { currentToken.matches.push(literal); } } } if (currentToken.matches.length > 0) opts.regexTokens.push(currentToken); }; function validateRegexToken(token, fromGroup) { var isvalid = false; if (fromGroup) { regexPart += "("; openGroupCount++; } for (var mndx = 0; mndx < token["matches"].length; mndx++) { var matchToken = token["matches"][mndx]; if (matchToken["isGroup"] == true) { isvalid = validateRegexToken(matchToken, true); } else if (matchToken["isQuantifier"] == true) { matchToken = matchToken["matches"][0]; var quantifierMax = opts.quantifierFilter.exec(matchToken)[0].replace("}", ""); var testExp = regexPart + "{1," + quantifierMax + "}"; //relax quantifier validation for (var j = 0; j < openGroupCount; j++) { testExp += ")"; } var exp = new RegExp("^(" + testExp + ")$"); isvalid = exp.test(bufferStr); regexPart += matchToken; } else if (matchToken["isLiteral"] == true) { matchToken = matchToken["matches"][0]; var testExp = regexPart, openGroupCloser = ""; for (var j = 0; j < openGroupCount; j++) { openGroupCloser += ")"; } for (var k = 0; k < matchToken.length; k++) { //relax literal validation testExp = (testExp + matchToken[k]).replace(/\|$/, ""); var exp = new RegExp("^(" + testExp + openGroupCloser + ")$"); isvalid = exp.test(bufferStr); if (isvalid) break; } regexPart += matchToken; //console.log(bufferStr + " " + exp + " " + isvalid); } else { regexPart += matchToken; var testExp = regexPart.replace(/\|$/, ""); for (var j = 0; j < openGroupCount; j++) { testExp += ")"; } var exp = new RegExp("^(" + testExp + ")$"); isvalid = exp.test(bufferStr); //console.log(bufferStr + " " + exp + " " + isvalid); } if (isvalid) break; } if (fromGroup) { regexPart += ")"; openGroupCount--; } return isvalid; } if (opts.regexTokens == null) { analyseRegex(); } var cbuffer = buffer.slice(), regexPart = "", isValid = false, openGroupCount = 0; cbuffer.splice(pos, 0, chrs); var bufferStr = cbuffer.join(''); for (var i = 0; i < opts.regexTokens.length; i++) { var regexToken = opts.regexTokens[i]; isValid = validateRegexToken(regexToken, regexToken["isGroup"]); if (isValid) break; } return isValid; }, cardinality: 1 } } } }); })(jQuery); /* Input Mask plugin extensions http://github.com/RobinHerbots/jquery.inputmask Copyright (c) 2010 - 2014 Robin Herbots Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) Version: 2.4.18 Phone extension. When using this extension make sure you specify the correct url to get the masks $(selector).inputmask("phone", { url: "Scripts/jquery.inputmask/phone-codes/phone-codes.json", onKeyValidation: function () { //show some metadata in the console console.log($(this).inputmask("getmetadata")["name_en"]); } }); */ (function ($) { $.extend($.inputmask.defaults.aliases, { 'phone': { url: "phone-codes/phone-codes.json", mask: function (opts) { opts.definitions = { 'p': { validator: function () { return false; }, cardinality: 1 }, '#': { validator: "[0-9]", cardinality: 1 } }; var maskList = []; $.ajax({ url: opts.url, async: false, dataType: 'json', success: function (response) { maskList = response; } }); maskList.splice(0, 0, "+p(ppp)ppp-pppp"); return maskList; } } }); })(jQuery);
JavaScript
/*! * jQVMap Version 1.0 * * http://jqvmap.com * * Copyright 2012, Peter Schmalfeldt <manifestinteractive@gmail.com> * Copyright 2011-2012, Kirill Lebedev * Licensed under the MIT license. * * Fork Me @ https://github.com/manifestinteractive/jqvmap */ (function ($) { var apiParams = { colors: 1, values: 1, backgroundColor: 1, scaleColors: 1, normalizeFunction: 1, enableZoom: 1, showTooltip: 1, borderColor: 1, borderWidth: 1, borderOpacity: 1, selectedRegions: 1, multiSelectRegion: 1 }; var apiEvents = { onLabelShow: 'labelShow', onRegionOver: 'regionMouseOver', onRegionOut: 'regionMouseOut', onRegionClick: 'regionClick', onRegionSelect: 'regionSelect', onRegionDeselect: 'regionDeselect' }; $.fn.vectorMap = function (options) { var defaultParams = { map: 'world_en', backgroundColor: '#a5bfdd', color: '#f4f3f0', hoverColor: '#c9dfaf', selectedColor: '#c9dfaf', scaleColors: ['#b6d6ff', '#005ace'], normalizeFunction: 'linear', enableZoom: true, showTooltip: true, borderColor: '#818181', borderWidth: 1, borderOpacity: 0.25, selectedRegions: null, multiSelectRegion: false }, map = this.data('mapObject'); if (options === 'addMap') { WorldMap.maps[arguments[1]] = arguments[2]; } else if (options === 'set' && apiParams[arguments[1]]) { map['set' + arguments[1].charAt(0).toUpperCase() + arguments[1].substr(1)].apply(map, Array.prototype.slice.call(arguments, 2)); } else if (typeof options === 'string' && typeof map[options] === 'function') { return map[options].apply(map, Array.prototype.slice.call(arguments, 1)); } else { $.extend(defaultParams, options); defaultParams.container = this; this.css({ position: 'relative', overflow: 'hidden' }); map = new WorldMap(defaultParams); this.data('mapObject', map); for (var e in apiEvents) { if (defaultParams[e]) { this.bind(apiEvents[e] + '.jqvmap', defaultParams[e]); } } } }; var VectorCanvas = function (width, height, params) { this.mode = window.SVGAngle ? 'svg' : 'vml'; this.params = params; if (this.mode == 'svg') { this.createSvgNode = function (nodeName) { return document.createElementNS(this.svgns, nodeName); }; } else { try { if (!document.namespaces.rvml) { document.namespaces.add("rvml", "urn:schemas-microsoft-com:vml"); } this.createVmlNode = function (tagName) { return document.createElement('<rvml:' + tagName + ' class="rvml">'); }; } catch (e) { this.createVmlNode = function (tagName) { return document.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">'); }; } document.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)"); } if (this.mode == 'svg') { this.canvas = this.createSvgNode('svg'); } else { this.canvas = this.createVmlNode('group'); this.canvas.style.position = 'absolute'; } this.setSize(width, height); }; VectorCanvas.prototype = { svgns: "http://www.w3.org/2000/svg", mode: 'svg', width: 0, height: 0, canvas: null, setSize: function (width, height) { if (this.mode == 'svg') { this.canvas.setAttribute('width', width); this.canvas.setAttribute('height', height); } else { this.canvas.style.width = width + "px"; this.canvas.style.height = height + "px"; this.canvas.coordsize = width + ' ' + height; this.canvas.coordorigin = "0 0"; if (this.rootGroup) { var pathes = this.rootGroup.getElementsByTagName('shape'); for (var i = 0, l = pathes.length; i < l; i++) { pathes[i].coordsize = width + ' ' + height; pathes[i].style.width = width + 'px'; pathes[i].style.height = height + 'px'; } this.rootGroup.coordsize = width + ' ' + height; this.rootGroup.style.width = width + 'px'; this.rootGroup.style.height = height + 'px'; } } this.width = width; this.height = height; }, createPath: function (config) { var node; if (this.mode == 'svg') { node = this.createSvgNode('path'); node.setAttribute('d', config.path); if (this.params.borderColor !== null) { node.setAttribute('stroke', this.params.borderColor); } if (this.params.borderWidth > 0) { node.setAttribute('stroke-width', this.params.borderWidth); node.setAttribute('stroke-linecap', 'round'); node.setAttribute('stroke-linejoin', 'round'); } if (this.params.borderOpacity > 0) { node.setAttribute('stroke-opacity', this.params.borderOpacity); } node.setFill = function (color) { this.setAttribute("fill", color); if (this.getAttribute("original") === null) { this.setAttribute("original", color); } }; node.getFill = function (color) { return this.getAttribute("fill"); }; node.getOriginalFill = function () { return this.getAttribute("original"); }; node.setOpacity = function (opacity) { this.setAttribute('fill-opacity', opacity); }; } else { node = this.createVmlNode('shape'); node.coordorigin = "0 0"; node.coordsize = this.width + ' ' + this.height; node.style.width = this.width + 'px'; node.style.height = this.height + 'px'; node.fillcolor = WorldMap.defaultFillColor; node.stroked = false; node.path = VectorCanvas.pathSvgToVml(config.path); var scale = this.createVmlNode('skew'); scale.on = true; scale.matrix = '0.01,0,0,0.01,0,0'; scale.offset = '0,0'; node.appendChild(scale); var fill = this.createVmlNode('fill'); node.appendChild(fill); node.setFill = function (color) { this.getElementsByTagName('fill')[0].color = color; if (this.getAttribute("original") === null) { this.setAttribute("original", color); } }; node.getFill = function (color) { return this.getElementsByTagName('fill')[0].color; }; node.getOriginalFill = function () { return this.getAttribute("original"); }; node.setOpacity = function (opacity) { this.getElementsByTagName('fill')[0].opacity = parseInt(opacity * 100, 10) + '%'; }; } return node; }, createGroup: function (isRoot) { var node; if (this.mode == 'svg') { node = this.createSvgNode('g'); } else { node = this.createVmlNode('group'); node.style.width = this.width + 'px'; node.style.height = this.height + 'px'; node.style.left = '0px'; node.style.top = '0px'; node.coordorigin = "0 0"; node.coordsize = this.width + ' ' + this.height; } if (isRoot) { this.rootGroup = node; } return node; }, applyTransformParams: function (scale, transX, transY) { if (this.mode == 'svg') { this.rootGroup.setAttribute('transform', 'scale(' + scale + ') translate(' + transX + ', ' + transY + ')'); } else { this.rootGroup.coordorigin = (this.width - transX) + ',' + (this.height - transY); this.rootGroup.coordsize = this.width / scale + ',' + this.height / scale; } } }; VectorCanvas.pathSvgToVml = function (path) { var result = ''; var cx = 0, cy = 0, ctrlx, ctrly; return path.replace(/([MmLlHhVvCcSs])((?:-?(?:\d+)?(?:\.\d+)?,?\s?)+)/g, function (segment, letter, coords, index) { coords = coords.replace(/(\d)-/g, '$1,-').replace(/\s+/g, ',').split(','); if (!coords[0]) { coords.shift(); } for (var i = 0, l = coords.length; i < l; i++) { coords[i] = Math.round(100 * coords[i]); } switch (letter) { case 'm': cx += coords[0]; cy += coords[1]; return 't' + coords.join(','); break; case 'M': cx = coords[0]; cy = coords[1]; return 'm' + coords.join(','); break; case 'l': cx += coords[0]; cy += coords[1]; return 'r' + coords.join(','); break; case 'L': cx = coords[0]; cy = coords[1]; return 'l' + coords.join(','); break; case 'h': cx += coords[0]; return 'r' + coords[0] + ',0'; break; case 'H': cx = coords[0]; return 'l' + cx + ',' + cy; break; case 'v': cy += coords[0]; return 'r0,' + coords[0]; break; case 'V': cy = coords[0]; return 'l' + cx + ',' + cy; break; case 'c': ctrlx = cx + coords[coords.length - 4]; ctrly = cy + coords[coords.length - 3]; cx += coords[coords.length - 2]; cy += coords[coords.length - 1]; return 'v' + coords.join(','); break; case 'C': ctrlx = coords[coords.length - 4]; ctrly = coords[coords.length - 3]; cx = coords[coords.length - 2]; cy = coords[coords.length - 1]; return 'c' + coords.join(','); break; case 's': coords.unshift(cy - ctrly); coords.unshift(cx - ctrlx); ctrlx = cx + coords[coords.length - 4]; ctrly = cy + coords[coords.length - 3]; cx += coords[coords.length - 2]; cy += coords[coords.length - 1]; return 'v' + coords.join(','); break; case 'S': coords.unshift(cy + cy - ctrly); coords.unshift(cx + cx - ctrlx); ctrlx = coords[coords.length - 4]; ctrly = coords[coords.length - 3]; cx = coords[coords.length - 2]; cy = coords[coords.length - 1]; return 'c' + coords.join(','); break; default: return false; break; } return ''; }).replace(/z/g, ''); }; var WorldMap = function (params) { params = params || {}; var map = this; var mapData = WorldMap.maps[params.map]; this.selectedRegions = []; this.multiSelectRegion = params.multiSelectRegion; this.container = params.container; this.defaultWidth = mapData.width; this.defaultHeight = mapData.height; this.color = params.color; this.selectedColor = params.selectedColor; this.hoverColor = params.hoverColor; this.hoverOpacity = params.hoverOpacity; this.setBackgroundColor(params.backgroundColor); this.width = params.container.width(); this.height = params.container.height(); this.resize(); jQuery(window).resize(function () { map.width = params.container.width(); map.height = params.container.height(); map.resize(); map.canvas.setSize(map.width, map.height); map.applyTransform(); }); this.canvas = new VectorCanvas(this.width, this.height, params); params.container.append(this.canvas.canvas); this.makeDraggable(); this.rootGroup = this.canvas.createGroup(true); this.index = WorldMap.mapIndex; this.label = jQuery('<div/>').addClass('jqvmap-label').appendTo(jQuery('body')); if (params.enableZoom) { jQuery('<div/>').addClass('jqvmap-zoomin').text('+').appendTo(params.container); jQuery('<div/>').addClass('jqvmap-zoomout').html('&#x2212;').appendTo(params.container); } map.countries = []; for (var key in mapData.pathes) { var path = this.canvas.createPath({ path: mapData.pathes[key].path }); path.setFill(this.color); path.id = map.getCountryId(key); map.countries[key] = path; if (this.canvas.mode == 'svg') { path.setAttribute('class', 'jvectormap-region'); } else { jQuery(path).addClass('jvectormap-region'); } jQuery(this.rootGroup).append(path); } jQuery(params.container).delegate(this.canvas.mode == 'svg' ? 'path' : 'shape', 'mouseover mouseout', function (e) { var path = e.target, code = e.target.id.split('_').pop(), labelShowEvent = $.Event('labelShow.jqvmap'), regionMouseOverEvent = $.Event('regionMouseOver.jqvmap'); if (e.type == 'mouseover') { jQuery(params.container).trigger(regionMouseOverEvent, [code, mapData.pathes[code].name]); if (!regionMouseOverEvent.isDefaultPrevented()) { map.highlight(code, path); } if (params.showTooltip) { map.label.text(mapData.pathes[code].name); jQuery(params.container).trigger(labelShowEvent, [map.label, code]); if (!labelShowEvent.isDefaultPrevented()) { map.label.show(); map.labelWidth = map.label.width(); map.labelHeight = map.label.height(); } } } else { map.unhighlight(code, path); map.label.hide(); jQuery(params.container).trigger('regionMouseOut.jqvmap', [code, mapData.pathes[code].name]); } }); jQuery(params.container).delegate(this.canvas.mode == 'svg' ? 'path' : 'shape', 'click', function (e) { if (!params.multiSelectRegion) { for (var key in mapData.pathes) { map.countries[key].currentFillColor = map.countries[key].getOriginalFill(); map.countries[key].setFill(map.countries[key].getOriginalFill()); } } var path = e.target; var code = e.target.id.split('_').pop(); jQuery(params.container).trigger('regionClick.jqvmap', [code, mapData.pathes[code].name]); if (map.selectedRegions.indexOf(code) !== -1) { map.deselect(code, path); } else { map.select(code, path); } //console.log(selectedRegions); }); if (params.showTooltip) { params.container.mousemove(function (e) { if (map.label.is(':visible')) { map.label.css({ left: e.pageX - 15 - map.labelWidth, top: e.pageY - 15 - map.labelHeight }); } }); } this.setColors(params.colors); this.canvas.canvas.appendChild(this.rootGroup); this.applyTransform(); this.colorScale = new ColorScale(params.scaleColors, params.normalizeFunction, params.valueMin, params.valueMax); if (params.values) { this.values = params.values; this.setValues(params.values); } if (params.selectedRegions) { if (params.selectedRegions instanceof Array) { for(var k in params.selectedRegions) { this.select(params.selectedRegions[k].toLowerCase()); } } else { this.select(params.selectedRegions.toLowerCase()); } } this.bindZoomButtons(); WorldMap.mapIndex++; }; WorldMap.prototype = { transX: 0, transY: 0, scale: 1, baseTransX: 0, baseTransY: 0, baseScale: 1, width: 0, height: 0, countries: {}, countriesColors: {}, countriesData: {}, zoomStep: 1.4, zoomMaxStep: 4, zoomCurStep: 1, setColors: function (key, color) { if (typeof key == 'string') { this.countries[key].setFill(color); this.countries[key].setAttribute("original", color); } else { var colors = key; for (var code in colors) { if (this.countries[code]) { this.countries[code].setFill(colors[code]); this.countries[code].setAttribute("original", colors[code]); } } } }, setValues: function (values) { var max = 0, min = Number.MAX_VALUE, val; for (var cc in values) { val = parseFloat(values[cc]); if (val > max) { max = values[cc]; } if (val && val < min) { min = val; } } this.colorScale.setMin(min); this.colorScale.setMax(max); var colors = {}; for (cc in values) { val = parseFloat(values[cc]); if (val) { colors[cc] = this.colorScale.getColor(val); } else { colors[cc] = this.color; } } this.setColors(colors); this.values = values; }, setBackgroundColor: function (backgroundColor) { this.container.css('background-color', backgroundColor); }, setScaleColors: function (colors) { this.colorScale.setColors(colors); if (this.values) { this.setValues(this.values); } }, setNormalizeFunction: function (f) { this.colorScale.setNormalizeFunction(f); if (this.values) { this.setValues(this.values); } }, highlight: function (cc, path) { path = path || $('#' + this.getCountryId(cc))[0]; if (this.hoverOpacity) { path.setOpacity(this.hoverOpacity); } else if (this.hoverColor) { path.currentFillColor = path.getFill() + ''; path.setFill(this.hoverColor); } }, unhighlight: function (cc, path) { path = path || $('#' + this.getCountryId(cc))[0]; path.setOpacity(1); if (path.currentFillColor) { path.setFill(path.currentFillColor); } }, select: function (cc, path) { path = path || $('#' + this.getCountryId(cc))[0]; if(this.selectedRegions.indexOf(cc) < 0) { if (this.multiSelectRegion) { this.selectedRegions.push(cc); } else { this.selectedRegions = [cc]; } // MUST BE after the change of selectedRegions // Otherwise, we might loop $(this.container).trigger('regionSelect.jqvmap', [cc]); if (this.selectedColor) { path.currentFillColor = this.selectedColor; path.setFill(this.selectedColor); } } }, deselect: function (cc, path) { path = path || $('#' + this.getCountryId(cc))[0]; if(this.selectedRegions.indexOf(cc) >= 0) { this.selectedRegions.splice(this.selectedRegions.indexOf(cc), 1); // MUST BE after the change of selectedRegions // Otherwise, we might loop $(this.container).trigger('regionDeselect.jqvmap', [cc]); path.currentFillColor = path.getOriginalFill(); path.setFill(path.getOriginalFill()); } }, isSelected: function(cc) { return this.selectedRegions.indexOf(cc) >= 0; }, resize: function () { var curBaseScale = this.baseScale; if (this.width / this.height > this.defaultWidth / this.defaultHeight) { this.baseScale = this.height / this.defaultHeight; this.baseTransX = Math.abs(this.width - this.defaultWidth * this.baseScale) / (2 * this.baseScale); } else { this.baseScale = this.width / this.defaultWidth; this.baseTransY = Math.abs(this.height - this.defaultHeight * this.baseScale) / (2 * this.baseScale); } this.scale *= this.baseScale / curBaseScale; this.transX *= this.baseScale / curBaseScale; this.transY *= this.baseScale / curBaseScale; }, reset: function () { this.countryTitle.reset(); for (var key in this.countries) { this.countries[key].setFill(WorldMap.defaultColor); } this.scale = this.baseScale; this.transX = this.baseTransX; this.transY = this.baseTransY; this.applyTransform(); }, applyTransform: function () { var maxTransX, maxTransY, minTransX, minTransY; if (this.defaultWidth * this.scale <= this.width) { maxTransX = (this.width - this.defaultWidth * this.scale) / (2 * this.scale); minTransX = (this.width - this.defaultWidth * this.scale) / (2 * this.scale); } else { maxTransX = 0; minTransX = (this.width - this.defaultWidth * this.scale) / this.scale; } if (this.defaultHeight * this.scale <= this.height) { maxTransY = (this.height - this.defaultHeight * this.scale) / (2 * this.scale); minTransY = (this.height - this.defaultHeight * this.scale) / (2 * this.scale); } else { maxTransY = 0; minTransY = (this.height - this.defaultHeight * this.scale) / this.scale; } if (this.transY > maxTransY) { this.transY = maxTransY; } else if (this.transY < minTransY) { this.transY = minTransY; } if (this.transX > maxTransX) { this.transX = maxTransX; } else if (this.transX < minTransX) { this.transX = minTransX; } this.canvas.applyTransformParams(this.scale, this.transX, this.transY); }, makeDraggable: function () { var mouseDown = false; var oldPageX, oldPageY; var self = this; self.isMoving = false; self.isMovingTimeout = false; this.container.mousemove(function (e) { if (mouseDown) { var curTransX = self.transX; var curTransY = self.transY; self.transX -= (oldPageX - e.pageX) / self.scale; self.transY -= (oldPageY - e.pageY) / self.scale; self.applyTransform(); oldPageX = e.pageX; oldPageY = e.pageY; self.isMoving = true; if (self.isMovingTimeout) { clearTimeout(self.isMovingTimeout); } } return false; }).mousedown(function (e) { mouseDown = true; oldPageX = e.pageX; oldPageY = e.pageY; return false; }).mouseup(function () { mouseDown = false; self.isMovingTimeout = setTimeout(function () { self.isMoving = false; }, 100); return false; }); }, bindZoomButtons: function () { var map = this; var sliderDelta = (jQuery('#zoom').innerHeight() - 6 * 2 - 15 * 2 - 3 * 2 - 7 - 6) / (this.zoomMaxStep - this.zoomCurStep); this.container.find('.jqvmap-zoomin').click(function () { if (map.zoomCurStep < map.zoomMaxStep) { var curTransX = map.transX; var curTransY = map.transY; var curScale = map.scale; map.transX -= (map.width / map.scale - map.width / (map.scale * map.zoomStep)) / 2; map.transY -= (map.height / map.scale - map.height / (map.scale * map.zoomStep)) / 2; map.setScale(map.scale * map.zoomStep); map.zoomCurStep++; jQuery('#zoomSlider').css('top', parseInt(jQuery('#zoomSlider').css('top'), 10) - sliderDelta); } }); this.container.find('.jqvmap-zoomout').click(function () { if (map.zoomCurStep > 1) { var curTransX = map.transX; var curTransY = map.transY; var curScale = map.scale; map.transX += (map.width / (map.scale / map.zoomStep) - map.width / map.scale) / 2; map.transY += (map.height / (map.scale / map.zoomStep) - map.height / map.scale) / 2; map.setScale(map.scale / map.zoomStep); map.zoomCurStep--; jQuery('#zoomSlider').css('top', parseInt(jQuery('#zoomSlider').css('top'), 10) + sliderDelta); } }); }, setScale: function (scale) { this.scale = scale; this.applyTransform(); }, getCountryId: function (cc) { return 'jqvmap' + this.index + '_' + cc; } }; WorldMap.xlink = "http://www.w3.org/1999/xlink"; WorldMap.mapIndex = 1; WorldMap.maps = {}; var ColorScale = function (colors, normalizeFunction, minValue, maxValue) { if (colors) { this.setColors(colors); } if (normalizeFunction) { this.setNormalizeFunction(normalizeFunction); } if (minValue) { this.setMin(minValue); } if (minValue) { this.setMax(maxValue); } }; ColorScale.prototype = { colors: [], setMin: function (min) { this.clearMinValue = min; if (typeof this.normalize === 'function') { this.minValue = this.normalize(min); } else { this.minValue = min; } }, setMax: function (max) { this.clearMaxValue = max; if (typeof this.normalize === 'function') { this.maxValue = this.normalize(max); } else { this.maxValue = max; } }, setColors: function (colors) { for (var i = 0; i < colors.length; i++) { colors[i] = ColorScale.rgbToArray(colors[i]); } this.colors = colors; }, setNormalizeFunction: function (f) { if (f === 'polynomial') { this.normalize = function (value) { return Math.pow(value, 0.2); }; } else if (f === 'linear') { delete this.normalize; } else { this.normalize = f; } this.setMin(this.clearMinValue); this.setMax(this.clearMaxValue); }, getColor: function (value) { if (typeof this.normalize === 'function') { value = this.normalize(value); } var lengthes = []; var fullLength = 0; var l; for (var i = 0; i < this.colors.length - 1; i++) { l = this.vectorLength(this.vectorSubtract(this.colors[i + 1], this.colors[i])); lengthes.push(l); fullLength += l; } var c = (this.maxValue - this.minValue) / fullLength; for (i = 0; i < lengthes.length; i++) { lengthes[i] *= c; } i = 0; value -= this.minValue; while (value - lengthes[i] >= 0) { value -= lengthes[i]; i++; } var color; if (i == this.colors.length - 1) { color = this.vectorToNum(this.colors[i]).toString(16); } else { color = (this.vectorToNum(this.vectorAdd(this.colors[i], this.vectorMult(this.vectorSubtract(this.colors[i + 1], this.colors[i]), (value) / (lengthes[i]))))).toString(16); } while (color.length < 6) { color = '0' + color; } return '#' + color; }, vectorToNum: function (vector) { var num = 0; for (var i = 0; i < vector.length; i++) { num += Math.round(vector[i]) * Math.pow(256, vector.length - i - 1); } return num; }, vectorSubtract: function (vector1, vector2) { var vector = []; for (var i = 0; i < vector1.length; i++) { vector[i] = vector1[i] - vector2[i]; } return vector; }, vectorAdd: function (vector1, vector2) { var vector = []; for (var i = 0; i < vector1.length; i++) { vector[i] = vector1[i] + vector2[i]; } return vector; }, vectorMult: function (vector, num) { var result = []; for (var i = 0; i < vector.length; i++) { result[i] = vector[i] * num; } return result; }, vectorLength: function (vector) { var result = 0; for (var i = 0; i < vector.length; i++) { result += vector[i] * vector[i]; } return Math.sqrt(result); } }; ColorScale.arrayToRgb = function (ar) { var rgb = '#'; var d; for (var i = 0; i < ar.length; i++) { d = ar[i].toString(16); rgb += d.length == 1 ? '0' + d : d; } return rgb; }; ColorScale.rgbToArray = function (rgb) { rgb = rgb.substr(1); return [parseInt(rgb.substr(0, 2), 16), parseInt(rgb.substr(2, 2), 16), parseInt(rgb.substr(4, 2), 16)]; }; })(jQuery);
JavaScript
// Ion.RangeSlider // version 1.7.2 Build: 134 // © 2013 Denis Ineshin | IonDen.com // // Project page: http://ionden.com/a/plugins/ion.rangeSlider/ // GitHub page: https://github.com/IonDen/ion.rangeSlider // // Released under MIT licence: // http://ionden.com/a/plugins/licence-en.html // ===================================================================================================================== (function($){ var pluginCount = 0; var oldie = (function(){ var n = navigator.userAgent, r = /msie\s\d+/i, v; if(n.search(r) > 0){ v = r.exec(n).toString(); v = v.split(" ")[1]; if(v < 9) { return true; } else { return false; } } else { return false; } }()); var isTouch = (function() { try { document.createEvent("TouchEvent"); return true; } catch (e) { return false; } }()); var methods = { init: function(options){ var settings = $.extend({ min: 10, max: 100, from: null, to: null, type: "single", step: 1, prefix: "", postfix: "", hasGrid: false, hideText: false, prettify: true, onChange: null, onFinish: null }, options); var baseHTML = '<span class="irs">'; // irs = ion range slider css prefix baseHTML += '<span class="irs-line"><span class="irs-line-left"></span><span class="irs-line-mid"></span><span class="irs-line-right"></span></span>'; baseHTML += '<span class="irs-min">0</span><span class="irs-max">1</span>'; baseHTML += '<span class="irs-from">0</span><span class="irs-to">0</span><span class="irs-single">0</span>'; baseHTML += '</span>'; baseHTML += '<span class="irs-grid"></span>'; var singleHTML = '<span class="irs-slider single"></span>'; var doubleHTML = '<span class="irs-diapason"></span>'; doubleHTML += '<span class="irs-slider from"></span>'; doubleHTML += '<span class="irs-slider to"></span>'; return this.each(function(){ var slider = $(this); if(slider.data("isActive")) { return; } slider.data("isActive", true); pluginCount++; this.pluginCount = pluginCount; // check default values if (typeof settings.from !== "number") { settings.from = settings.min; } if (typeof settings.to !== "number") { settings.to = settings.max; } if (slider.attr("value")) { settings.min = parseInt(slider.attr("value").split(";")[0], 10); settings.max = parseInt(slider.attr("value").split(";")[1], 10); } // extend from data-* if (typeof slider.data("from") === "number") { settings.from = parseInt(slider.data("from"), 10); } if (typeof slider.data("to") === "number") { settings.to = parseInt(slider.data("to"), 10); } if (slider.data("step")) { settings.step = parseFloat(slider.data("step")); } if (slider.data("type")) { settings.type = slider.data("type"); } if (slider.data("prefix")) { settings.prefix = slider.data("prefix"); } if (slider.data("postfix")) { settings.postfix = slider.data("postfix"); } if (slider.data("hasgrid")) { settings.hasGrid = slider.data("hasgrid"); } if (slider.data("hidetext")) { settings.hideText = slider.data("hidetext"); } if (slider.data("prettify")) { settings.prettify = slider.data("prettify"); } // fix diapason if(settings.from < settings.min) { settings.from = settings.min; } if(settings.to > settings.max) { settings.to = settings.max; } if(settings.type === "double") { if(settings.from > settings.to) { settings.from = settings.to; } if(settings.to < settings.from) { settings.to = settings.from; } } var prettify = function(num){ var n = num.toString(); if(settings.prettify) { n = n.replace(/(\d{1,3}(?=(?:\d\d\d)+(?!\d)))/g,"$1 "); } return n; }; var containerHTML = '<span class="irs" id="irs-' + this.pluginCount + '"></span>'; slider[0].style.display = "none"; slider.before(containerHTML); var $container = $("#irs-" + this.pluginCount), $body = $(document.body), $window = $(window), $rangeSlider, $fieldMin, $fieldMax, $fieldFrom, $fieldTo, $fieldSingle, $singleSlider, $fromSlider, $toSlider, $activeSlider, $diapason, $grid; var allowDrag = false, sliderIsActive = false, firstStart = true, numbers = {}; var mouseX = 0, fieldMinWidth = 0, fieldMaxWidth = 0, normalWidth = 0, fullWidth = 0, sliderWidth = 0, width = 0, left = 0, right = 0, minusX = 0, stepFloat = 0; if(parseInt(settings.step, 10) !== parseFloat(settings.step)) { stepFloat = settings.step.toString().split(".")[1]; stepFloat = Math.pow(10, stepFloat.length); } // public methods this.updateData = function(options){ settings = $.extend(settings, options); removeHTML(); }; this.removeSlider = function(){ $container.find("*").off(); $container.html("").remove(); slider.data("isActive", false); slider.show(); }; // private methods var removeHTML = function(){ $container.find("*").off(); $container.html(""); placeHTML(); }; var placeHTML = function(){ $container.html(baseHTML); $rangeSlider = $container.find(".irs"); $fieldMin = $rangeSlider.find(".irs-min"); $fieldMax = $rangeSlider.find(".irs-max"); $fieldFrom = $rangeSlider.find(".irs-from"); $fieldTo = $rangeSlider.find(".irs-to"); $fieldSingle = $rangeSlider.find(".irs-single"); $grid = $container.find(".irs-grid"); if(settings.hideText) { $fieldMin[0].style.display = "none"; $fieldMax[0].style.display = "none"; $fieldFrom[0].style.display = "none"; $fieldTo[0].style.display = "none"; $fieldSingle[0].style.display = "none"; } else { $fieldMin.html(settings.prefix + prettify(settings.min) + settings.postfix); $fieldMax.html(settings.prefix + prettify(settings.max) + settings.postfix); } fieldMinWidth = $fieldMin.outerWidth(); fieldMaxWidth = $fieldMax.outerWidth(); if(settings.type === "single") { $rangeSlider.append(singleHTML); $singleSlider = $rangeSlider.find(".single"); $singleSlider.on("mousedown", function(e){ e.preventDefault(); e.stopPropagation(); calcDimensions(e, $(this), null); allowDrag = true; sliderIsActive = true; if(oldie) { $("*").prop("unselectable",true); } }); if(isTouch) { $singleSlider.on("touchstart", function(e){ e.preventDefault(); e.stopPropagation(); calcDimensions(e.originalEvent.touches[0], $(this), null); allowDrag = true; sliderIsActive = true; }); } } else if(settings.type === "double") { $rangeSlider.append(doubleHTML); $fromSlider = $rangeSlider.find(".from"); $toSlider = $rangeSlider.find(".to"); $diapason = $rangeSlider.find(".irs-diapason"); setDiapason(); $fromSlider.on("mousedown", function(e){ e.preventDefault(); e.stopPropagation(); $(this).addClass("last"); $toSlider.removeClass("last"); calcDimensions(e, $(this), "from"); allowDrag = true; sliderIsActive = true; if(oldie) { $("*").prop("unselectable",true); } }); $toSlider.on("mousedown", function(e){ e.preventDefault(); e.stopPropagation(); $(this).addClass("last"); $fromSlider.removeClass("last"); calcDimensions(e, $(this), "to"); allowDrag = true; sliderIsActive = true; if(oldie) { $("*").prop("unselectable",true); } }); if(isTouch) { $fromSlider.on("touchstart", function(e){ e.preventDefault(); e.stopPropagation(); $(this).addClass("last"); $toSlider.removeClass("last"); calcDimensions(e.originalEvent.touches[0], $(this), "from"); allowDrag = true; sliderIsActive = true; }); $toSlider.on("touchstart", function(e){ e.preventDefault(); e.stopPropagation(); $(this).addClass("last"); $fromSlider.removeClass("last"); calcDimensions(e.originalEvent.touches[0], $(this), "to"); allowDrag = true; sliderIsActive = true; }); } if(settings.to === settings.max) { $fromSlider.addClass("last"); } } $body.on("mouseup", function(){ if(!allowDrag) return; sliderIsActive = false; allowDrag = false; $activeSlider.removeAttr("id"); $activeSlider = null; if(settings.type === "double") { setDiapason(); } getNumbers(); if(oldie) { $("*").prop("unselectable",false); } }); $body.on("mousemove", function(e){ if(allowDrag) { mouseX = e.pageX; dragSlider(); } }); if(isTouch) { $window.on("touchend", function(){ if(!allowDrag) return; sliderIsActive = false; allowDrag = false; $activeSlider.removeAttr("id"); $activeSlider = null; if(settings.type === "double") { setDiapason(); } getNumbers(); }); $window.on("touchmove", function(e){ if(allowDrag) { mouseX = e.originalEvent.touches[0].pageX; dragSlider(); } }); } getSize(); setNumbers(); if(settings.hasGrid) { setGrid(); } }; var getSize = function(){ normalWidth = $rangeSlider.width(); if($singleSlider) { sliderWidth = $singleSlider.width(); } else { sliderWidth = $fromSlider.width(); } fullWidth = normalWidth - sliderWidth; }; var calcDimensions = function(e, currentSlider, whichSlider){ getSize(); firstStart = false; $activeSlider = currentSlider; $activeSlider.attr("id", "irs-active-slider"); var _x1 = $activeSlider.offset().left, _x2 = e.pageX - _x1; minusX = _x1 + _x2 - $activeSlider.position().left; if(settings.type === "single") { width = $rangeSlider.width() - sliderWidth; } else if(settings.type === "double") { if(whichSlider === "from") { left = 0; right = parseInt($toSlider.css("left"), 10); } else { left = parseInt($fromSlider.css("left"), 10); right = $rangeSlider.width() - sliderWidth; } } }; var setDiapason = function(){ var _w = $fromSlider.width(), _x = parseInt($fromSlider[0].style.left, 10) || $fromSlider.position().left, _width = parseInt($toSlider[0].style.left, 10) || $toSlider.position().left, x = _x + (_w / 2), w = _width - _x; $diapason[0].style.left = x + "px"; $diapason[0].style.width = w + "px"; }; var dragSlider = function(){ var x = Math.round(mouseX - minusX); if(settings.type === "single") { if(x < 0) { x = 0; } if(x > width) { x = width; } getNumbers(); } else if(settings.type === "double") { if(x < left) { x = left; } if(x > right) { x = right; } getNumbers(); setDiapason(); } $activeSlider[0].style.left = x + "px"; }; var getNumbers = function(){ var nums = { fromNumber: 0, toNumber: 0, fromPers: 0, toPers: 0, fromX: 0, toX: 0 }; var diapason = settings.max - settings.min, _from, _to; if(settings.type === "single") { nums.fromX = parseInt($singleSlider[0].style.left, 10) || $singleSlider.position().left; nums.fromPers = nums.fromX / fullWidth * 100; _from = (diapason / 100 * nums.fromPers) + parseInt(settings.min, 10); nums.fromNumber = Math.round(_from / settings.step) * settings.step; if(stepFloat) { nums.fromNumber = parseInt(nums.fromNumber * stepFloat, 10) / stepFloat; } } else if(settings.type === "double") { nums.fromX = parseInt($fromSlider[0].style.left, 10) || $fromSlider.position().left; nums.fromPers = nums.fromX / fullWidth * 100; _from = (diapason / 100 * nums.fromPers) + parseInt(settings.min, 10); nums.fromNumber = Math.round(_from / settings.step) * settings.step; nums.toX = parseInt($toSlider[0].style.left, 10) || $toSlider.position().left; nums.toPers = nums.toX / fullWidth * 100; _to = (diapason / 100 * nums.toPers) + parseInt(settings.min, 10); nums.toNumber = Math.round(_to / settings.step) * settings.step; if(stepFloat) { nums.fromNumber = parseInt(nums.fromNumber * stepFloat, 10) / stepFloat; nums.toNumber = parseInt(nums.toNumber * stepFloat, 10) / stepFloat; } } numbers = nums; setFields(); }; var setNumbers = function(){ var nums = { fromNumber: settings.from, toNumber: settings.to, fromPers: 0, toPers: 0, fromX: 0, toX: 0 }; var diapason = settings.max - settings.min; if(settings.type === "single") { nums.fromPers = (nums.fromNumber - settings.min) / diapason * 100; nums.fromX = Math.round(fullWidth / 100 * nums.fromPers); $singleSlider[0].style.left = nums.fromX + "px"; } else if(settings.type === "double") { nums.fromPers = (nums.fromNumber - settings.min) / diapason * 100; nums.fromX = Math.round(fullWidth / 100 * nums.fromPers); $fromSlider[0].style.left = nums.fromX + "px"; nums.toPers = (nums.toNumber - settings.min) / diapason * 100; nums.toX = Math.round(fullWidth / 100 * nums.toPers); $toSlider[0].style.left = nums.toX + "px"; setDiapason(); } numbers = nums; setFields(); }; var setFields = function(){ var _from, _fromW, _fromX, _to, _toW, _toX, _single, _singleW, _singleX, _slW = (sliderWidth / 2); if(settings.type === "single") { if(!settings.hideText) { $fieldFrom[0].style.display = "none"; $fieldTo[0].style.display = "none"; _single = settings.prefix + prettify(numbers.fromNumber) + settings.postfix; $fieldSingle.html(_single); _singleW = $fieldSingle.outerWidth(); _singleX = numbers.fromX - (_singleW / 2) + _slW; if(_singleX < 0) { _singleX = 0; } if(_singleX > normalWidth - _singleW) { _singleX = normalWidth - _singleW; } $fieldSingle[0].style.left = _singleX + "px"; if(_singleX < fieldMinWidth) { $fieldMin[0].style.display = "none"; } else { $fieldMin[0].style.display = "block"; } if(_singleX + _singleW > normalWidth - fieldMaxWidth) { $fieldMax[0].style.display = "none"; } else { $fieldMax[0].style.display = "block"; } } slider.attr("value", parseInt(numbers.fromNumber, 10)); } else if(settings.type === "double") { if(!settings.hideText) { _from = settings.prefix + prettify(numbers.fromNumber) + settings.postfix; _to = settings.prefix + prettify(numbers.toNumber) + settings.postfix; if(numbers.fromNumber != numbers.toNumber) { _single = settings.prefix + prettify(numbers.fromNumber) + " — " + settings.prefix + prettify(numbers.toNumber) + settings.postfix; } else { _single = settings.prefix + prettify(numbers.fromNumber) + settings.postfix; } $fieldFrom.html(_from); $fieldTo.html(_to); $fieldSingle.html(_single); _fromW = $fieldFrom.outerWidth(); _fromX = numbers.fromX - (_fromW / 2) + _slW; if(_fromX < 0) { _fromX = 0; } if(_fromX > normalWidth - _fromW) { _fromX = normalWidth - _fromW; } $fieldFrom[0].style.left = _fromX + "px"; _toW = $fieldTo.outerWidth(); _toX = numbers.toX - (_toW / 2) + _slW; if(_toX < 0) { _toX = 0; } if(_toX > normalWidth - _toW) { _toX = normalWidth - _toW; } $fieldTo[0].style.left = _toX + "px"; _singleW = $fieldSingle.outerWidth(); _singleX = numbers.fromX + ((numbers.toX - numbers.fromX) / 2) - (_singleW / 2) + _slW; if(_singleX < 0) { _singleX = 0; } if(_singleX > normalWidth - _singleW) { _singleX = normalWidth - _singleW; } $fieldSingle[0].style.left = _singleX + "px"; if(_fromX + _fromW < _toX) { $fieldSingle[0].style.display = "none"; $fieldFrom[0].style.display = "block"; $fieldTo[0].style.display = "block"; } else { $fieldSingle[0].style.display = "block"; $fieldFrom[0].style.display = "none"; $fieldTo[0].style.display = "none"; } if(_singleX < fieldMinWidth || _fromX < fieldMinWidth) { $fieldMin[0].style.display = "none"; } else { $fieldMin[0].style.display = "block"; } if(_singleX + _singleW > normalWidth - fieldMaxWidth || _toX + _toW > normalWidth - fieldMaxWidth) { $fieldMax[0].style.display = "none"; } else { $fieldMax[0].style.display = "block"; } } slider.attr("value", parseInt(numbers.fromNumber, 10) + ";" + parseInt(numbers.toNumber, 10)); } // trigger callback function if(typeof settings.onChange === "function") { settings.onChange.call(this, numbers); } // trigger finish function if(typeof settings.onFinish === "function" && !sliderIsActive && !firstStart) { settings.onFinish.call(this, numbers); } }; var setGrid = function(){ $container.addClass("irs-with-grid"); var i, text = '', step = 0, tStep = 0, gridHTML = '', smNum = 20, bigNum = 4; for(i = 0; i <= smNum; i++){ step = Math.floor(normalWidth / smNum * i); if(step >= normalWidth) { step = normalWidth - 1; } gridHTML += '<span class="irs-grid-pol small" style="left: ' + step + 'px;"></span>'; } for(i = 0; i <= bigNum; i++){ step = Math.floor(normalWidth / bigNum * i); if(step >= normalWidth) { step = normalWidth - 1; } gridHTML += '<span class="irs-grid-pol" style="left: ' + step + 'px;"></span>'; if(stepFloat) { text = (settings.min + ((settings.max -settings.min) / bigNum * i)); text = (text / settings.step) * settings.step; text = parseInt(text * stepFloat, 10) / stepFloat; } else { text = Math.round(settings.min + ((settings.max -settings.min) / bigNum * i)); text = Math.round(text / settings.step) * settings.step; text = prettify(text); } if(i === 0) { tStep = step; gridHTML += '<span class="irs-grid-text" style="left: ' + tStep + 'px; text-align: left;">' + text + '</span>'; } else if(i === bigNum) { tStep = step - 100; gridHTML += '<span class="irs-grid-text" style="left: ' + tStep + 'px; text-align: right;">' + text + '</span>'; } else { tStep = step - 50; gridHTML += '<span class="irs-grid-text" style="left: ' + tStep + 'px;">' + text + '</span>'; } } $grid.html(gridHTML); }; placeHTML(); }); }, update: function(options){ return this.each(function(){ this.updateData(options); }); }, remove: function(){ return this.each(function(){ this.removeSlider(); }); } }; $.fn.ionRangeSlider = function(method){ if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist for jQuery.ionRangeSlider'); } }; })(jQuery);
JavaScript
/*! * MockJax - jQuery Plugin to Mock Ajax requests * * Version: 1.5.0pre * Released: * Home: http://github.com/appendto/jquery-mockjax * Author: Jonathan Sharp (http://jdsharp.com) * License: MIT,GPL * * Copyright (c) 2011 appendTo LLC. * Dual licensed under the MIT or GPL licenses. * http://appendto.com/open-source-licenses */ (function($) { var _ajax = $.ajax, mockHandlers = [], CALLBACK_REGEX = /=\?(&|$)/, jsc = (new Date()).getTime(); // Parse the given XML string. function parseXML(xml) { if ( window['DOMParser'] == undefined && window.ActiveXObject ) { DOMParser = function() { }; DOMParser.prototype.parseFromString = function( xmlString ) { var doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML( xmlString ); return doc; }; } try { var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' ); if ( $.isXMLDoc( xmlDoc ) ) { var err = $('parsererror', xmlDoc); if ( err.length == 1 ) { throw('Error: ' + $(xmlDoc).text() ); } } else { throw('Unable to parse XML'); } } catch( e ) { var msg = ( e.name == undefined ? e : e.name + ': ' + e.message ); $(document).trigger('xmlParseError', [ msg ]); return undefined; } return xmlDoc; } // Trigger a jQuery event function trigger(s, type, args) { (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args); } // Check if the data field on the mock handler and the request match. This // can be used to restrict a mock handler to being used only when a certain // set of data is passed to it. function isMockDataEqual( mock, live ) { var identical = false; // Test for situations where the data is a querystring (not an object) if (typeof live === 'string') { // Querystring may be a regex return $.isFunction( mock.test ) ? mock.test(live) : mock == live; } $.each(mock, function(k, v) { if ( live[k] === undefined ) { identical = false; return identical; } else { identical = true; if ( typeof live[k] == 'object' ) { return isMockDataEqual(mock[k], live[k]); } else { if ( $.isFunction( mock[k].test ) ) { identical = mock[k].test(live[k]); } else { identical = ( mock[k] == live[k] ); } return identical; } } }); return identical; } // Check the given handler should mock the given request function getMockForRequest( handler, requestSettings ) { // If the mock was registered with a function, let the function decide if we // want to mock this request if ( $.isFunction(handler) ) { return handler( requestSettings ); } // Inspect the URL of the request and check if the mock handler's url // matches the url for this ajax request if ( $.isFunction(handler.url.test) ) { // The user provided a regex for the url, test it if ( !handler.url.test( requestSettings.url ) ) { return null; } } else { // Look for a simple wildcard '*' or a direct URL match var star = handler.url.indexOf('*'); if (handler.url !== requestSettings.url && star === -1 || !new RegExp(handler.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace('*', '.+')).test(requestSettings.url)) { return null; } } // Inspect the data submitted in the request (either POST body or GET query string) if ( handler.data && requestSettings.data ) { if ( !isMockDataEqual(handler.data, requestSettings.data) ) { // They're not identical, do not mock this request return null; } } // Inspect the request type if ( handler && handler.type && handler.type.toLowerCase() != requestSettings.type.toLowerCase() ) { // The request type doesn't match (GET vs. POST) return null; } return handler; } // If logging is enabled, log the mock to the console function logMock( mockHandler, requestSettings ) { var c = $.extend({}, $.mockjaxSettings, mockHandler); if ( c.log && $.isFunction(c.log) ) { c.log('MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url, $.extend({}, requestSettings)); } } // Process the xhr objects send operation function _xhrSend(mockHandler, requestSettings, origSettings) { // This is a substitute for < 1.4 which lacks $.proxy var process = (function(that) { return function() { return (function() { // The request has returned this.status = mockHandler.status; this.statusText = mockHandler.statusText; this.readyState = 4; // We have an executable function, call it to give // the mock handler a chance to update it's data if ( $.isFunction(mockHandler.response) ) { mockHandler.response(origSettings); } // Copy over our mock to our xhr object before passing control back to // jQuery's onreadystatechange callback if ( requestSettings.dataType == 'json' && ( typeof mockHandler.responseText == 'object' ) ) { this.responseText = JSON.stringify(mockHandler.responseText); } else if ( requestSettings.dataType == 'xml' ) { if ( typeof mockHandler.responseXML == 'string' ) { this.responseXML = parseXML(mockHandler.responseXML); } else { this.responseXML = mockHandler.responseXML; } } else { this.responseText = mockHandler.responseText; } if( typeof mockHandler.status == 'number' || typeof mockHandler.status == 'string' ) { this.status = mockHandler.status; } if( typeof mockHandler.statusText === "string") { this.statusText = mockHandler.statusText; } // jQuery < 1.4 doesn't have onreadystate change for xhr if ( $.isFunction(this.onreadystatechange) ) { if( mockHandler.isTimeout) { this.status = -1; } this.onreadystatechange( mockHandler.isTimeout ? 'timeout' : undefined ); } else if ( mockHandler.isTimeout ) { // Fix for 1.3.2 timeout to keep success from firing. this.status = -1; } }).apply(that); }; })(this); if ( mockHandler.proxy ) { // We're proxying this request and loading in an external file instead _ajax({ global: false, url: mockHandler.proxy, type: mockHandler.proxyType, data: mockHandler.data, dataType: requestSettings.dataType === "script" ? "text/plain" : requestSettings.dataType, complete: function(xhr, txt) { mockHandler.responseXML = xhr.responseXML; mockHandler.responseText = xhr.responseText; mockHandler.status = xhr.status; mockHandler.statusText = xhr.statusText; this.responseTimer = setTimeout(process, mockHandler.responseTime || 0); } }); } else { // type == 'POST' || 'GET' || 'DELETE' if ( requestSettings.async === false ) { // TODO: Blocking delay process(); } else { this.responseTimer = setTimeout(process, mockHandler.responseTime || 50); } } } // Construct a mocked XHR Object function xhr(mockHandler, requestSettings, origSettings, origHandler) { // Extend with our default mockjax settings mockHandler = $.extend({}, $.mockjaxSettings, mockHandler); if (typeof mockHandler.headers === 'undefined') { mockHandler.headers = {}; } if ( mockHandler.contentType ) { mockHandler.headers['content-type'] = mockHandler.contentType; } return { status: mockHandler.status, statusText: mockHandler.statusText, readyState: 1, open: function() { }, send: function() { origHandler.fired = true; _xhrSend.call(this, mockHandler, requestSettings, origSettings); }, abort: function() { clearTimeout(this.responseTimer); }, setRequestHeader: function(header, value) { mockHandler.headers[header] = value; }, getResponseHeader: function(header) { // 'Last-modified', 'Etag', 'content-type' are all checked by jQuery if ( mockHandler.headers && mockHandler.headers[header] ) { // Return arbitrary headers return mockHandler.headers[header]; } else if ( header.toLowerCase() == 'last-modified' ) { return mockHandler.lastModified || (new Date()).toString(); } else if ( header.toLowerCase() == 'etag' ) { return mockHandler.etag || ''; } else if ( header.toLowerCase() == 'content-type' ) { return mockHandler.contentType || 'text/plain'; } }, getAllResponseHeaders: function() { var headers = ''; $.each(mockHandler.headers, function(k, v) { headers += k + ': ' + v + "\n"; }); return headers; } }; } // Process a JSONP mock request. function processJsonpMock( requestSettings, mockHandler, origSettings ) { // Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here // because there isn't an easy hook for the cross domain script tag of jsonp processJsonpUrl( requestSettings ); requestSettings.dataType = "json"; if(requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) { createJsonpCallback(requestSettings, mockHandler); // We need to make sure // that a JSONP style response is executed properly var rurl = /^(\w+:)?\/\/([^\/?#]+)/, parts = rurl.exec( requestSettings.url ), remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host); requestSettings.dataType = "script"; if(requestSettings.type.toUpperCase() === "GET" && remote ) { var newMockReturn = processJsonpRequest( requestSettings, mockHandler, origSettings ); // Check if we are supposed to return a Deferred back to the mock call, or just // signal success if(newMockReturn) { return newMockReturn; } else { return true; } } } return null; } // Append the required callback parameter to the end of the request URL, for a JSONP request function processJsonpUrl( requestSettings ) { if ( requestSettings.type.toUpperCase() === "GET" ) { if ( !CALLBACK_REGEX.test( requestSettings.url ) ) { requestSettings.url += (/\?/.test( requestSettings.url ) ? "&" : "?") + (requestSettings.jsonp || "callback") + "=?"; } } else if ( !requestSettings.data || !CALLBACK_REGEX.test(requestSettings.data) ) { requestSettings.data = (requestSettings.data ? requestSettings.data + "&" : "") + (requestSettings.jsonp || "callback") + "=?"; } } // Process a JSONP request by evaluating the mocked response text function processJsonpRequest( requestSettings, mockHandler, origSettings ) { // Synthesize the mock request for adding a script tag var callbackContext = origSettings && origSettings.context || requestSettings, newMock = null; // If the response handler on the moock is a function, call it if ( mockHandler.response && $.isFunction(mockHandler.response) ) { mockHandler.response(origSettings); } else { // Evaluate the responseText javascript in a global context if( typeof mockHandler.responseText === 'object' ) { $.globalEval( '(' + JSON.stringify( mockHandler.responseText ) + ')'); } else { $.globalEval( '(' + mockHandler.responseText + ')'); } } // Successful response jsonpSuccess( requestSettings, mockHandler ); jsonpComplete( requestSettings, mockHandler ); // If we are running under jQuery 1.5+, return a deferred object if(jQuery.Deferred){ newMock = new jQuery.Deferred(); if(typeof mockHandler.responseText == "object"){ newMock.resolve( mockHandler.responseText ); } else{ newMock.resolve( jQuery.parseJSON( mockHandler.responseText ) ); } } return newMock; } // Create the required JSONP callback function for the request function createJsonpCallback( requestSettings, mockHandler ) { jsonp = requestSettings.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if ( requestSettings.data ) { requestSettings.data = (requestSettings.data + "").replace(CALLBACK_REGEX, "=" + jsonp + "$1"); } requestSettings.url = requestSettings.url.replace(CALLBACK_REGEX, "=" + jsonp + "$1"); // Handle JSONP-style loading window[ jsonp ] = window[ jsonp ] || function( tmp ) { data = tmp; jsonpSuccess( requestSettings, mockHandler ); jsonpComplete( requestSettings, mockHandler ); // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch(e) {} if ( head ) { head.removeChild( script ); } }; } // The JSONP request was successful function jsonpSuccess(requestSettings, mockHandler) { // If a local callback was specified, fire it and pass it the data if ( requestSettings.success ) { requestSettings.success.call( callbackContext, ( mockHandler.response ? mockHandler.response.toString() : mockHandler.responseText || ''), status, {} ); } // Fire the global callback if ( requestSettings.global ) { trigger(requestSettings, "ajaxSuccess", [{}, requestSettings] ); } } // The JSONP request was completed function jsonpComplete(requestSettings, mockHandler) { // Process result if ( requestSettings.complete ) { requestSettings.complete.call( callbackContext, {} , status ); } // The request was completed if ( requestSettings.global ) { trigger( "ajaxComplete", [{}, requestSettings] ); } // Handle the global AJAX counter if ( requestSettings.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } } // The core $.ajax replacement. function handleAjax( url, origSettings ) { var mockRequest, requestSettings, mockHandler; // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { origSettings = url; url = undefined; } else { // work around to support 1.5 signature origSettings.url = url; } // Extend the original settings for the request requestSettings = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings); // Iterate over our mock handlers (in registration order) until we find // one that is willing to intercept the request for(var k = 0; k < mockHandlers.length; k++) { if ( !mockHandlers[k] ) { continue; } mockHandler = getMockForRequest( mockHandlers[k], requestSettings ); if(!mockHandler) { // No valid mock found for this request continue; } // Handle console logging logMock( mockHandler, requestSettings ); if ( requestSettings.dataType === "jsonp" ) { if ((mockRequest = processJsonpMock( requestSettings, mockHandler, origSettings ))) { // This mock will handle the JSONP request return mockRequest; } } // Removed to fix #54 - keep the mocking data object intact //mockHandler.data = requestSettings.data; mockHandler.cache = requestSettings.cache; mockHandler.timeout = requestSettings.timeout; mockHandler.global = requestSettings.global; (function(mockHandler, requestSettings, origSettings, origHandler) { mockRequest = _ajax.call($, $.extend(true, {}, origSettings, { // Mock the XHR object xhr: function() { return xhr( mockHandler, requestSettings, origSettings, origHandler ) } })); })(mockHandler, requestSettings, origSettings, mockHandlers[k]); return mockRequest; } // We don't have a mock request, trigger a normal request return _ajax.apply($, [origSettings]); } // Public $.extend({ ajax: handleAjax }); $.mockjaxSettings = { //url: null, //type: 'GET', log: function(msg) { window['console'] && window.console.log && window.console.log(msg); }, status: 200, statusText: "OK", responseTime: 500, isTimeout: false, contentType: 'text/plain', response: '', responseText: '', responseXML: '', proxy: '', proxyType: 'GET', lastModified: null, etag: '', headers: { etag: 'IJF@H#@923uf8023hFO@I#H#', 'content-type' : 'text/plain' } }; $.mockjax = function(settings) { var i = mockHandlers.length; mockHandlers[i] = settings; return i; }; $.mockjaxClear = function(i) { if ( arguments.length == 1 ) { mockHandlers[i] = null; } else { mockHandlers = []; } }; $.mockjax.handler = function(i) { if ( arguments.length == 1 ) { return mockHandlers[i]; } }; })(jQuery);
JavaScript
(function() { var AjaxMonitor, Bar, DocumentMonitor, ElementMonitor, ElementTracker, EventLagMonitor, Evented, Events, NoTargetError, RequestIntercept, SOURCE_KEYS, Scaler, SocketRequestTracker, XHRRequestTracker, animation, avgAmplitude, bar, cancelAnimation, cancelAnimationFrame, defaultOptions, extend, extendNative, getFromDOM, getIntercept, handlePushState, ignoreStack, init, now, options, requestAnimationFrame, result, runAnimation, scalers, shouldTrack, source, sources, uniScaler, _WebSocket, _XDomainRequest, _XMLHttpRequest, _i, _intercept, _len, _pushState, _ref, _ref1, _replaceState, __slice = [].slice, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; defaultOptions = { catchupTime: 500, initialRate: .03, minTime: 500, ghostTime: 500, maxProgressPerFrame: 10, easeFactor: 1.25, startOnPageLoad: true, restartOnPushState: true, restartOnRequestAfter: 500, target: 'body', elements: { checkInterval: 100, selectors: ['body'] }, eventLag: { minSamples: 10, sampleCount: 3, lagThreshold: 3 }, ajax: { trackMethods: ['GET'], trackWebSockets: false } }; now = function() { var _ref; return (_ref = typeof performance !== "undefined" && performance !== null ? typeof performance.now === "function" ? performance.now() : void 0 : void 0) != null ? _ref : +(new Date); }; requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame; if (requestAnimationFrame == null) { requestAnimationFrame = function(fn) { return setTimeout(fn, 50); }; cancelAnimationFrame = function(id) { return clearTimeout(id); }; } runAnimation = function(fn) { var last, tick; last = now(); tick = function() { var diff; diff = now() - last; if (diff >= 33) { last = now(); return fn(diff, function() { return requestAnimationFrame(tick); }); } else { return setTimeout(tick, 33 - diff); } }; return tick(); }; result = function() { var args, key, obj; obj = arguments[0], key = arguments[1], args = 3 <= arguments.length ? __slice.call(arguments, 2) : []; if (typeof obj[key] === 'function') { return obj[key].apply(obj, args); } else { return obj[key]; } }; extend = function() { var key, out, source, sources, val, _i, _len; out = arguments[0], sources = 2 <= arguments.length ? __slice.call(arguments, 1) : []; for (_i = 0, _len = sources.length; _i < _len; _i++) { source = sources[_i]; if (source) { for (key in source) { if (!__hasProp.call(source, key)) continue; val = source[key]; if ((out[key] != null) && typeof out[key] === 'object' && (val != null) && typeof val === 'object') { extend(out[key], val); } else { out[key] = val; } } } } return out; }; avgAmplitude = function(arr) { var count, sum, v, _i, _len; sum = count = 0; for (_i = 0, _len = arr.length; _i < _len; _i++) { v = arr[_i]; sum += Math.abs(v); count++; } return sum / count; }; getFromDOM = function(key, json) { var data, e, el; if (key == null) { key = 'options'; } if (json == null) { json = true; } el = document.querySelector("[data-pace-" + key + "]"); if (!el) { return; } data = el.getAttribute("data-pace-" + key); if (!json) { return data; } try { return JSON.parse(data); } catch (_error) { e = _error; return typeof console !== "undefined" && console !== null ? console.error("Error parsing inline pace options", e) : void 0; } }; Evented = (function() { function Evented() {} Evented.prototype.on = function(event, handler, ctx, once) { var _base; if (once == null) { once = false; } if (this.bindings == null) { this.bindings = {}; } if ((_base = this.bindings)[event] == null) { _base[event] = []; } return this.bindings[event].push({ handler: handler, ctx: ctx, once: once }); }; Evented.prototype.once = function(event, handler, ctx) { return this.on(event, handler, ctx, true); }; Evented.prototype.off = function(event, handler) { var i, _ref, _results; if (((_ref = this.bindings) != null ? _ref[event] : void 0) == null) { return; } if (handler == null) { return delete this.bindings[event]; } else { i = 0; _results = []; while (i < this.bindings[event].length) { if (this.bindings[event][i].handler === handler) { _results.push(this.bindings[event].splice(i, 1)); } else { _results.push(i++); } } return _results; } }; Evented.prototype.trigger = function() { var args, ctx, event, handler, i, once, _ref, _ref1, _results; event = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; if ((_ref = this.bindings) != null ? _ref[event] : void 0) { i = 0; _results = []; while (i < this.bindings[event].length) { _ref1 = this.bindings[event][i], handler = _ref1.handler, ctx = _ref1.ctx, once = _ref1.once; handler.apply(ctx != null ? ctx : this, args); if (once) { _results.push(this.bindings[event].splice(i, 1)); } else { _results.push(i++); } } return _results; } }; return Evented; })(); if (window.Pace == null) { window.Pace = {}; } extend(Pace, Evented.prototype); options = Pace.options = extend({}, defaultOptions, window.paceOptions, getFromDOM()); _ref = ['ajax', 'document', 'eventLag', 'elements']; for (_i = 0, _len = _ref.length; _i < _len; _i++) { source = _ref[_i]; if (options[source] === true) { options[source] = defaultOptions[source]; } } NoTargetError = (function(_super) { __extends(NoTargetError, _super); function NoTargetError() { _ref1 = NoTargetError.__super__.constructor.apply(this, arguments); return _ref1; } return NoTargetError; })(Error); Bar = (function() { function Bar() { this.progress = 0; } Bar.prototype.getElement = function() { var targetElement; if (this.el == null) { targetElement = document.querySelector(options.target); if (!targetElement) { throw new NoTargetError; } this.el = document.createElement('div'); this.el.className = "pace pace-active"; document.body.className = document.body.className.replace('pace-done', ''); document.body.className += ' pace-running'; this.el.innerHTML = '<div class="pace-progress">\n <div class="pace-progress-inner"></div>\n</div>\n<div class="pace-activity"></div>'; if (targetElement.firstChild != null) { targetElement.insertBefore(this.el, targetElement.firstChild); } else { targetElement.appendChild(this.el); } } return this.el; }; Bar.prototype.finish = function() { var el; el = this.getElement(); el.className = el.className.replace('pace-active', ''); el.className += ' pace-inactive'; document.body.className = document.body.className.replace('pace-running', ''); return document.body.className += ' pace-done'; }; Bar.prototype.update = function(prog) { this.progress = prog; return this.render(); }; Bar.prototype.destroy = function() { try { this.getElement().parentNode.removeChild(this.getElement()); } catch (_error) { NoTargetError = _error; } return this.el = void 0; }; Bar.prototype.render = function() { var el, progressStr; if (document.querySelector(options.target) == null) { return false; } el = this.getElement(); el.children[0].style.width = "" + this.progress + "%"; if (!this.lastRenderedProgress || this.lastRenderedProgress | 0 !== this.progress | 0) { el.children[0].setAttribute('data-progress-text', "" + (this.progress | 0) + "%"); if (this.progress >= 100) { progressStr = '99'; } else { progressStr = this.progress < 10 ? "0" : ""; progressStr += this.progress | 0; } el.children[0].setAttribute('data-progress', "" + progressStr); } return this.lastRenderedProgress = this.progress; }; Bar.prototype.done = function() { return this.progress >= 100; }; return Bar; })(); Events = (function() { function Events() { this.bindings = {}; } Events.prototype.trigger = function(name, val) { var binding, _j, _len1, _ref2, _results; if (this.bindings[name] != null) { _ref2 = this.bindings[name]; _results = []; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { binding = _ref2[_j]; _results.push(binding.call(this, val)); } return _results; } }; Events.prototype.on = function(name, fn) { var _base; if ((_base = this.bindings)[name] == null) { _base[name] = []; } return this.bindings[name].push(fn); }; return Events; })(); _XMLHttpRequest = window.XMLHttpRequest; _XDomainRequest = window.XDomainRequest; _WebSocket = window.WebSocket; extendNative = function(to, from) { var e, key, val, _results; _results = []; for (key in from.prototype) { try { val = from.prototype[key]; if ((to[key] == null) && typeof val !== 'function') { _results.push(to[key] = val); } else { _results.push(void 0); } } catch (_error) { e = _error; } } return _results; }; ignoreStack = []; Pace.ignore = function() { var args, fn, ret; fn = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; ignoreStack.unshift('ignore'); ret = fn.apply(null, args); ignoreStack.shift(); return ret; }; Pace.track = function() { var args, fn, ret; fn = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; ignoreStack.unshift('track'); ret = fn.apply(null, args); ignoreStack.shift(); return ret; }; shouldTrack = function(method) { var _ref2; if (method == null) { method = 'GET'; } if (ignoreStack[0] === 'track') { return 'force'; } if (!ignoreStack.length && options.ajax) { if (method === 'socket' && options.ajax.trackWebSockets) { return true; } else if (_ref2 = method.toUpperCase(), __indexOf.call(options.ajax.trackMethods, _ref2) >= 0) { return true; } } return false; }; RequestIntercept = (function(_super) { __extends(RequestIntercept, _super); function RequestIntercept() { var monitorXHR, _this = this; RequestIntercept.__super__.constructor.apply(this, arguments); monitorXHR = function(req) { var _open; _open = req.open; return req.open = function(type, url, async) { if (shouldTrack(type)) { _this.trigger('request', { type: type, url: url, request: req }); } return _open.apply(req, arguments); }; }; window.XMLHttpRequest = function(flags) { var req; req = new _XMLHttpRequest(flags); monitorXHR(req); return req; }; extendNative(window.XMLHttpRequest, _XMLHttpRequest); if (_XDomainRequest != null) { window.XDomainRequest = function() { var req; req = new _XDomainRequest; monitorXHR(req); return req; }; extendNative(window.XDomainRequest, _XDomainRequest); } if ((_WebSocket != null) && options.ajax.trackWebSockets) { window.WebSocket = function(url, protocols) { var req; req = new _WebSocket(url, protocols); if (shouldTrack('socket')) { _this.trigger('request', { type: 'socket', url: url, protocols: protocols, request: req }); } return req; }; extendNative(window.WebSocket, _WebSocket); } } return RequestIntercept; })(Events); _intercept = null; getIntercept = function() { if (_intercept == null) { _intercept = new RequestIntercept; } return _intercept; }; getIntercept().on('request', function(_arg) { var after, args, request, type; type = _arg.type, request = _arg.request; if (!Pace.running && (options.restartOnRequestAfter !== false || shouldTrack(type) === 'force')) { args = arguments; after = options.restartOnRequestAfter || 0; if (typeof after === 'boolean') { after = 0; } return setTimeout(function() { var stillActive, _j, _len1, _ref2, _ref3, _results; if (type === 'socket') { stillActive = request.readyState < 2; } else { stillActive = (0 < (_ref2 = request.readyState) && _ref2 < 4); } if (stillActive) { Pace.restart(); _ref3 = Pace.sources; _results = []; for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { source = _ref3[_j]; if (source instanceof AjaxMonitor) { source.watch.apply(source, args); break; } else { _results.push(void 0); } } return _results; } }, after); } }); AjaxMonitor = (function() { function AjaxMonitor() { var _this = this; this.elements = []; getIntercept().on('request', function() { return _this.watch.apply(_this, arguments); }); } AjaxMonitor.prototype.watch = function(_arg) { var request, tracker, type; type = _arg.type, request = _arg.request; if (type === 'socket') { tracker = new SocketRequestTracker(request); } else { tracker = new XHRRequestTracker(request); } return this.elements.push(tracker); }; return AjaxMonitor; })(); XHRRequestTracker = (function() { function XHRRequestTracker(request) { var event, size, _j, _len1, _onreadystatechange, _ref2, _this = this; this.progress = 0; if (window.ProgressEvent != null) { size = null; request.addEventListener('progress', function(evt) { if (evt.lengthComputable) { return _this.progress = 100 * evt.loaded / evt.total; } else { return _this.progress = _this.progress + (100 - _this.progress) / 2; } }); _ref2 = ['load', 'abort', 'timeout', 'error']; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { event = _ref2[_j]; request.addEventListener(event, function() { return _this.progress = 100; }); } } else { _onreadystatechange = request.onreadystatechange; request.onreadystatechange = function() { var _ref3; if ((_ref3 = request.readyState) === 0 || _ref3 === 4) { _this.progress = 100; } else if (request.readyState === 3) { _this.progress = 50; } return typeof _onreadystatechange === "function" ? _onreadystatechange.apply(null, arguments) : void 0; }; } } return XHRRequestTracker; })(); SocketRequestTracker = (function() { function SocketRequestTracker(request) { var event, _j, _len1, _ref2, _this = this; this.progress = 0; _ref2 = ['error', 'open']; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { event = _ref2[_j]; request.addEventListener(event, function() { return _this.progress = 100; }); } } return SocketRequestTracker; })(); ElementMonitor = (function() { function ElementMonitor(options) { var selector, _j, _len1, _ref2; if (options == null) { options = {}; } this.elements = []; if (options.selectors == null) { options.selectors = []; } _ref2 = options.selectors; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { selector = _ref2[_j]; this.elements.push(new ElementTracker(selector)); } } return ElementMonitor; })(); ElementTracker = (function() { function ElementTracker(selector) { this.selector = selector; this.progress = 0; this.check(); } ElementTracker.prototype.check = function() { var _this = this; if (document.querySelector(this.selector)) { return this.done(); } else { return setTimeout((function() { return _this.check(); }), options.elements.checkInterval); } }; ElementTracker.prototype.done = function() { return this.progress = 100; }; return ElementTracker; })(); DocumentMonitor = (function() { DocumentMonitor.prototype.states = { loading: 0, interactive: 50, complete: 100 }; function DocumentMonitor() { var _onreadystatechange, _ref2, _this = this; this.progress = (_ref2 = this.states[document.readyState]) != null ? _ref2 : 100; _onreadystatechange = document.onreadystatechange; document.onreadystatechange = function() { if (_this.states[document.readyState] != null) { _this.progress = _this.states[document.readyState]; } return typeof _onreadystatechange === "function" ? _onreadystatechange.apply(null, arguments) : void 0; }; } return DocumentMonitor; })(); EventLagMonitor = (function() { function EventLagMonitor() { var avg, interval, last, points, samples, _this = this; this.progress = 0; avg = 0; samples = []; points = 0; last = now(); interval = setInterval(function() { var diff; diff = now() - last - 50; last = now(); samples.push(diff); if (samples.length > options.eventLag.sampleCount) { samples.shift(); } avg = avgAmplitude(samples); if (++points >= options.eventLag.minSamples && avg < options.eventLag.lagThreshold) { _this.progress = 100; return clearInterval(interval); } else { return _this.progress = 100 * (3 / (avg + 3)); } }, 50); } return EventLagMonitor; })(); Scaler = (function() { function Scaler(source) { this.source = source; this.last = this.sinceLastUpdate = 0; this.rate = options.initialRate; this.catchup = 0; this.progress = this.lastProgress = 0; if (this.source != null) { this.progress = result(this.source, 'progress'); } } Scaler.prototype.tick = function(frameTime, val) { var scaling; if (val == null) { val = result(this.source, 'progress'); } if (val >= 100) { this.done = true; } if (val === this.last) { this.sinceLastUpdate += frameTime; } else { if (this.sinceLastUpdate) { this.rate = (val - this.last) / this.sinceLastUpdate; } this.catchup = (val - this.progress) / options.catchupTime; this.sinceLastUpdate = 0; this.last = val; } if (val > this.progress) { this.progress += this.catchup * frameTime; } scaling = 1 - Math.pow(this.progress / 100, options.easeFactor); this.progress += scaling * this.rate * frameTime; this.progress = Math.min(this.lastProgress + options.maxProgressPerFrame, this.progress); this.progress = Math.max(0, this.progress); this.progress = Math.min(100, this.progress); this.lastProgress = this.progress; return this.progress; }; return Scaler; })(); sources = null; scalers = null; bar = null; uniScaler = null; animation = null; cancelAnimation = null; Pace.running = false; handlePushState = function() { if (options.restartOnPushState) { return Pace.restart(); } }; if (window.history.pushState != null) { _pushState = window.history.pushState; window.history.pushState = function() { handlePushState(); return _pushState.apply(window.history, arguments); }; } if (window.history.replaceState != null) { _replaceState = window.history.replaceState; window.history.replaceState = function() { handlePushState(); return _replaceState.apply(window.history, arguments); }; } SOURCE_KEYS = { ajax: AjaxMonitor, elements: ElementMonitor, document: DocumentMonitor, eventLag: EventLagMonitor }; (init = function() { var type, _j, _k, _len1, _len2, _ref2, _ref3, _ref4; Pace.sources = sources = []; _ref2 = ['ajax', 'elements', 'document', 'eventLag']; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { type = _ref2[_j]; if (options[type] !== false) { sources.push(new SOURCE_KEYS[type](options[type])); } } _ref4 = (_ref3 = options.extraSources) != null ? _ref3 : []; for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) { source = _ref4[_k]; sources.push(new source(options)); } Pace.bar = bar = new Bar; scalers = []; return uniScaler = new Scaler; })(); Pace.stop = function() { Pace.trigger('stop'); Pace.running = false; bar.destroy(); cancelAnimation = true; if (animation != null) { if (typeof cancelAnimationFrame === "function") { cancelAnimationFrame(animation); } animation = null; } return init(); }; Pace.restart = function() { Pace.trigger('restart'); Pace.stop(); return Pace.start(); }; Pace.go = function() { Pace.running = true; bar.render(); cancelAnimation = false; return animation = runAnimation(function(frameTime, enqueueNextFrame) { var avg, count, done, element, elements, i, j, remaining, scaler, scalerList, start, sum, _j, _k, _len1, _len2, _ref2; remaining = 100 - bar.progress; count = sum = 0; done = true; for (i = _j = 0, _len1 = sources.length; _j < _len1; i = ++_j) { source = sources[i]; scalerList = scalers[i] != null ? scalers[i] : scalers[i] = []; elements = (_ref2 = source.elements) != null ? _ref2 : [source]; for (j = _k = 0, _len2 = elements.length; _k < _len2; j = ++_k) { element = elements[j]; scaler = scalerList[j] != null ? scalerList[j] : scalerList[j] = new Scaler(element); done &= scaler.done; if (scaler.done) { continue; } count++; sum += scaler.tick(frameTime); } } avg = sum / count; bar.update(uniScaler.tick(frameTime, avg)); start = now(); if (bar.done() || done || cancelAnimation) { bar.update(100); Pace.trigger('done'); return setTimeout(function() { bar.finish(); Pace.running = false; return Pace.trigger('hide'); }, Math.max(options.ghostTime, Math.min(options.minTime, now() - start))); } else { return enqueueNextFrame(); } }); }; Pace.start = function(_options) { extend(options, _options); Pace.running = true; try { bar.render(); } catch (_error) { NoTargetError = _error; } if (!document.querySelector('.pace')) { return setTimeout(Pace.start, 50); } else { Pace.trigger('start'); return Pace.go(); } }; if (typeof define === 'function' && define.amd) { define(function() { return Pace; }); } else if (typeof exports === 'object') { module.exports = Pace; } else { if (options.startOnPageLoad) { Pace.start(); } } }).call(this);
JavaScript
/** * Clockface - v1.0.0 * Clockface timepicker for Twitter Bootstrap * * Confusion with noon and midnight: * http://en.wikipedia.org/wiki/12-hour_clock * Here considered '00:00 am' as midnight and '12:00 pm' as noon. * * Author: Vitaliy Potapov * Project page: http://github.com/vitalets/clockface * Copyright (c) 2012 Vitaliy Potapov. Released under MIT License. **/ (function ($) { var Clockface = function (element, options) { this.$element = $(element); this.options = $.extend({}, $.fn.clockface.defaults, options, this.$element.data()); this.init(); }; Clockface.prototype = { constructor: Clockface, init: function () { //apply template this.$clockface = $($.fn.clockface.template); this.$clockface.find('.l1 .cell, .left.cell').html('<div class="outer"></div><div class="inner"></div>'); this.$clockface.find('.l5 .cell, .right.cell').html('<div class="inner"></div><div class="outer"></div>'); this.$clockface.hide(); this.$outer = this.$clockface.find('.outer'); this.$inner = this.$clockface.find('.inner'); this.$ampm = this.$clockface.find('.ampm'); //internal vars this.ampm = null; this.hour = null; this.minute = null; //click am/pm this.$ampm.click($.proxy(this.clickAmPm, this)); //click cell this.$clockface.on('click', '.cell', $.proxy(this.click, this)); this.parseFormat(); this.prepareRegexp(); //set ampm text this.ampmtext = this.is24 ? {am: '12-23', pm: '0-11'} : {am: 'AM', pm: 'PM'}; this.isInline = this.$element.is('div'); if(this.isInline) { this.$clockface.addClass('clockface-inline').appendTo(this.$element); } else { this.$clockface.addClass('dropdown-menu').appendTo('body'); if(this.options.trigger === 'focus') { this.$element.on('focus.clockface', $.proxy(function(e) { this.show(); }, this)); } // Click outside hide it. Register single handler for all clockface widgets $(document).off('click.clockface').on('click.clockface', $.proxy(function (e) { var $target = $(e.target); //click inside some clockface --> do nothing if ($target.closest('.clockface').length) { return; } //iterate all open clockface and close all except current $('.clockface-open').each(function(){ if(this === e.target) { return; } $(this).clockface('hide'); }); }, this)); } //fill minutes once this.fill('minute'); }, /* Displays widget with specified value */ show: function(value) { if(this.$clockface.is(':visible')) { return; } if(!this.isInline) { if(value === undefined) { value = this.$element.val(); } this.$element.addClass('clockface-open'); this.$element.on('keydown.clockface', $.proxy(this.keydown, this)); this.place(); $(window).on('resize.clockface', $.proxy(this.place, this)); } this.$clockface.show(); this.setTime(value); //trigger shown event this.$element.triggerHandler('shown.clockface', this.getTime(true)); }, /* hides widget */ hide: function() { this.$clockface.hide(); if(!this.isInline) { this.$element.removeClass('clockface-open'); this.$element.off('keydown.clockface'); $(window).off('resize.clockface'); } //trigger hidden event this.$element.triggerHandler('hidden.clockface', this.getTime(true)); }, /* toggles show/hide */ toggle: function(value) { if(this.$clockface.is(':visible')) { this.hide(); } else { this.show(value); } }, /* Set time of clockface. Am/pm will be set automatically. Value can be Date object or string */ setTime: function(value) { var res, hour, minute, ampm = 'am'; //no new value if(value === undefined) { //if ampm null, it;s first showw, need to render hours ('am' by default) if(this.ampm === null) { this.setAmPm('am'); } return; } //take value from Date object if(value instanceof Date) { hour = value.getHours(); minute = value.getMinutes(); } //parse value from string if(typeof value === 'string' && value.length) { res = this.parseTime(value); //'24' always '0' if(res.hour === 24) { res.hour = 0; } hour = res.hour; minute = res.minute; ampm = res.ampm; } //try to set ampm automatically if(hour > 11 && hour < 24) { ampm = 'pm'; //for 12h format substract 12 from value if(!this.is24 && hour > 12) { hour -= 12; } } else if(hour >= 0 && hour < 11) { //always set am for 24h and for '0' in 12h if(this.is24 || hour === 0) { ampm = 'am'; } //otherwise ampm should be defined in value itself and retrieved when parsing } this.setAmPm(ampm); this.setHour(hour); this.setMinute(minute); }, /* Set ampm and re-fill hours */ setAmPm: function(value) { if(value === this.ampm) { return; } else { this.ampm = value === 'am' ? 'am' : 'pm'; } //set link's text this.$ampm.text(this.ampmtext[this.ampm]); //re-fill and highlight hour this.fill('hour'); this.highlight('hour'); }, /* Sets hour value and highlight if possible */ setHour: function(value) { value = parseInt(value, 10); value = isNaN(value) ? null : value; if(value < 0 || value > 23) { value = null; } if(value === this.hour) { return; } else { this.hour = value; } this.highlight('hour'); }, /* Sets minute value and highlight */ setMinute: function(value) { value = parseInt(value, 10); value = isNaN(value) ? null : value; if(value < 0 || value > 59) { value = null; } if(value === this.minute) { return; } else { this.minute = value; } this.highlight('minute'); }, /* Highlights hour/minute */ highlight: function(what) { var index, values = this.getValues(what), value = what === 'minute' ? this.minute : this.hour, $cells = what === 'minute' ? this.$outer : this.$inner; $cells.removeClass('active'); //find index of value and highlight if possible index = $.inArray(value, values); if(index >= 0) { $cells.eq(index).addClass('active'); } }, /* Fill values around */ fill: function(what) { var values = this.getValues(what), $cells = what === 'minute' ? this.$outer : this.$inner, leadZero = what === 'minute'; $cells.each(function(i){ var v = values[i]; if(leadZero && v < 10) { v = '0' + v; } $(this).text(v); }); }, /* returns values of hours or minutes, depend on ampm and 24/12 format (0-11, 12-23, 00-55, etc) param what: 'hour'/'minute' */ getValues: function(what) { var values = [11, 0, 1, 10, 2, 9, 3, 8, 4, 7, 6, 5], result = []; if(what === 'minute') { $.each(values, function(i, v) { result[i] = v*5; }); } else if(this.ampm === 'pm') { if(this.is24) { $.each(values, function(i, v) { result[i] = v+12; }); } else { result = values.slice(); result[1] = 12; //need this to show '12' instead of '0' for 12h pm } } else { result = values.slice(); } return result; }, /* Click cell handler. Stores hour/minute and highlights. On second click deselect value */ click: function(e) { var $target = $(e.target), value = $target.hasClass('active') ? null : $target.text(); if($target.hasClass('inner')) { this.setHour(value); } else { this.setMinute(value); } //update value in input if(!this.isInline) { this.$element.val(this.getTime()); } //trigger pick event this.$element.triggerHandler('pick.clockface', this.getTime(true)); }, /* Click handler on ampm link */ clickAmPm: function(e) { e.preventDefault(); //toggle am/pm this.setAmPm(this.ampm === 'am' ? 'pm' : 'am'); //update value in input if(!this.isInline && !this.is24) { this.$element.val(this.getTime()); } //trigger pick event this.$element.triggerHandler('pick.clockface', this.getTime(true)); }, /* Place widget below input */ place: function(){ var zIndex = parseInt(this.$element.parents().filter(function() { return $(this).css('z-index') != 'auto'; }).first().css('z-index'), 10)+10, offset = this.$element.offset(); this.$clockface.css({ top: offset.top + this.$element.outerHeight(), left: offset.left, zIndex: zIndex }); }, /* keydown handler (for not inline mode) */ keydown: function(e) { //tab, escape, enter --> hide if(/^(9|27|13)$/.test(e.which)) { this.hide(); return; } clearTimeout(this.timer); this.timer = setTimeout($.proxy(function(){ this.setTime(this.$element.val()); }, this), 500); }, /* Parse format from options and set this.is24 */ parseFormat: function() { var format = this.options.format, hFormat = 'HH', mFormat = 'mm'; //hour format $.each(['HH', 'hh', 'H', 'h'], function(i, f){ if(format.indexOf(f) !== -1) { hFormat = f; return false; } }); //minute format $.each(['mm', 'm'], function(i, f){ if(format.indexOf(f) !== -1) { mFormat = f; return false; } }); //is 24 hour format this.is24 = hFormat.indexOf('H') !== -1; this.hFormat = hFormat; this.mFormat = mFormat; }, /* Parse value passed as string or Date object */ parseTime: function(value) { var hour = null, minute = null, ampm = 'am', parts = [], digits; value = $.trim(value); //try parse time from string assuming separator exist if(this.regexpSep) { parts = value.match(this.regexpSep); } if(parts && parts.length) { hour = parts[1] ? parseInt(parts[1], 10) : null; minute = parts[2] ? parseInt(parts[2], 10): null; ampm = (!parts[3] || parts[3].toLowerCase() === 'a') ? 'am' : 'pm'; } else { //if parse with separator failed, search for 1,4-digit block and process it //use reversed string to start from end (usefull with full dates) //see http://stackoverflow.com/questions/141348/what-is-the-best-way-to-parse-a-time-into-a-date-object-from-user-input-in-javas value = value.split('').reverse().join('').replace(/\s/g, ''); parts = value.match(this.regexpNoSep); if(parts && parts.length) { ampm = (!parts[1] || parts[1].toLowerCase() === 'a') ? 'am' : 'pm'; //reverse back digits = parts[2].split('').reverse().join(''); //use smart analyzing to detect hours and minutes switch(digits.length) { case 1: hour = parseInt(digits, 10); //e.g. '6' break; case 2: hour = parseInt(digits, 10); //e.g. '16' //if((this.is24 && hour > 24) || (!this.is24 && hour > 12)) { //e.g. 26 if(hour > 24) { //e.g. 26 hour = parseInt(digits[0], 10); minute = parseInt(digits[1], 10); } break; case 3: hour = parseInt(digits[0], 10); //e.g. 105 minute = parseInt(digits[1]+digits[2], 10); if(minute > 59) { hour = parseInt(digits[0]+digits[1], 10); //e.g. 195 minute = parseInt(digits[2], 10); if(hour > 24) { hour = null; minute = null; } } break; case 4: hour = parseInt(digits[0]+digits[1], 10); //e.g. 2006 minute = parseInt(digits[2]+digits[3], 10); if(hour > 24) { hour = null; } if(minute > 59) { minute = null; } } } } return {hour: hour, minute: minute, ampm: ampm}; }, prepareRegexp: function() { //take separator from format var sep = this.options.format.match(/h\s*([^hm]?)\s*m/i); //HH-mm, HH:mm if(sep && sep.length) { sep = sep[1]; } //sep can be null for HH, and '' for HHmm this.separator = sep; //parse from string //use reversed string and regexp to parse 2-digit minutes first //see http://stackoverflow.com/questions/141348/what-is-the-best-way-to-parse-a-time-into-a-date-object-from-user-input-in-javas //this.regexp = new RegExp('(a|p)?\\s*((\\d\\d?)' + sep + ')?(\\d\\d?)', 'i'); //regexp, used with separator this.regexpSep = (this.separator && this.separator.length) ? new RegExp('(\\d\\d?)\\s*\\' + this.separator + '\\s*(\\d?\\d?)\\s*(a|p)?', 'i') : null; //second regexp applied if previous has no result or separator is empty (to reversed string) this.regexpNoSep = new RegExp('(a|p)?\\s*(\\d{1,4})', 'i'); }, /* Returns time as string in specified format */ getTime: function(asObject) { if(asObject === true) { return { hour: this.hour, minute: this.minute, ampm: this.ampm }; } var hour = this.hour !== null ? this.hour + '' : '', minute = this.minute !== null ? this.minute + '' : '', result = this.options.format; if(!hour.length && !minute.length) { return ''; } if(this.hFormat.length > 1 && hour.length === 1) { hour = '0' + hour; } if(this.mFormat.length > 1 && minute.length === 1) { minute = '0' + minute; } //delete separator if no minutes if(!minute.length && this.separator) { result = result.replace(this.separator, ''); } result = result.replace(this.hFormat, hour).replace(this.mFormat, minute); if(!this.is24) { if(result.indexOf('A') !== -1) { result = result.replace('A', this.ampm.toUpperCase()); } else { result = result.replace('a', this.ampm); } } return result; }, /* Removes widget and detach events */ destroy: function() { this.hide(); this.$clockface.remove(); if(!this.isInline && this.options.trigger === 'focus') { this.$element.off('focus.clockface'); } } }; $.fn.clockface = function ( option ) { var d, args = Array.apply(null, arguments); args.shift(); //getTime returns string (not jQuery onject) if(option === 'getTime' && this.length && (d = this.eq(0).data('clockface'))) { return d.getTime.apply(d, args); } return this.each(function () { var $this = $(this), data = $this.data('clockface'), options = typeof option == 'object' && option; if (!data) { $this.data('clockface', (data = new Clockface(this, options))); } if (typeof option == 'string' && typeof data[option] == 'function') { data[option].apply(data, args); } }); }; $.fn.clockface.defaults = { //see http://momentjs.com/docs/#/displaying/format/ format: 'H:mm', trigger: 'focus' //focus|manual }; $.fn.clockface.template = ''+ '<div class="clockface">' + '<div class="l1">' + '<div class="cell"></div>' + '<div class="cell"></div>' + '<div class="cell"></div>' + '</div>' + '<div class="l2">' + '<div class="cell left"></div>' + '<div class="cell right"></div>' + '</div>'+ '<div class="l3">' + '<div class="cell left"></div>' + '<div class="cell right"></div>' + '<div class="center"><a href="#" class="ampm"></a></div>' + '</div>'+ '<div class="l4">' + '<div class="cell left"></div>' + '<div class="cell right"></div>' + '</div>'+ '<div class="l5">' + '<div class="cell"></div>' + '<div class="cell"></div>' + '<div class="cell"></div>' + '</div>'+ '</div>'; }(window.jQuery));
JavaScript
// Released under MIT license // Copyright (c) 2009-2010 Dominic Baggott // Copyright (c) 2009-2010 Ash Berlin // Copyright (c) 2011 Christoph Dorn <christoph@christophdorn.com> (http://www.christophdorn.com) (function( expose ) { /** * class Markdown * * Markdown processing in Javascript done right. We have very particular views * on what constitutes 'right' which include: * * - produces well-formed HTML (this means that em and strong nesting is * important) * * - has an intermediate representation to allow processing of parsed data (We * in fact have two, both as [JsonML]: a markdown tree and an HTML tree). * * - is easily extensible to add new dialects without having to rewrite the * entire parsing mechanics * * - has a good test suite * * This implementation fulfills all of these (except that the test suite could * do with expanding to automatically run all the fixtures from other Markdown * implementations.) * * ##### Intermediate Representation * * *TODO* Talk about this :) Its JsonML, but document the node names we use. * * [JsonML]: http://jsonml.org/ "JSON Markup Language" **/ var Markdown = expose.Markdown = function Markdown(dialect) { switch (typeof dialect) { case "undefined": this.dialect = Markdown.dialects.Gruber; break; case "object": this.dialect = dialect; break; default: if (dialect in Markdown.dialects) { this.dialect = Markdown.dialects[dialect]; } else { throw new Error("Unknown Markdown dialect '" + String(dialect) + "'"); } break; } this.em_state = []; this.strong_state = []; this.debug_indent = ""; }; /** * parse( markdown, [dialect] ) -> JsonML * - markdown (String): markdown string to parse * - dialect (String | Dialect): the dialect to use, defaults to gruber * * Parse `markdown` and return a markdown document as a Markdown.JsonML tree. **/ expose.parse = function( source, dialect ) { // dialect will default if undefined var md = new Markdown( dialect ); return md.toTree( source ); }; /** * toHTML( markdown, [dialect] ) -> String * toHTML( md_tree ) -> String * - markdown (String): markdown string to parse * - md_tree (Markdown.JsonML): parsed markdown tree * * Take markdown (either as a string or as a JsonML tree) and run it through * [[toHTMLTree]] then turn it into a well-formated HTML fragment. **/ expose.toHTML = function toHTML( source , dialect , options ) { var input = expose.toHTMLTree( source , dialect , options ); return expose.renderJsonML( input ); }; /** * toHTMLTree( markdown, [dialect] ) -> JsonML * toHTMLTree( md_tree ) -> JsonML * - markdown (String): markdown string to parse * - dialect (String | Dialect): the dialect to use, defaults to gruber * - md_tree (Markdown.JsonML): parsed markdown tree * * Turn markdown into HTML, represented as a JsonML tree. If a string is given * to this function, it is first parsed into a markdown tree by calling * [[parse]]. **/ expose.toHTMLTree = function toHTMLTree( input, dialect , options ) { // convert string input to an MD tree if ( typeof input ==="string" ) input = this.parse( input, dialect ); // Now convert the MD tree to an HTML tree // remove references from the tree var attrs = extract_attr( input ), refs = {}; if ( attrs && attrs.references ) { refs = attrs.references; } var html = convert_tree_to_html( input, refs , options ); merge_text_nodes( html ); return html; }; // For Spidermonkey based engines function mk_block_toSource() { return "Markdown.mk_block( " + uneval(this.toString()) + ", " + uneval(this.trailing) + ", " + uneval(this.lineNumber) + " )"; } // node function mk_block_inspect() { var util = require('util'); return "Markdown.mk_block( " + util.inspect(this.toString()) + ", " + util.inspect(this.trailing) + ", " + util.inspect(this.lineNumber) + " )"; } var mk_block = Markdown.mk_block = function(block, trail, line) { // Be helpful for default case in tests. if ( arguments.length == 1 ) trail = "\n\n"; var s = new String(block); s.trailing = trail; // To make it clear its not just a string s.inspect = mk_block_inspect; s.toSource = mk_block_toSource; if (line != undefined) s.lineNumber = line; return s; }; function count_lines( str ) { var n = 0, i = -1; while ( ( i = str.indexOf('\n', i+1) ) !== -1) n++; return n; } // Internal - split source into rough blocks Markdown.prototype.split_blocks = function splitBlocks( input, startLine ) { // [\s\S] matches _anything_ (newline or space) var re = /([\s\S]+?)($|\n(?:\s*\n|$)+)/g, blocks = [], m; var line_no = 1; if ( ( m = /^(\s*\n)/.exec(input) ) != null ) { // skip (but count) leading blank lines line_no += count_lines( m[0] ); re.lastIndex = m[0].length; } while ( ( m = re.exec(input) ) !== null ) { blocks.push( mk_block( m[1], m[2], line_no ) ); line_no += count_lines( m[0] ); } return blocks; }; /** * Markdown#processBlock( block, next ) -> undefined | [ JsonML, ... ] * - block (String): the block to process * - next (Array): the following blocks * * Process `block` and return an array of JsonML nodes representing `block`. * * It does this by asking each block level function in the dialect to process * the block until one can. Succesful handling is indicated by returning an * array (with zero or more JsonML nodes), failure by a false value. * * Blocks handlers are responsible for calling [[Markdown#processInline]] * themselves as appropriate. * * If the blocks were split incorrectly or adjacent blocks need collapsing you * can adjust `next` in place using shift/splice etc. * * If any of this default behaviour is not right for the dialect, you can * define a `__call__` method on the dialect that will get invoked to handle * the block processing. */ Markdown.prototype.processBlock = function processBlock( block, next ) { var cbs = this.dialect.block, ord = cbs.__order__; if ( "__call__" in cbs ) { return cbs.__call__.call(this, block, next); } for ( var i = 0; i < ord.length; i++ ) { //D:this.debug( "Testing", ord[i] ); var res = cbs[ ord[i] ].call( this, block, next ); if ( res ) { //D:this.debug(" matched"); if ( !isArray(res) || ( res.length > 0 && !( isArray(res[0]) ) ) ) this.debug(ord[i], "didn't return a proper array"); //D:this.debug( "" ); return res; } } // Uhoh! no match! Should we throw an error? return []; }; Markdown.prototype.processInline = function processInline( block ) { return this.dialect.inline.__call__.call( this, String( block ) ); }; /** * Markdown#toTree( source ) -> JsonML * - source (String): markdown source to parse * * Parse `source` into a JsonML tree representing the markdown document. **/ // custom_tree means set this.tree to `custom_tree` and restore old value on return Markdown.prototype.toTree = function toTree( source, custom_root ) { var blocks = source instanceof Array ? source : this.split_blocks( source ); // Make tree a member variable so its easier to mess with in extensions var old_tree = this.tree; try { this.tree = custom_root || this.tree || [ "markdown" ]; blocks: while ( blocks.length ) { var b = this.processBlock( blocks.shift(), blocks ); // Reference blocks and the like won't return any content if ( !b.length ) continue blocks; this.tree.push.apply( this.tree, b ); } return this.tree; } finally { if ( custom_root ) { this.tree = old_tree; } } }; // Noop by default Markdown.prototype.debug = function () { var args = Array.prototype.slice.call( arguments); args.unshift(this.debug_indent); if (typeof print !== "undefined") print.apply( print, args ); if (typeof console !== "undefined" && typeof console.log !== "undefined") console.log.apply( null, args ); } Markdown.prototype.loop_re_over_block = function( re, block, cb ) { // Dont use /g regexps with this var m, b = block.valueOf(); while ( b.length && (m = re.exec(b) ) != null) { b = b.substr( m[0].length ); cb.call(this, m); } return b; }; /** * Markdown.dialects * * Namespace of built-in dialects. **/ Markdown.dialects = {}; /** * Markdown.dialects.Gruber * * The default dialect that follows the rules set out by John Gruber's * markdown.pl as closely as possible. Well actually we follow the behaviour of * that script which in some places is not exactly what the syntax web page * says. **/ Markdown.dialects.Gruber = { block: { atxHeader: function atxHeader( block, next ) { var m = block.match( /^(#{1,6})\s*(.*?)\s*#*\s*(?:\n|$)/ ); if ( !m ) return undefined; var header = [ "header", { level: m[ 1 ].length } ]; Array.prototype.push.apply(header, this.processInline(m[ 2 ])); if ( m[0].length < block.length ) next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) ); return [ header ]; }, setextHeader: function setextHeader( block, next ) { var m = block.match( /^(.*)\n([-=])\2\2+(?:\n|$)/ ); if ( !m ) return undefined; var level = ( m[ 2 ] === "=" ) ? 1 : 2; var header = [ "header", { level : level }, m[ 1 ] ]; if ( m[0].length < block.length ) next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) ); return [ header ]; }, code: function code( block, next ) { // | Foo // |bar // should be a code block followed by a paragraph. Fun // // There might also be adjacent code block to merge. var ret = [], re = /^(?: {0,3}\t| {4})(.*)\n?/, lines; // 4 spaces + content if ( !block.match( re ) ) return undefined; block_search: do { // Now pull out the rest of the lines var b = this.loop_re_over_block( re, block.valueOf(), function( m ) { ret.push( m[1] ); } ); if (b.length) { // Case alluded to in first comment. push it back on as a new block next.unshift( mk_block(b, block.trailing) ); break block_search; } else if (next.length) { // Check the next block - it might be code too if ( !next[0].match( re ) ) break block_search; // Pull how how many blanks lines follow - minus two to account for .join ret.push ( block.trailing.replace(/[^\n]/g, '').substring(2) ); block = next.shift(); } else { break block_search; } } while (true); return [ [ "code_block", ret.join("\n") ] ]; }, horizRule: function horizRule( block, next ) { // this needs to find any hr in the block to handle abutting blocks var m = block.match( /^(?:([\s\S]*?)\n)?[ \t]*([-_*])(?:[ \t]*\2){2,}[ \t]*(?:\n([\s\S]*))?$/ ); if ( !m ) { return undefined; } var jsonml = [ [ "hr" ] ]; // if there's a leading abutting block, process it if ( m[ 1 ] ) { jsonml.unshift.apply( jsonml, this.processBlock( m[ 1 ], [] ) ); } // if there's a trailing abutting block, stick it into next if ( m[ 3 ] ) { next.unshift( mk_block( m[ 3 ] ) ); } return jsonml; }, // There are two types of lists. Tight and loose. Tight lists have no whitespace // between the items (and result in text just in the <li>) and loose lists, // which have an empty line between list items, resulting in (one or more) // paragraphs inside the <li>. // // There are all sorts weird edge cases about the original markdown.pl's // handling of lists: // // * Nested lists are supposed to be indented by four chars per level. But // if they aren't, you can get a nested list by indenting by less than // four so long as the indent doesn't match an indent of an existing list // item in the 'nest stack'. // // * The type of the list (bullet or number) is controlled just by the // first item at the indent. Subsequent changes are ignored unless they // are for nested lists // lists: (function( ) { // Use a closure to hide a few variables. var any_list = "[*+-]|\\d+\\.", bullet_list = /[*+-]/, number_list = /\d+\./, // Capture leading indent as it matters for determining nested lists. is_list_re = new RegExp( "^( {0,3})(" + any_list + ")[ \t]+" ), indent_re = "(?: {0,3}\\t| {4})"; // TODO: Cache this regexp for certain depths. // Create a regexp suitable for matching an li for a given stack depth function regex_for_depth( depth ) { return new RegExp( // m[1] = indent, m[2] = list_type "(?:^(" + indent_re + "{0," + depth + "} {0,3})(" + any_list + ")\\s+)|" + // m[3] = cont "(^" + indent_re + "{0," + (depth-1) + "}[ ]{0,4})" ); } function expand_tab( input ) { return input.replace( / {0,3}\t/g, " " ); } // Add inline content `inline` to `li`. inline comes from processInline // so is an array of content function add(li, loose, inline, nl) { if (loose) { li.push( [ "para" ].concat(inline) ); return; } // Hmmm, should this be any block level element or just paras? var add_to = li[li.length -1] instanceof Array && li[li.length - 1][0] == "para" ? li[li.length -1] : li; // If there is already some content in this list, add the new line in if (nl && li.length > 1) inline.unshift(nl); for (var i=0; i < inline.length; i++) { var what = inline[i], is_str = typeof what == "string"; if (is_str && add_to.length > 1 && typeof add_to[add_to.length-1] == "string" ) { add_to[ add_to.length-1 ] += what; } else { add_to.push( what ); } } } // contained means have an indent greater than the current one. On // *every* line in the block function get_contained_blocks( depth, blocks ) { var re = new RegExp( "^(" + indent_re + "{" + depth + "}.*?\\n?)*$" ), replace = new RegExp("^" + indent_re + "{" + depth + "}", "gm"), ret = []; while ( blocks.length > 0 ) { if ( re.exec( blocks[0] ) ) { var b = blocks.shift(), // Now remove that indent x = b.replace( replace, ""); ret.push( mk_block( x, b.trailing, b.lineNumber ) ); } break; } return ret; } // passed to stack.forEach to turn list items up the stack into paras function paragraphify(s, i, stack) { var list = s.list; var last_li = list[list.length-1]; if (last_li[1] instanceof Array && last_li[1][0] == "para") { return; } if (i+1 == stack.length) { // Last stack frame // Keep the same array, but replace the contents last_li.push( ["para"].concat( last_li.splice(1) ) ); } else { var sublist = last_li.pop(); last_li.push( ["para"].concat( last_li.splice(1) ), sublist ); } } // The matcher function return function( block, next ) { var m = block.match( is_list_re ); if ( !m ) return undefined; function make_list( m ) { var list = bullet_list.exec( m[2] ) ? ["bulletlist"] : ["numberlist"]; stack.push( { list: list, indent: m[1] } ); return list; } var stack = [], // Stack of lists for nesting. list = make_list( m ), last_li, loose = false, ret = [ stack[0].list ], i; // Loop to search over block looking for inner block elements and loose lists loose_search: while( true ) { // Split into lines preserving new lines at end of line var lines = block.split( /(?=\n)/ ); // We have to grab all lines for a li and call processInline on them // once as there are some inline things that can span lines. var li_accumulate = ""; // Loop over the lines in this block looking for tight lists. tight_search: for (var line_no=0; line_no < lines.length; line_no++) { var nl = "", l = lines[line_no].replace(/^\n/, function(n) { nl = n; return ""; }); // TODO: really should cache this var line_re = regex_for_depth( stack.length ); m = l.match( line_re ); //print( "line:", uneval(l), "\nline match:", uneval(m) ); // We have a list item if ( m[1] !== undefined ) { // Process the previous list item, if any if ( li_accumulate.length ) { add( last_li, loose, this.processInline( li_accumulate ), nl ); // Loose mode will have been dealt with. Reset it loose = false; li_accumulate = ""; } m[1] = expand_tab( m[1] ); var wanted_depth = Math.floor(m[1].length/4)+1; //print( "want:", wanted_depth, "stack:", stack.length); if ( wanted_depth > stack.length ) { // Deep enough for a nested list outright //print ( "new nested list" ); list = make_list( m ); last_li.push( list ); last_li = list[1] = [ "listitem" ]; } else { // We aren't deep enough to be strictly a new level. This is // where Md.pl goes nuts. If the indent matches a level in the // stack, put it there, else put it one deeper then the // wanted_depth deserves. var found = false; for (i = 0; i < stack.length; i++) { if ( stack[ i ].indent != m[1] ) continue; list = stack[ i ].list; stack.splice( i+1 ); found = true; break; } if (!found) { //print("not found. l:", uneval(l)); wanted_depth++; if (wanted_depth <= stack.length) { stack.splice(wanted_depth); //print("Desired depth now", wanted_depth, "stack:", stack.length); list = stack[wanted_depth-1].list; //print("list:", uneval(list) ); } else { //print ("made new stack for messy indent"); list = make_list(m); last_li.push(list); } } //print( uneval(list), "last", list === stack[stack.length-1].list ); last_li = [ "listitem" ]; list.push(last_li); } // end depth of shenegains nl = ""; } // Add content if (l.length > m[0].length) { li_accumulate += nl + l.substr( m[0].length ); } } // tight_search if ( li_accumulate.length ) { add( last_li, loose, this.processInline( li_accumulate ), nl ); // Loose mode will have been dealt with. Reset it loose = false; li_accumulate = ""; } // Look at the next block - we might have a loose list. Or an extra // paragraph for the current li var contained = get_contained_blocks( stack.length, next ); // Deal with code blocks or properly nested lists if (contained.length > 0) { // Make sure all listitems up the stack are paragraphs forEach( stack, paragraphify, this); last_li.push.apply( last_li, this.toTree( contained, [] ) ); } var next_block = next[0] && next[0].valueOf() || ""; if ( next_block.match(is_list_re) || next_block.match( /^ / ) ) { block = next.shift(); // Check for an HR following a list: features/lists/hr_abutting var hr = this.dialect.block.horizRule( block, next ); if (hr) { ret.push.apply(ret, hr); break; } // Make sure all listitems up the stack are paragraphs forEach( stack, paragraphify, this); loose = true; continue loose_search; } break; } // loose_search return ret; }; })(), blockquote: function blockquote( block, next ) { if ( !block.match( /^>/m ) ) return undefined; var jsonml = []; // separate out the leading abutting block, if any if ( block[ 0 ] != ">" ) { var lines = block.split( /\n/ ), prev = []; // keep shifting lines until you find a crotchet while ( lines.length && lines[ 0 ][ 0 ] != ">" ) { prev.push( lines.shift() ); } // reassemble! block = lines.join( "\n" ); jsonml.push.apply( jsonml, this.processBlock( prev.join( "\n" ), [] ) ); } // if the next block is also a blockquote merge it in while ( next.length && next[ 0 ][ 0 ] == ">" ) { var b = next.shift(); block = new String(block + block.trailing + b); block.trailing = b.trailing; } // Strip off the leading "> " and re-process as a block. var input = block.replace( /^> ?/gm, '' ), old_tree = this.tree; jsonml.push( this.toTree( input, [ "blockquote" ] ) ); return jsonml; }, referenceDefn: function referenceDefn( block, next) { var re = /^\s*\[(.*?)\]:\s*(\S+)(?:\s+(?:(['"])(.*?)\3|\((.*?)\)))?\n?/; // interesting matches are [ , ref_id, url, , title, title ] if ( !block.match(re) ) return undefined; // make an attribute node if it doesn't exist if ( !extract_attr( this.tree ) ) { this.tree.splice( 1, 0, {} ); } var attrs = extract_attr( this.tree ); // make a references hash if it doesn't exist if ( attrs.references === undefined ) { attrs.references = {}; } var b = this.loop_re_over_block(re, block, function( m ) { if ( m[2] && m[2][0] == '<' && m[2][m[2].length-1] == '>' ) m[2] = m[2].substring( 1, m[2].length - 1 ); var ref = attrs.references[ m[1].toLowerCase() ] = { href: m[2] }; if (m[4] !== undefined) ref.title = m[4]; else if (m[5] !== undefined) ref.title = m[5]; } ); if (b.length) next.unshift( mk_block( b, block.trailing ) ); return []; }, para: function para( block, next ) { // everything's a para! return [ ["para"].concat( this.processInline( block ) ) ]; } } }; Markdown.dialects.Gruber.inline = { __oneElement__: function oneElement( text, patterns_or_re, previous_nodes ) { var m, res, lastIndex = 0; patterns_or_re = patterns_or_re || this.dialect.inline.__patterns__; var re = new RegExp( "([\\s\\S]*?)(" + (patterns_or_re.source || patterns_or_re) + ")" ); m = re.exec( text ); if (!m) { // Just boring text return [ text.length, text ]; } else if ( m[1] ) { // Some un-interesting text matched. Return that first return [ m[1].length, m[1] ]; } var res; if ( m[2] in this.dialect.inline ) { res = this.dialect.inline[ m[2] ].call( this, text.substr( m.index ), m, previous_nodes || [] ); } // Default for now to make dev easier. just slurp special and output it. res = res || [ m[2].length, m[2] ]; return res; }, __call__: function inline( text, patterns ) { var out = [], res; function add(x) { //D:self.debug(" adding output", uneval(x)); if (typeof x == "string" && typeof out[out.length-1] == "string") out[ out.length-1 ] += x; else out.push(x); } while ( text.length > 0 ) { res = this.dialect.inline.__oneElement__.call(this, text, patterns, out ); text = text.substr( res.shift() ); forEach(res, add ) } return out; }, // These characters are intersting elsewhere, so have rules for them so that // chunks of plain text blocks don't include them "]": function () {}, "}": function () {}, "\\": function escaped( text ) { // [ length of input processed, node/children to add... ] // Only esacape: \ ` * _ { } [ ] ( ) # * + - . ! if ( text.match( /^\\[\\`\*_{}\[\]()#\+.!\-]/ ) ) return [ 2, text[1] ]; else // Not an esacpe return [ 1, "\\" ]; }, "![": function image( text ) { // Unlike images, alt text is plain text only. no other elements are // allowed in there // ![Alt text](/path/to/img.jpg "Optional title") // 1 2 3 4 <--- captures var m = text.match( /^!\[(.*?)\][ \t]*\([ \t]*(\S*)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/ ); if ( m ) { if ( m[2] && m[2][0] == '<' && m[2][m[2].length-1] == '>' ) m[2] = m[2].substring( 1, m[2].length - 1 ); m[2] = this.dialect.inline.__call__.call( this, m[2], /\\/ )[0]; var attrs = { alt: m[1], href: m[2] || "" }; if ( m[4] !== undefined) attrs.title = m[4]; return [ m[0].length, [ "img", attrs ] ]; } // ![Alt text][id] m = text.match( /^!\[(.*?)\][ \t]*\[(.*?)\]/ ); if ( m ) { // We can't check if the reference is known here as it likely wont be // found till after. Check it in md tree->hmtl tree conversion return [ m[0].length, [ "img_ref", { alt: m[1], ref: m[2].toLowerCase(), original: m[0] } ] ]; } // Just consume the '![' return [ 2, "![" ]; }, "[": function link( text ) { var orig = String(text); // Inline content is possible inside `link text` var res = Markdown.DialectHelpers.inline_until_char.call( this, text.substr(1), ']' ); // No closing ']' found. Just consume the [ if ( !res ) return [ 1, '[' ]; var consumed = 1 + res[ 0 ], children = res[ 1 ], link, attrs; // At this point the first [...] has been parsed. See what follows to find // out which kind of link we are (reference or direct url) text = text.substr( consumed ); // [link text](/path/to/img.jpg "Optional title") // 1 2 3 <--- captures // This will capture up to the last paren in the block. We then pull // back based on if there a matching ones in the url // ([here](/url/(test)) // The parens have to be balanced var m = text.match( /^\s*\([ \t]*(\S+)(?:[ \t]+(["'])(.*?)\2)?[ \t]*\)/ ); if ( m ) { var url = m[1]; consumed += m[0].length; if ( url && url[0] == '<' && url[url.length-1] == '>' ) url = url.substring( 1, url.length - 1 ); // If there is a title we don't have to worry about parens in the url if ( !m[3] ) { var open_parens = 1; // One open that isn't in the capture for (var len = 0; len < url.length; len++) { switch ( url[len] ) { case '(': open_parens++; break; case ')': if ( --open_parens == 0) { consumed -= url.length - len; url = url.substring(0, len); } break; } } } // Process escapes only url = this.dialect.inline.__call__.call( this, url, /\\/ )[0]; attrs = { href: url || "" }; if ( m[3] !== undefined) attrs.title = m[3]; link = [ "link", attrs ].concat( children ); return [ consumed, link ]; } // [Alt text][id] // [Alt text] [id] m = text.match( /^\s*\[(.*?)\]/ ); if ( m ) { consumed += m[ 0 ].length; // [links][] uses links as its reference attrs = { ref: ( m[ 1 ] || String(children) ).toLowerCase(), original: orig.substr( 0, consumed ) }; link = [ "link_ref", attrs ].concat( children ); // We can't check if the reference is known here as it likely wont be // found till after. Check it in md tree->hmtl tree conversion. // Store the original so that conversion can revert if the ref isn't found. return [ consumed, link ]; } // [id] // Only if id is plain (no formatting.) if ( children.length == 1 && typeof children[0] == "string" ) { attrs = { ref: children[0].toLowerCase(), original: orig.substr( 0, consumed ) }; link = [ "link_ref", attrs, children[0] ]; return [ consumed, link ]; } // Just consume the '[' return [ 1, "[" ]; }, "<": function autoLink( text ) { var m; if ( ( m = text.match( /^<(?:((https?|ftp|mailto):[^>]+)|(.*?@.*?\.[a-zA-Z]+))>/ ) ) != null ) { if ( m[3] ) { return [ m[0].length, [ "link", { href: "mailto:" + m[3] }, m[3] ] ]; } else if ( m[2] == "mailto" ) { return [ m[0].length, [ "link", { href: m[1] }, m[1].substr("mailto:".length ) ] ]; } else return [ m[0].length, [ "link", { href: m[1] }, m[1] ] ]; } return [ 1, "<" ]; }, "`": function inlineCode( text ) { // Inline code block. as many backticks as you like to start it // Always skip over the opening ticks. var m = text.match( /(`+)(([\s\S]*?)\1)/ ); if ( m && m[2] ) return [ m[1].length + m[2].length, [ "inlinecode", m[3] ] ]; else { // TODO: No matching end code found - warn! return [ 1, "`" ]; } }, " \n": function lineBreak( text ) { return [ 3, [ "linebreak" ] ]; } }; // Meta Helper/generator method for em and strong handling function strong_em( tag, md ) { var state_slot = tag + "_state", other_slot = tag == "strong" ? "em_state" : "strong_state"; function CloseTag(len) { this.len_after = len; this.name = "close_" + md; } return function ( text, orig_match ) { if (this[state_slot][0] == md) { // Most recent em is of this type //D:this.debug("closing", md); this[state_slot].shift(); // "Consume" everything to go back to the recrusion in the else-block below return[ text.length, new CloseTag(text.length-md.length) ]; } else { // Store a clone of the em/strong states var other = this[other_slot].slice(), state = this[state_slot].slice(); this[state_slot].unshift(md); //D:this.debug_indent += " "; // Recurse var res = this.processInline( text.substr( md.length ) ); //D:this.debug_indent = this.debug_indent.substr(2); var last = res[res.length - 1]; //D:this.debug("processInline from", tag + ": ", uneval( res ) ); var check = this[state_slot].shift(); if (last instanceof CloseTag) { res.pop(); // We matched! Huzzah. var consumed = text.length - last.len_after; return [ consumed, [ tag ].concat(res) ]; } else { // Restore the state of the other kind. We might have mistakenly closed it. this[other_slot] = other; this[state_slot] = state; // We can't reuse the processed result as it could have wrong parsing contexts in it. return [ md.length, md ]; } } }; // End returned function } Markdown.dialects.Gruber.inline["**"] = strong_em("strong", "**"); Markdown.dialects.Gruber.inline["__"] = strong_em("strong", "__"); Markdown.dialects.Gruber.inline["*"] = strong_em("em", "*"); Markdown.dialects.Gruber.inline["_"] = strong_em("em", "_"); // Build default order from insertion order. Markdown.buildBlockOrder = function(d) { var ord = []; for ( var i in d ) { if ( i == "__order__" || i == "__call__" ) continue; ord.push( i ); } d.__order__ = ord; }; // Build patterns for inline matcher Markdown.buildInlinePatterns = function(d) { var patterns = []; for ( var i in d ) { // __foo__ is reserved and not a pattern if ( i.match( /^__.*__$/) ) continue; var l = i.replace( /([\\.*+?|()\[\]{}])/g, "\\$1" ) .replace( /\n/, "\\n" ); patterns.push( i.length == 1 ? l : "(?:" + l + ")" ); } patterns = patterns.join("|"); d.__patterns__ = patterns; //print("patterns:", uneval( patterns ) ); var fn = d.__call__; d.__call__ = function(text, pattern) { if (pattern != undefined) { return fn.call(this, text, pattern); } else { return fn.call(this, text, patterns); } }; }; Markdown.DialectHelpers = {}; Markdown.DialectHelpers.inline_until_char = function( text, want ) { var consumed = 0, nodes = []; while ( true ) { if ( text[ consumed ] == want ) { // Found the character we were looking for consumed++; return [ consumed, nodes ]; } if ( consumed >= text.length ) { // No closing char found. Abort. return null; } var res = this.dialect.inline.__oneElement__.call(this, text.substr( consumed ) ); consumed += res[ 0 ]; // Add any returned nodes. nodes.push.apply( nodes, res.slice( 1 ) ); } } // Helper function to make sub-classing a dialect easier Markdown.subclassDialect = function( d ) { function Block() {} Block.prototype = d.block; function Inline() {} Inline.prototype = d.inline; return { block: new Block(), inline: new Inline() }; }; Markdown.buildBlockOrder ( Markdown.dialects.Gruber.block ); Markdown.buildInlinePatterns( Markdown.dialects.Gruber.inline ); Markdown.dialects.Maruku = Markdown.subclassDialect( Markdown.dialects.Gruber ); Markdown.dialects.Maruku.processMetaHash = function processMetaHash( meta_string ) { var meta = split_meta_hash( meta_string ), attr = {}; for ( var i = 0; i < meta.length; ++i ) { // id: #foo if ( /^#/.test( meta[ i ] ) ) { attr.id = meta[ i ].substring( 1 ); } // class: .foo else if ( /^\./.test( meta[ i ] ) ) { // if class already exists, append the new one if ( attr['class'] ) { attr['class'] = attr['class'] + meta[ i ].replace( /./, " " ); } else { attr['class'] = meta[ i ].substring( 1 ); } } // attribute: foo=bar else if ( /\=/.test( meta[ i ] ) ) { var s = meta[ i ].split( /\=/ ); attr[ s[ 0 ] ] = s[ 1 ]; } } return attr; } function split_meta_hash( meta_string ) { var meta = meta_string.split( "" ), parts = [ "" ], in_quotes = false; while ( meta.length ) { var letter = meta.shift(); switch ( letter ) { case " " : // if we're in a quoted section, keep it if ( in_quotes ) { parts[ parts.length - 1 ] += letter; } // otherwise make a new part else { parts.push( "" ); } break; case "'" : case '"' : // reverse the quotes and move straight on in_quotes = !in_quotes; break; case "\\" : // shift off the next letter to be used straight away. // it was escaped so we'll keep it whatever it is letter = meta.shift(); default : parts[ parts.length - 1 ] += letter; break; } } return parts; } Markdown.dialects.Maruku.block.document_meta = function document_meta( block, next ) { // we're only interested in the first block if ( block.lineNumber > 1 ) return undefined; // document_meta blocks consist of one or more lines of `Key: Value\n` if ( ! block.match( /^(?:\w+:.*\n)*\w+:.*$/ ) ) return undefined; // make an attribute node if it doesn't exist if ( !extract_attr( this.tree ) ) { this.tree.splice( 1, 0, {} ); } var pairs = block.split( /\n/ ); for ( p in pairs ) { var m = pairs[ p ].match( /(\w+):\s*(.*)$/ ), key = m[ 1 ].toLowerCase(), value = m[ 2 ]; this.tree[ 1 ][ key ] = value; } // document_meta produces no content! return []; }; Markdown.dialects.Maruku.block.block_meta = function block_meta( block, next ) { // check if the last line of the block is an meta hash var m = block.match( /(^|\n) {0,3}\{:\s*((?:\\\}|[^\}])*)\s*\}$/ ); if ( !m ) return undefined; // process the meta hash var attr = this.dialect.processMetaHash( m[ 2 ] ); var hash; // if we matched ^ then we need to apply meta to the previous block if ( m[ 1 ] === "" ) { var node = this.tree[ this.tree.length - 1 ]; hash = extract_attr( node ); // if the node is a string (rather than JsonML), bail if ( typeof node === "string" ) return undefined; // create the attribute hash if it doesn't exist if ( !hash ) { hash = {}; node.splice( 1, 0, hash ); } // add the attributes in for ( a in attr ) { hash[ a ] = attr[ a ]; } // return nothing so the meta hash is removed return []; } // pull the meta hash off the block and process what's left var b = block.replace( /\n.*$/, "" ), result = this.processBlock( b, [] ); // get or make the attributes hash hash = extract_attr( result[ 0 ] ); if ( !hash ) { hash = {}; result[ 0 ].splice( 1, 0, hash ); } // attach the attributes to the block for ( a in attr ) { hash[ a ] = attr[ a ]; } return result; }; Markdown.dialects.Maruku.block.definition_list = function definition_list( block, next ) { // one or more terms followed by one or more definitions, in a single block var tight = /^((?:[^\s:].*\n)+):\s+([\s\S]+)$/, list = [ "dl" ], i; // see if we're dealing with a tight or loose block if ( ( m = block.match( tight ) ) ) { // pull subsequent tight DL blocks out of `next` var blocks = [ block ]; while ( next.length && tight.exec( next[ 0 ] ) ) { blocks.push( next.shift() ); } for ( var b = 0; b < blocks.length; ++b ) { var m = blocks[ b ].match( tight ), terms = m[ 1 ].replace( /\n$/, "" ).split( /\n/ ), defns = m[ 2 ].split( /\n:\s+/ ); // print( uneval( m ) ); for ( i = 0; i < terms.length; ++i ) { list.push( [ "dt", terms[ i ] ] ); } for ( i = 0; i < defns.length; ++i ) { // run inline processing over the definition list.push( [ "dd" ].concat( this.processInline( defns[ i ].replace( /(\n)\s+/, "$1" ) ) ) ); } } } else { return undefined; } return [ list ]; }; Markdown.dialects.Maruku.inline[ "{:" ] = function inline_meta( text, matches, out ) { if ( !out.length ) { return [ 2, "{:" ]; } // get the preceeding element var before = out[ out.length - 1 ]; if ( typeof before === "string" ) { return [ 2, "{:" ]; } // match a meta hash var m = text.match( /^\{:\s*((?:\\\}|[^\}])*)\s*\}/ ); // no match, false alarm if ( !m ) { return [ 2, "{:" ]; } // attach the attributes to the preceeding element var meta = this.dialect.processMetaHash( m[ 1 ] ), attr = extract_attr( before ); if ( !attr ) { attr = {}; before.splice( 1, 0, attr ); } for ( var k in meta ) { attr[ k ] = meta[ k ]; } // cut out the string and replace it with nothing return [ m[ 0 ].length, "" ]; }; Markdown.buildBlockOrder ( Markdown.dialects.Maruku.block ); Markdown.buildInlinePatterns( Markdown.dialects.Maruku.inline ); var isArray = Array.isArray || function(obj) { return Object.prototype.toString.call(obj) == '[object Array]'; }; var forEach; // Don't mess with Array.prototype. Its not friendly if ( Array.prototype.forEach ) { forEach = function( arr, cb, thisp ) { return arr.forEach( cb, thisp ); }; } else { forEach = function(arr, cb, thisp) { for (var i = 0; i < arr.length; i++) { cb.call(thisp || arr, arr[i], i, arr); } } } function extract_attr( jsonml ) { return isArray(jsonml) && jsonml.length > 1 && typeof jsonml[ 1 ] === "object" && !( isArray(jsonml[ 1 ]) ) ? jsonml[ 1 ] : undefined; } /** * renderJsonML( jsonml[, options] ) -> String * - jsonml (Array): JsonML array to render to XML * - options (Object): options * * Converts the given JsonML into well-formed XML. * * The options currently understood are: * * - root (Boolean): wether or not the root node should be included in the * output, or just its children. The default `false` is to not include the * root itself. */ expose.renderJsonML = function( jsonml, options ) { options = options || {}; // include the root element in the rendered output? options.root = options.root || false; var content = []; if ( options.root ) { content.push( render_tree( jsonml ) ); } else { jsonml.shift(); // get rid of the tag if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) { jsonml.shift(); // get rid of the attributes } while ( jsonml.length ) { content.push( render_tree( jsonml.shift() ) ); } } return content.join( "\n\n" ); }; function escapeHTML( text ) { return text.replace( /&/g, "&amp;" ) .replace( /</g, "&lt;" ) .replace( />/g, "&gt;" ) .replace( /"/g, "&quot;" ) .replace( /'/g, "&#39;" ); } function render_tree( jsonml ) { // basic case if ( typeof jsonml === "string" ) { return escapeHTML( jsonml ); } var tag = jsonml.shift(), attributes = {}, content = []; if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) { attributes = jsonml.shift(); } while ( jsonml.length ) { content.push( arguments.callee( jsonml.shift() ) ); } var tag_attrs = ""; for ( var a in attributes ) { tag_attrs += " " + a + '="' + escapeHTML( attributes[ a ] ) + '"'; } // be careful about adding whitespace here for inline elements if ( tag == "img" || tag == "br" || tag == "hr" ) { return "<"+ tag + tag_attrs + "/>"; } else { return "<"+ tag + tag_attrs + ">" + content.join( "" ) + "</" + tag + ">"; } } function convert_tree_to_html( tree, references, options ) { var i; options = options || {}; // shallow clone var jsonml = tree.slice( 0 ); if (typeof options.preprocessTreeNode === "function") { jsonml = options.preprocessTreeNode(jsonml, references); } // Clone attributes if they exist var attrs = extract_attr( jsonml ); if ( attrs ) { jsonml[ 1 ] = {}; for ( i in attrs ) { jsonml[ 1 ][ i ] = attrs[ i ]; } attrs = jsonml[ 1 ]; } // basic case if ( typeof jsonml === "string" ) { return jsonml; } // convert this node switch ( jsonml[ 0 ] ) { case "header": jsonml[ 0 ] = "h" + jsonml[ 1 ].level; delete jsonml[ 1 ].level; break; case "bulletlist": jsonml[ 0 ] = "ul"; break; case "numberlist": jsonml[ 0 ] = "ol"; break; case "listitem": jsonml[ 0 ] = "li"; break; case "para": jsonml[ 0 ] = "p"; break; case "markdown": jsonml[ 0 ] = "html"; if ( attrs ) delete attrs.references; break; case "code_block": jsonml[ 0 ] = "pre"; i = attrs ? 2 : 1; var code = [ "code" ]; code.push.apply( code, jsonml.splice( i ) ); jsonml[ i ] = code; break; case "inlinecode": jsonml[ 0 ] = "code"; break; case "img": jsonml[ 1 ].src = jsonml[ 1 ].href; delete jsonml[ 1 ].href; break; case "linebreak": jsonml[ 0 ] = "br"; break; case "link": jsonml[ 0 ] = "a"; break; case "link_ref": jsonml[ 0 ] = "a"; // grab this ref and clean up the attribute node var ref = references[ attrs.ref ]; // if the reference exists, make the link if ( ref ) { delete attrs.ref; // add in the href and title, if present attrs.href = ref.href; if ( ref.title ) { attrs.title = ref.title; } // get rid of the unneeded original text delete attrs.original; } // the reference doesn't exist, so revert to plain text else { return attrs.original; } break; case "img_ref": jsonml[ 0 ] = "img"; // grab this ref and clean up the attribute node var ref = references[ attrs.ref ]; // if the reference exists, make the link if ( ref ) { delete attrs.ref; // add in the href and title, if present attrs.src = ref.href; if ( ref.title ) { attrs.title = ref.title; } // get rid of the unneeded original text delete attrs.original; } // the reference doesn't exist, so revert to plain text else { return attrs.original; } break; } // convert all the children i = 1; // deal with the attribute node, if it exists if ( attrs ) { // if there are keys, skip over it for ( var key in jsonml[ 1 ] ) { i = 2; } // if there aren't, remove it if ( i === 1 ) { jsonml.splice( i, 1 ); } } for ( ; i < jsonml.length; ++i ) { jsonml[ i ] = arguments.callee( jsonml[ i ], references, options ); } return jsonml; } // merges adjacent text nodes into a single node function merge_text_nodes( jsonml ) { // skip the tag name and attribute hash var i = extract_attr( jsonml ) ? 2 : 1; while ( i < jsonml.length ) { // if it's a string check the next item too if ( typeof jsonml[ i ] === "string" ) { if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) { // merge the second string into the first and remove it jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ]; } else { ++i; } } // if it's not a string recurse else { arguments.callee( jsonml[ i ] ); ++i; } } } } )( (function() { if ( typeof exports === "undefined" ) { window.markdown = {}; return window.markdown; } else { return exports; } } )() );
JavaScript
/* global jQuery */ (function ($) { "use strict"; $(function () { var search = function (str) { var tmp = str && str.length ? $.vakata.search(str, true, { threshold : 0.2, fuzzy : true, caseSensitive : false }) : null, res = $('#api_inner') .find('.item').hide() .filter(function () { return tmp ? tmp.search($(this).find('>h4>code').text()).isMatch : true; }).show().length; $('#api_inner').find('#no_res')[ !tmp || res ? 'hide' : 'show' ](); $('#api_inner').find('#cl_src')[ tmp && res ? 'show' : 'hide' ](); if(!$('#srch').is(':focus')) { $('#srch').val(str); } $(window).resize(); }, filter = function (str) { $('.item-inner').hide(); if(str) { var i = $('.item[rel="'+str+'"]'); if(!i.length) { i = $('.item[rel^="'+str+'"]'); } if(i && i.length) { i = i.eq(0); i.children('.item-inner').show().end(); if(i.offset().top < $(document).scrollTop() || i.offset().top + i.height() > $(document).scrollTop() + $(window).height()) { i[0].scrollIntoView(); } } } }; var to1 = false; $(window).resize(function () { if(to1) { clearTimeout(to1); } to1 = setTimeout(function () { $('.page').css('minHeight','0px').css('minHeight', ($(document).height() - $('#head').outerHeight()) + 'px'); },50); }); $('.tab-content').children().hide().eq(0).show(); $('.nav a').on('click', function () { $(this).blur(); }); $.address //.state(window.location.protocol + '//' + window.location.host + window.location.pathname.replace(/^(.*?\/docs\/).*$/ig, '$1')) .init(function(e) { $('a:not([href^=http])').not($('.demo a')).address().on('click', function () { if($.address.pathNames().length < 2 && !$.address.parameter('f')) { $(document).scrollTop(0); } }); }) .change(function(e) { var page, elem, cont, srch; if(!e.pathNames.length || !$('#content').children('#' + e.pathNames[0]).length) { $('#menu a').eq(0).click(); return; } page = e.pathNames[0]; $('#menu').find('a[href$="'+page+'"]').blur().parent().addClass('active').siblings().removeClass('active'); cont = $('#content').children('#' + page).show().siblings().hide().end(); if(page === 'api') { search($.address.parameter('q') ? decodeURIComponent($.address.parameter('q')) : ''); filter($.address.parameter('f') ? decodeURIComponent($.address.parameter('f')) : ''); } else { $('#srch').val(''); cont.find('.item').show(); elem = e.pathNames[1] ? cont.find('#' + e.pathNames[1]) : []; if(elem.length) { if(elem.hasClass('tab-content-item')) { elem.siblings().hide().end().show().parent().prev().children().removeClass('active').eq(elem.index()).addClass('active'); } else { elem[0].scrollIntoView(); } } //else { // document.documentElement.scrollTop = 0; //} } $(window).resize(); }); var to2 = false; $('#srch').on('keyup', function () { if(to2) { clearTimeout(to2); } to2 = setTimeout(function () { var f = $.address.parameter('f'), q = $('#srch').val(), d = []; if(q && q.length) { d.push('q=' + q); } if(f && f.length && false) { d.push('f=' + f); } $.address.value('/api/' + (d.length ? '?' + d.join('&') : '')); }, 250); }); var container = $('#api_inner'), str; $.getJSON('./jstree.json', function (data) { //return; $.each(data, function (ii, v) { if(v.description.full.indexOf('<p>lobals') === 0) { return true; } if(v.ignore) { return true; } var str = '', name, plugin, internal, params = [], retrn, priv = false, evnt = false, trig, i, j; for(i = 0, j = v.tags.length; i < j; i++) { switch(v.tags[i].type) { case "name": name = v.tags[i].string; break; case "private": priv = true; break; case "event": evnt = true; break; case "trigger": trig = v.tags[i].string; break; case 'plugin': plugin = v.tags[i].string; break; case 'return': retrn = '<ul class="params list-unstyled"><li><code class="param return">Returns</code><p><code class="type">' + v.tags[i].types.join('</code> <code class="type">') + '</code> ' + v.tags[i].description + '</p></li></ul>'; break; case 'param': params.push('<code class="param">' + v.tags[i].name + '</code><p><code class="type">' + v.tags[i].types.join('</code> <code class="type">') + '</code> ' + v.tags[i].description + '</p>'); break; } } str += '<div class="item '+(priv?'private':'')+'" rel="'+(name?name.replace('"',''):'')+'">'; if(name) { if(name.indexOf('(') !== -1 && name.indexOf('$(') === -1) { name = name.split('('); name = '<strong>' + name[0] + '</strong> (' + name[1]; } str += '<h4><code class="'+(name.indexOf('(') === -1 ? (evnt ? 'evnt' : 'prop') : 'func')+'">'+name+(evnt?' Event <i class="glyphicon glyphicon-flash"></i>' : '')+'</code>'; if(plugin) { str += '<code class="meta plugin"><i class="glyphicon glyphicon-leaf"></i> '+plugin+' plugin</code> '; } if(priv) { str += '<code class="meta">private</code> '; } str += '</h4>'; } str += '<div class="' + (name ? "item-inner" : "" ) + '">'; str += '<div>'+ v.description.full +'</div>'; if(params.length) { str += '<ul class="params list-unstyled">'; for(var k = 0, l = params.length; k < l; k++) { str += '<li>' + params[k] + '</li>'; } str += '</ul>'; } if(retrn) { str += retrn; } if(trig) { str += '<ul class="params list-unstyled"><li><code class="param trigger">Triggers</code><p><code class="evnt">'+ trig.split(',').join('</code> <code class="evnt">')+'</code></p></li></ul>'; } str += '</div>'; str += '</div>'; container.append(str); }); $('#api h3').prepend('<i class="glyphicon glyphicon-leaf"></i>&nbsp;').closest('.item').css({ 'background' : 'white', 'border' : '0', 'borderRadius' : '0', /*'borderBottom' : '1px solid #8b0000', 'textAlign' : 'center',*/ 'marginTop' : '0', 'paddingTop' : '0' }).prev().css('marginBottom', '3em'); $('.item > h4').on('click', function () { var r = $(this).parent().attr('rel'); if(r && r.length) { var q = $.address.parameter('q'); if($.address.parameter('f') === r) { $.address.value($.address.pathNames()[0] + '/' + (q ? '?q=' + q : '')); } else { $.address.value($.address.pathNames()[0] + '/?' + (q ? 'q=' + q + '&' : '') + 'f=' + r); } } //$(this).next().slideToggle(); }); //$('.item > h4 > code').on('click', function () { $('#srch').val($(this).text().replace(' Event','')).keyup(); }); container.find('pre').each(function () { var d = $('<div>'), p = $(this).closest('.item').find('.item-inner'); $(this).prev().appendTo(d); $(this).appendTo(d); p.append(d); }); if($('#srch').val().length) { search(decodeURIComponent($.address.parameter('q'))); } filter(decodeURIComponent($.address.parameter('f'))); }); }); }(jQuery));
JavaScript
(function ($) { $.vakata = {}; })(jQuery); (function ($) { // from http://kiro.me/projects/fuse.html $.vakata.search = function(pattern, txt, options) { options = options || {}; if(options.fuzzy !== false) { options.fuzzy = true; } pattern = options.caseSensitive ? pattern : pattern.toLowerCase(); var MATCH_LOCATION = options.location || 0, MATCH_DISTANCE = options.distance || 100, MATCH_THRESHOLD = options.threshold || 0.6, patternLen = pattern.length; if(patternLen > 32) { options.fuzzy = false; } if(options.fuzzy) { var matchmask = 1 << (patternLen - 1); var pattern_alphabet = (function () { var mask = {}, i = 0; for (i = 0; i < patternLen; i++) { mask[pattern.charAt(i)] = 0; } for (i = 0; i < patternLen; i++) { mask[pattern.charAt(i)] |= 1 << (patternLen - i - 1); } return mask; })(); var match_bitapScore = function (e, x) { var accuracy = e / patternLen, proximity = Math.abs(MATCH_LOCATION - x); if(!MATCH_DISTANCE) { return proximity ? 1.0 : accuracy; } return accuracy + (proximity / MATCH_DISTANCE); }; } var search = function (text) { text = options.caseSensitive ? text : text.toLowerCase(); if(pattern === text || text.indexOf(pattern) !== -1) { return { isMatch: true, score: 0 }; } if(!options.fuzzy) { return { isMatch: false, score: 1 }; } var i, j, textLen = text.length, scoreThreshold = MATCH_THRESHOLD, bestLoc = text.indexOf(pattern, MATCH_LOCATION), binMin, binMid, binMax = patternLen + textLen, lastRd, start, finish, rd, charMatch, score = 1, locations = []; if (bestLoc != -1) { scoreThreshold = Math.min(match_bitapScore(0, bestLoc), scoreThreshold); bestLoc = text.lastIndexOf(pattern, MATCH_LOCATION + patternLen); if (bestLoc != -1) { scoreThreshold = Math.min(match_bitapScore(0, bestLoc), scoreThreshold); } } bestLoc = -1; for (i = 0; i < patternLen; i++) { binMin = 0; binMid = binMax; while (binMin < binMid) { if (match_bitapScore(i, MATCH_LOCATION + binMid) <= scoreThreshold) { binMin = binMid; } else { binMax = binMid; } binMid = Math.floor((binMax - binMin) / 2 + binMin); } binMax = binMid; start = Math.max(1, MATCH_LOCATION - binMid + 1); finish = Math.min(MATCH_LOCATION + binMid, textLen) + patternLen; rd = Array(finish + 2); rd[finish + 1] = (1 << i) - 1; for (j = finish; j >= start; j--) { charMatch = pattern_alphabet[text.charAt(j - 1)]; if (i === 0) { rd[j] = ((rd[j + 1] << 1) | 1) & charMatch; } else { rd[j] = ((rd[j + 1] << 1) | 1) & charMatch | (((lastRd[j + 1] | lastRd[j]) << 1) | 1) | lastRd[j + 1]; } if (rd[j] & matchmask) { score = match_bitapScore(i, j - 1); if (score <= scoreThreshold) { scoreThreshold = score; bestLoc = j - 1; locations.push(bestLoc); if (bestLoc > MATCH_LOCATION) { start = Math.max(1, 2 * MATCH_LOCATION - bestLoc); } else { break; } } } } if (match_bitapScore(i + 1, MATCH_LOCATION) > scoreThreshold) { break; } lastRd = rd; } return { isMatch: bestLoc >= 0, score: score }; }; return txt === true ? { 'search' : search } : search(txt); }; })(jQuery);
JavaScript
/*! jQuery Address v.1.6 | (c) 2009, 2013 Rostislav Hristov | jquery.org/license */ (function ($) { $.address = (function () { var _trigger = function(name) { var e = $.extend($.Event(name), (function() { var parameters = {}, parameterNames = $.address.parameterNames(); for (var i = 0, l = parameterNames.length; i < l; i++) { parameters[parameterNames[i]] = $.address.parameter(parameterNames[i]); } return { value: $.address.value(), path: $.address.path(), pathNames: $.address.pathNames(), parameterNames: parameterNames, parameters: parameters, queryString: $.address.queryString() }; }).call($.address)); $($.address).trigger(e); return e; }, _array = function(obj) { return Array.prototype.slice.call(obj); }, _bind = function(value, data, fn) { $().bind.apply($($.address), Array.prototype.slice.call(arguments)); return $.address; }, _unbind = function(value, fn) { $().unbind.apply($($.address), Array.prototype.slice.call(arguments)); return $.address; }, _supportsState = function() { return (_h.pushState && _opts.state !== UNDEFINED); }, _hrefState = function() { return ('/' + _l.pathname.replace(new RegExp(_opts.state), '') + _l.search + (_hrefHash() ? '#' + _hrefHash() : '')).replace(_re, '/'); }, _hrefHash = function() { var index = _l.href.indexOf('#'); return index != -1 ? _l.href.substr(index + 1) : ''; }, _href = function() { return _supportsState() ? _hrefState() : _hrefHash(); }, _window = function() { try { return top.document !== UNDEFINED && top.document.title !== UNDEFINED && top.jQuery !== UNDEFINED && top.jQuery.address !== UNDEFINED && top.jQuery.address.frames() !== false ? top : window; } catch (e) { return window; } }, _js = function() { return 'javascript'; }, _strict = function(value) { value = value.toString(); return (_opts.strict && value.substr(0, 1) != '/' ? '/' : '') + value; }, _cssint = function(el, value) { return parseInt(el.css(value), 10); }, _listen = function() { if (!_silent) { var hash = _href(), diff = decodeURI(_value) != decodeURI(hash); if (diff) { if (_msie && _version < 7) { _l.reload(); } else { if (_msie && !_hashchange && _opts.history) { _st(_html, 50); } _value = hash; _update(FALSE); } } } }, _update = function(internal) { _st(_track, 10); return _trigger(CHANGE).isDefaultPrevented() || _trigger(internal ? INTERNAL_CHANGE : EXTERNAL_CHANGE).isDefaultPrevented(); }, _track = function() { if (_opts.tracker !== 'null' && _opts.tracker !== NULL) { var fn = $.isFunction(_opts.tracker) ? _opts.tracker : _t[_opts.tracker], value = (_l.pathname + _l.search + ($.address && !_supportsState() ? $.address.value() : '')) .replace(/\/\//, '/').replace(/^\/$/, ''); if ($.isFunction(fn)) { fn(value); } else if ($.isFunction(_t.urchinTracker)) { _t.urchinTracker(value); } else if (_t.pageTracker !== UNDEFINED && $.isFunction(_t.pageTracker._trackPageview)) { _t.pageTracker._trackPageview(value); } else if (_t._gaq !== UNDEFINED && $.isFunction(_t._gaq.push)) { _t._gaq.push(['_trackPageview', decodeURI(value)]); } } }, _html = function() { var src = _js() + ':' + FALSE + ';document.open();document.writeln(\'<html><head><title>' + _d.title.replace(/\'/g, '\\\'') + '</title><script>var ' + ID + ' = "' + encodeURIComponent(_href()).replace(/\'/g, '\\\'') + (_d.domain != _l.hostname ? '";document.domain="' + _d.domain : '') + '";</' + 'script></head></html>\');document.close();'; if (_version < 7) { _frame.src = src; } else { _frame.contentWindow.location.replace(src); } }, _options = function() { if (_url && _qi != -1) { var i, param, params = _url.substr(_qi + 1).split('&'); for (i = 0; i < params.length; i++) { param = params[i].split('='); if (/^(autoUpdate|history|strict|wrap)$/.test(param[0])) { _opts[param[0]] = (isNaN(param[1]) ? /^(true|yes)$/i.test(param[1]) : (parseInt(param[1], 10) !== 0)); } if (/^(state|tracker)$/.test(param[0])) { _opts[param[0]] = param[1]; } } _url = NULL; } _value = _href(); }, _load = function() { if (!_loaded) { _loaded = TRUE; _options(); $('a[rel*="address:"]').address(); if (_opts.wrap) { var body = $('body'), wrap = $('body > *') .wrapAll('<div style="padding:' + (_cssint(body, 'marginTop') + _cssint(body, 'paddingTop')) + 'px ' + (_cssint(body, 'marginRight') + _cssint(body, 'paddingRight')) + 'px ' + (_cssint(body, 'marginBottom') + _cssint(body, 'paddingBottom')) + 'px ' + (_cssint(body, 'marginLeft') + _cssint(body, 'paddingLeft')) + 'px;" />') .parent() .wrap('<div id="' + ID + '" style="height:100%;overflow:auto;position:relative;' + (_webkit && !window.statusbar.visible ? 'resize:both;' : '') + '" />'); $('html, body') .css({ height: '100%', margin: 0, padding: 0, overflow: 'hidden' }); if (_webkit) { $('<style type="text/css" />') .appendTo('head') .text('#' + ID + '::-webkit-resizer { background-color: #fff; }'); } } if (_msie && !_hashchange) { var frameset = _d.getElementsByTagName('frameset')[0]; _frame = _d.createElement((frameset ? '' : 'i') + 'frame'); _frame.src = _js() + ':' + FALSE; if (frameset) { frameset.insertAdjacentElement('beforeEnd', _frame); frameset[frameset.cols ? 'cols' : 'rows'] += ',0'; _frame.noResize = TRUE; _frame.frameBorder = _frame.frameSpacing = 0; } else { _frame.style.display = 'none'; _frame.style.width = _frame.style.height = 0; _frame.tabIndex = -1; _d.body.insertAdjacentElement('afterBegin', _frame); } _st(function() { $(_frame).bind('load', function() { var win = _frame.contentWindow; _value = win[ID] !== UNDEFINED ? win[ID] : ''; if (_value != _href()) { _update(FALSE); _l.hash = _value; } }); if (_frame.contentWindow[ID] === UNDEFINED) { _html(); } }, 50); } _st(function() { _trigger('init'); _update(FALSE); }, 1); if (!_supportsState()) { if ((_msie && _version > 7) || (!_msie && _hashchange)) { if (_t.addEventListener) { _t.addEventListener(HASH_CHANGE, _listen, FALSE); } else if (_t.attachEvent) { _t.attachEvent('on' + HASH_CHANGE, _listen); } } else { _si(_listen, 50); } } if ('state' in window.history) { $(window).trigger('popstate'); } } }, _popstate = function() { if (decodeURI(_value) != decodeURI(_href())) { _value = _href(); _update(FALSE); } }, _unload = function() { if (_t.removeEventListener) { _t.removeEventListener(HASH_CHANGE, _listen, FALSE); } else if (_t.detachEvent) { _t.detachEvent('on' + HASH_CHANGE, _listen); } }, _uaMatch = function(ua) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf('compatible') < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || '', version: match[ 2 ] || '0' }; }, _detectBrowser = function() { var browser = {}, matched = _uaMatch(navigator.userAgent); if (matched.browser) { browser[matched.browser] = true; browser.version = matched.version; } if (browser.chrome) { browser.webkit = true; } else if (browser.webkit) { browser.safari = true; } return browser; }, UNDEFINED, NULL = null, ID = 'jQueryAddress', STRING = 'string', HASH_CHANGE = 'hashchange', INIT = 'init', CHANGE = 'change', INTERNAL_CHANGE = 'internalChange', EXTERNAL_CHANGE = 'externalChange', TRUE = true, FALSE = false, _opts = { autoUpdate: TRUE, history: TRUE, strict: TRUE, frames: TRUE, wrap: FALSE }, _browser = _detectBrowser(), _version = parseFloat(_browser.version), _webkit = _browser.webkit || _browser.safari, _msie = !$.support.opacity, _t = _window(), _d = _t.document, _h = _t.history, _l = _t.location, _si = setInterval, _st = setTimeout, _re = /\/{2,9}/g, _agent = navigator.userAgent, _hashchange = 'on' + HASH_CHANGE in _t, _frame, _form, _url = $('script:last').attr('src'), _qi = _url ? _url.indexOf('?') : -1, _title = _d.title, _silent = FALSE, _loaded = FALSE, _juststart = TRUE, _updating = FALSE, _listeners = {}, _value = _href(); if (_msie) { _version = parseFloat(_agent.substr(_agent.indexOf('MSIE') + 4)); if (_d.documentMode && _d.documentMode != _version) { _version = _d.documentMode != 8 ? 7 : 8; } var pc = _d.onpropertychange; _d.onpropertychange = function() { if (pc) { pc.call(_d); } if (_d.title != _title && _d.title.indexOf('#' + _href()) != -1) { _d.title = _title; } }; } if (_h.navigationMode) { _h.navigationMode = 'compatible'; } if (document.readyState == 'complete') { var interval = setInterval(function() { if ($.address) { _load(); clearInterval(interval); } }, 50); } else { _options(); $(_load); } $(window).bind('popstate', _popstate).bind('unload', _unload); return { bind: function(type, data, fn) { return _bind.apply(this, _array(arguments)); }, unbind: function(type, fn) { return _unbind.apply(this, _array(arguments)); }, init: function(data, fn) { return _bind.apply(this, [INIT].concat(_array(arguments))); }, change: function(data, fn) { return _bind.apply(this, [CHANGE].concat(_array(arguments))); }, internalChange: function(data, fn) { return _bind.apply(this, [INTERNAL_CHANGE].concat(_array(arguments))); }, externalChange: function(data, fn) { return _bind.apply(this, [EXTERNAL_CHANGE].concat(_array(arguments))); }, baseURL: function() { var url = _l.href; if (url.indexOf('#') != -1) { url = url.substr(0, url.indexOf('#')); } if (/\/$/.test(url)) { url = url.substr(0, url.length - 1); } return url; }, autoUpdate: function(value) { if (value !== UNDEFINED) { _opts.autoUpdate = value; return this; } return _opts.autoUpdate; }, history: function(value) { if (value !== UNDEFINED) { _opts.history = value; return this; } return _opts.history; }, state: function(value) { if (value !== UNDEFINED) { _opts.state = value; var hrefState = _hrefState(); if (_opts.state !== UNDEFINED) { if (_h.pushState) { if (hrefState.substr(0, 3) == '/#/') { _l.replace(_opts.state.replace(/^\/$/, '') + hrefState.substr(2)); } } else if (hrefState != '/' && hrefState.replace(/^\/#/, '') != _hrefHash()) { _st(function() { _l.replace(_opts.state.replace(/^\/$/, '') + '/#' + hrefState); }, 1); } } return this; } return _opts.state; }, frames: function(value) { if (value !== UNDEFINED) { _opts.frames = value; _t = _window(); return this; } return _opts.frames; }, strict: function(value) { if (value !== UNDEFINED) { _opts.strict = value; return this; } return _opts.strict; }, tracker: function(value) { if (value !== UNDEFINED) { _opts.tracker = value; return this; } return _opts.tracker; }, wrap: function(value) { if (value !== UNDEFINED) { _opts.wrap = value; return this; } return _opts.wrap; }, update: function() { _updating = TRUE; this.value(_value); _updating = FALSE; return this; }, title: function(value) { if (value !== UNDEFINED) { _st(function() { _title = _d.title = value; if (_juststart && _frame && _frame.contentWindow && _frame.contentWindow.document) { _frame.contentWindow.document.title = value; _juststart = FALSE; } }, 50); return this; } return _d.title; }, value: function(value) { if (value !== UNDEFINED) { value = _strict(value); if (value == '/') { value = ''; } if (_value == value && !_updating) { return; } _value = value; if (_opts.autoUpdate || _updating) { if (_update(TRUE)) { return this; } if (_supportsState()) { _h[_opts.history ? 'pushState' : 'replaceState']({}, '', _opts.state.replace(/\/$/, '') + (_value === '' ? '/' : _value)); } else { _silent = TRUE; if (_webkit) { if (_opts.history) { _l.hash = '#' + _value; } else { _l.replace('#' + _value); } } else if (_value != _href()) { if (_opts.history) { _l.hash = '#' + _value; } else { _l.replace('#' + _value); } } if ((_msie && !_hashchange) && _opts.history) { _st(_html, 50); } if (_webkit) { _st(function(){ _silent = FALSE; }, 1); } else { _silent = FALSE; } } } return this; } return _strict(_value); }, path: function(value) { if (value !== UNDEFINED) { var qs = this.queryString(), hash = this.hash(); this.value(value + (qs ? '?' + qs : '') + (hash ? '#' + hash : '')); return this; } return _strict(_value).split('#')[0].split('?')[0]; }, pathNames: function() { var path = this.path(), names = path.replace(_re, '/').split('/'); if (path.substr(0, 1) == '/' || path.length === 0) { names.splice(0, 1); } if (path.substr(path.length - 1, 1) == '/') { names.splice(names.length - 1, 1); } return names; }, queryString: function(value) { if (value !== UNDEFINED) { var hash = this.hash(); this.value(this.path() + (value ? '?' + value : '') + (hash ? '#' + hash : '')); return this; } var arr = _value.split('?'); return arr.slice(1, arr.length).join('?').split('#')[0]; }, parameter: function(name, value, append) { var i, params; if (value !== UNDEFINED) { var names = this.parameterNames(); params = []; value = value === UNDEFINED || value === NULL ? '' : value.toString(); for (i = 0; i < names.length; i++) { var n = names[i], v = this.parameter(n); if (typeof v == STRING) { v = [v]; } if (n == name) { v = (value === NULL || value === '') ? [] : (append ? v.concat([value]) : [value]); } for (var j = 0; j < v.length; j++) { params.push(n + '=' + v[j]); } } if ($.inArray(name, names) == -1 && value !== NULL && value !== '') { params.push(name + '=' + value); } this.queryString(params.join('&')); return this; } value = this.queryString(); if (value) { var r = []; params = value.split('&'); for (i = 0; i < params.length; i++) { var p = params[i].split('='); if (p[0] == name) { r.push(p.slice(1).join('=')); } } if (r.length !== 0) { return r.length != 1 ? r : r[0]; } } }, parameterNames: function() { var qs = this.queryString(), names = []; if (qs && qs.indexOf('=') != -1) { var params = qs.split('&'); for (var i = 0; i < params.length; i++) { var name = params[i].split('=')[0]; if ($.inArray(name, names) == -1) { names.push(name); } } } return names; }, hash: function(value) { if (value !== UNDEFINED) { this.value(_value.split('#')[0] + (value ? '#' + value : '')); return this; } var arr = _value.split('#'); return arr.slice(1, arr.length).join('#'); } }; })(); $.fn.address = function(fn) { $(this).each(function(index) { if (!$(this).data('address')) { $(this).on('click', function(e) { if (e.shiftKey || e.ctrlKey || e.metaKey || e.which == 2) { return true; } var target = e.currentTarget; if ($(target).is('a')) { e.preventDefault(); var value = fn ? fn.call(target) : /address:/.test($(target).attr('rel')) ? $(target).attr('rel').split('address:')[1].split(' ')[0] : $.address.state() !== undefined && !/^\/?$/.test($.address.state()) ? $(target).attr('href').replace(new RegExp('^(.*' + $.address.state() + '|\\.)'), '') : $(target).attr('href').replace(/^(#\!?|\.)/, ''); $.address.value(value); } }).on('submit', function(e) { var target = e.currentTarget; if ($(target).is('form')) { e.preventDefault(); var action = $(target).attr('action'), value = fn ? fn.call(target) : (action.indexOf('?') != -1 ? action.replace(/&$/, '') : action + '?') + $(target).serialize(); $.address.value(value); } }).data('address', true); } }); return this; }; })(jQuery);
JavaScript
/*! * jQuery twitter bootstrap wizard plugin * Examples and documentation at: http://github.com/VinceG/twitter-bootstrap-wizard * version 1.0 * Requires jQuery v1.3.2 or later * Supports Bootstrap 2.2.x, 2.3.x, 3.0 * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * Authors: Vadim Vincent Gabriel (http://vadimg.com), Jason Gill (www.gilluminate.com) */ ;(function($) { var bootstrapWizardCreate = function(element, options) { var element = $(element); var obj = this; // selector skips any 'li' elements that do not contain a child with a tab data-toggle var baseItemSelector = 'li:has([data-toggle="tab"])'; // Merge options with defaults var $settings = $.extend({}, $.fn.bootstrapWizard.defaults, options); var $activeTab = null; var $navigation = null; this.rebindClick = function(selector, fn) { selector.unbind('click', fn).bind('click', fn); } this.fixNavigationButtons = function() { // Get the current active tab if(!$activeTab.length) { // Select first one $navigation.find('a:first').tab('show'); $activeTab = $navigation.find(baseItemSelector + ':first'); } // See if we're currently in the first/last then disable the previous and last buttons $($settings.previousSelector, element).toggleClass('disabled', (obj.firstIndex() >= obj.currentIndex())); $($settings.nextSelector, element).toggleClass('disabled', (obj.currentIndex() >= obj.navigationLength())); // We are unbinding and rebinding to ensure single firing and no double-click errors obj.rebindClick($($settings.nextSelector, element), obj.next); obj.rebindClick($($settings.previousSelector, element), obj.previous); obj.rebindClick($($settings.lastSelector, element), obj.last); obj.rebindClick($($settings.firstSelector, element), obj.first); if($settings.onTabShow && typeof $settings.onTabShow === 'function' && $settings.onTabShow($activeTab, $navigation, obj.currentIndex())===false){ return false; } }; this.next = function(e) { // If we clicked the last then dont activate this if(element.hasClass('last')) { return false; } if($settings.onNext && typeof $settings.onNext === 'function' && $settings.onNext($activeTab, $navigation, obj.nextIndex())===false){ return false; } // Did we click the last button $index = obj.nextIndex(); if($index > obj.navigationLength()) { } else { $navigation.find(baseItemSelector + ':eq('+$index+') a').tab('show'); } }; this.previous = function(e) { // If we clicked the first then dont activate this if(element.hasClass('first')) { return false; } if($settings.onPrevious && typeof $settings.onPrevious === 'function' && $settings.onPrevious($activeTab, $navigation, obj.previousIndex())===false){ return false; } $index = obj.previousIndex(); if($index < 0) { } else { $navigation.find(baseItemSelector + ':eq('+$index+') a').tab('show'); } }; this.first = function(e) { if($settings.onFirst && typeof $settings.onFirst === 'function' && $settings.onFirst($activeTab, $navigation, obj.firstIndex())===false){ return false; } // If the element is disabled then we won't do anything if(element.hasClass('disabled')) { return false; } $navigation.find(baseItemSelector + ':eq(0) a').tab('show'); }; this.last = function(e) { if($settings.onLast && typeof $settings.onLast === 'function' && $settings.onLast($activeTab, $navigation, obj.lastIndex())===false){ return false; } // If the element is disabled then we won't do anything if(element.hasClass('disabled')) { return false; } $navigation.find(baseItemSelector + ':eq('+obj.navigationLength()+') a').tab('show'); }; this.currentIndex = function() { return $navigation.find(baseItemSelector).index($activeTab); }; this.firstIndex = function() { return 0; }; this.lastIndex = function() { return obj.navigationLength(); }; this.getIndex = function(e) { return $navigation.find(baseItemSelector).index(e); }; this.nextIndex = function() { return $navigation.find(baseItemSelector).index($activeTab) + 1; }; this.previousIndex = function() { return $navigation.find(baseItemSelector).index($activeTab) - 1; }; this.navigationLength = function() { return $navigation.find(baseItemSelector).length - 1; }; this.activeTab = function() { return $activeTab; }; this.nextTab = function() { return $navigation.find(baseItemSelector + ':eq('+(obj.currentIndex()+1)+')').length ? $navigation.find(baseItemSelector + ':eq('+(obj.currentIndex()+1)+')') : null; }; this.previousTab = function() { if(obj.currentIndex() <= 0) { return null; } return $navigation.find(baseItemSelector + ':eq('+parseInt(obj.currentIndex()-1)+')'); }; this.show = function(index) { return element.find(baseItemSelector + ':eq(' + index + ') a').tab('show'); }; this.disable = function(index) { $navigation.find(baseItemSelector + ':eq('+index+')').addClass('disabled'); }; this.enable = function(index) { $navigation.find(baseItemSelector + ':eq('+index+')').removeClass('disabled'); }; this.hide = function(index) { $navigation.find(baseItemSelector + ':eq('+index+')').hide(); }; this.display = function(index) { $navigation.find(baseItemSelector + ':eq('+index+')').show(); }; this.remove = function(args) { var $index = args[0]; var $removeTabPane = typeof args[1] != 'undefined' ? args[1] : false; var $item = $navigation.find(baseItemSelector + ':eq('+$index+')'); // Remove the tab pane first if needed if($removeTabPane) { var $href = $item.find('a').attr('href'); $($href).remove(); } // Remove menu item $item.remove(); }; var innerTabClick = function (e) { // Get the index of the clicked tab var clickedIndex = $navigation.find(baseItemSelector).index($(e.currentTarget).parent(baseItemSelector)); if($settings.onTabClick && typeof $settings.onTabClick === 'function' && $settings.onTabClick($activeTab, $navigation, obj.currentIndex(), clickedIndex)===false){ return false; } }; var innerTabShown = function (e) { // use shown instead of show to help prevent double firing $element = $(e.target).parent(); var nextTab = $navigation.find(baseItemSelector).index($element); // If it's disabled then do not change if($element.hasClass('disabled')) { return false; } if($settings.onTabChange && typeof $settings.onTabChange === 'function' && $settings.onTabChange($activeTab, $navigation, obj.currentIndex(), nextTab)===false){ return false; } $activeTab = $element; // activated tab obj.fixNavigationButtons(); }; this.resetWizard = function() { // remove the existing handlers $('a[data-toggle="tab"]', $navigation).off('click', innerTabClick); $('a[data-toggle="tab"]', $navigation).off('shown shown.bs.tab', innerTabShown); // reset elements based on current state of the DOM $navigation = element.find('ul:first', element); $activeTab = $navigation.find(baseItemSelector + '.active', element); // re-add handlers $('a[data-toggle="tab"]', $navigation).on('click', innerTabClick); $('a[data-toggle="tab"]', $navigation).on('shown shown.bs.tab', innerTabShown); obj.fixNavigationButtons(); }; $navigation = element.find('ul:first', element); $activeTab = $navigation.find(baseItemSelector + '.active', element); if(!$navigation.hasClass($settings.tabClass)) { $navigation.addClass($settings.tabClass); } // Load onInit if($settings.onInit && typeof $settings.onInit === 'function'){ $settings.onInit($activeTab, $navigation, 0); } // Load onShow if($settings.onShow && typeof $settings.onShow === 'function'){ $settings.onShow($activeTab, $navigation, obj.nextIndex()); } $('a[data-toggle="tab"]', $navigation).on('click', innerTabClick); // attach to both shown and shown.bs.tab to support Bootstrap versions 2.3.2 and 3.0.0 $('a[data-toggle="tab"]', $navigation).on('shown shown.bs.tab', innerTabShown); }; $.fn.bootstrapWizard = function(options) { //expose methods if (typeof options == 'string') { var args = Array.prototype.slice.call(arguments, 1) if(args.length === 1) { args.toString(); } return this.data('bootstrapWizard')[options](args); } return this.each(function(index){ var element = $(this); // Return early if this element already has a plugin instance if (element.data('bootstrapWizard')) return; // pass options to plugin constructor var wizard = new bootstrapWizardCreate(element, options); // Store plugin object in this element's data element.data('bootstrapWizard', wizard); }); }; // expose options $.fn.bootstrapWizard.defaults = { tabClass: 'nav nav-pills', nextSelector: '.wizard li.next', previousSelector: '.wizard li.previous', firstSelector: '.wizard li.first', lastSelector: '.wizard li.last', onShow: null, onInit: null, onNext: null, onPrevious: null, onLast: null, onFirst: null, onTabChange: null, onTabClick: null, onTabShow: null }; })(jQuery);
JavaScript
// jquery.pjax.js // copyright chris wanstrath // https://github.com/defunkt/jquery-pjax (function($){ // When called on a container with a selector, fetches the href with // ajax into the container or with the data-pjax attribute on the link // itself. // // Tries to make sure the back button and ctrl+click work the way // you'd expect. // // Exported as $.fn.pjax // // Accepts a jQuery ajax options object that may include these // pjax specific options: // // // container - Where to stick the response body. Usually a String selector. // $(container).html(xhr.responseBody) // (default: current jquery context) // push - Whether to pushState the URL. Defaults to true (of course). // replace - Want to use replaceState instead? That's cool. // // For convenience the second parameter can be either the container or // the options object. // // Returns the jQuery object function fnPjax(selector, container, options) { var context = this return this.on('click.pjax', selector, function(event) { var opts = $.extend({}, optionsFor(container, options)) if (!opts.container) opts.container = $(this).attr('data-pjax') || context handleClick(event, opts) }) } // Public: pjax on click handler // // Exported as $.pjax.click. // // event - "click" jQuery.Event // options - pjax options // // Examples // // $(document).on('click', 'a', $.pjax.click) // // is the same as // $(document).pjax('a') // // $(document).on('click', 'a', function(event) { // var container = $(this).closest('[data-pjax-container]') // $.pjax.click(event, container) // }) // // Returns nothing. function handleClick(event, container, options) { options = optionsFor(container, options) var link = event.currentTarget if (link.tagName.toUpperCase() !== 'A') throw "$.fn.pjax or $.pjax.click requires an anchor element" // Middle click, cmd click, and ctrl click should open // links in a new tab as normal. if ( event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey ) return // Ignore cross origin links if ( location.protocol !== link.protocol || location.hostname !== link.hostname ) return // Ignore anchors on the same page if (link.hash && link.href.replace(link.hash, '') === location.href.replace(location.hash, '')) return // Ignore empty anchor "foo.html#" if (link.href === location.href + '#') return var defaults = { url: link.href, container: $(link).attr('data-pjax'), target: link } var opts = $.extend({}, defaults, options) var clickEvent = $.Event('pjax:click') $(link).trigger(clickEvent, [opts]) if (!clickEvent.isDefaultPrevented()) { pjax(opts) event.preventDefault() } } // Public: pjax on form submit handler // // Exported as $.pjax.submit // // event - "click" jQuery.Event // options - pjax options // // Examples // // $(document).on('submit', 'form', function(event) { // var container = $(this).closest('[data-pjax-container]') // $.pjax.submit(event, container) // }) // // Returns nothing. function handleSubmit(event, container, options) { options = optionsFor(container, options) var form = event.currentTarget if (form.tagName.toUpperCase() !== 'FORM') throw "$.pjax.submit requires a form element" var defaults = { type: form.method.toUpperCase(), url: form.action, data: $(form).serializeArray(), container: $(form).attr('data-pjax'), target: form } pjax($.extend({}, defaults, options)) event.preventDefault() } // Loads a URL with ajax, puts the response body inside a container, // then pushState()'s the loaded URL. // // Works just like $.ajax in that it accepts a jQuery ajax // settings object (with keys like url, type, data, etc). // // Accepts these extra keys: // // container - Where to stick the response body. // $(container).html(xhr.responseBody) // push - Whether to pushState the URL. Defaults to true (of course). // replace - Want to use replaceState instead? That's cool. // // Use it just like $.ajax: // // var xhr = $.pjax({ url: this.href, container: '#main' }) // console.log( xhr.readyState ) // // Returns whatever $.ajax returns. function pjax(options) { options = $.extend(true, {}, $.ajaxSettings, pjax.defaults, options) if ($.isFunction(options.url)) { options.url = options.url() } var target = options.target var hash = parseURL(options.url).hash var context = options.context = findContainerFor(options.container) // We want the browser to maintain two separate internal caches: one // for pjax'd partial page loads and one for normal page loads. // Without adding this secret parameter, some browsers will often // confuse the two. if (!options.data) options.data = {} options.data._pjax = context.selector function fire(type, args) { var event = $.Event(type, { relatedTarget: target }) context.trigger(event, args) return !event.isDefaultPrevented() } var timeoutTimer options.beforeSend = function(xhr, settings) { // No timeout for non-GET requests // Its not safe to request the resource again with a fallback method. if (settings.type !== 'GET') { settings.timeout = 0 } xhr.setRequestHeader('X-PJAX', 'true') xhr.setRequestHeader('X-PJAX-Container', context.selector) if (!fire('pjax:beforeSend', [xhr, settings])) return false if (settings.timeout > 0) { timeoutTimer = setTimeout(function() { if (fire('pjax:timeout', [xhr, options])) xhr.abort('timeout') }, settings.timeout) // Clear timeout setting so jquerys internal timeout isn't invoked settings.timeout = 0 } options.requestUrl = parseURL(settings.url).href } options.complete = function(xhr, textStatus) { if (timeoutTimer) clearTimeout(timeoutTimer) fire('pjax:complete', [xhr, textStatus, options]) fire('pjax:end', [xhr, options]) } options.error = function(xhr, textStatus, errorThrown) { var container = extractContainer("", xhr, options) var allowed = fire('pjax:error', [xhr, textStatus, errorThrown, options]) if (options.type == 'GET' && textStatus !== 'abort' && allowed) { locationReplace(container.url) } } options.success = function(data, status, xhr) { // If $.pjax.defaults.version is a function, invoke it first. // Otherwise it can be a static string. var currentVersion = (typeof $.pjax.defaults.version === 'function') ? $.pjax.defaults.version() : $.pjax.defaults.version var latestVersion = xhr.getResponseHeader('X-PJAX-Version') var container = extractContainer(data, xhr, options) // If there is a layout version mismatch, hard load the new url if (currentVersion && latestVersion && currentVersion !== latestVersion) { locationReplace(container.url) return } // If the new response is missing a body, hard load the page if (!container.contents) { locationReplace(container.url) return } pjax.state = { id: options.id || uniqueId(), url: container.url, title: container.title, container: context.selector, fragment: options.fragment, timeout: options.timeout } if (options.push || options.replace) { window.history.replaceState(pjax.state, container.title, container.url) } // Clear out any focused controls before inserting new page contents. document.activeElement.blur() if (container.title) document.title = container.title context.html(container.contents) // FF bug: Won't autofocus fields that are inserted via JS. // This behavior is incorrect. So if theres no current focus, autofocus // the last field. // // http://www.w3.org/html/wg/drafts/html/master/forms.html var autofocusEl = context.find('input[autofocus], textarea[autofocus]').last()[0] if (autofocusEl && document.activeElement !== autofocusEl) { autofocusEl.focus(); } executeScriptTags(container.scripts) // Scroll to top by default if (typeof options.scrollTo === 'number') $(window).scrollTop(options.scrollTo) // If the URL has a hash in it, make sure the browser // knows to navigate to the hash. if ( hash !== '' ) { // Avoid using simple hash set here. Will add another history // entry. Replace the url with replaceState and scroll to target // by hand. // // window.location.hash = hash var url = parseURL(container.url) url.hash = hash pjax.state.url = url.href window.history.replaceState(pjax.state, container.title, url.href) var target = $(url.hash) if (target.length) $(window).scrollTop(target.offset().top) } fire('pjax:success', [data, status, xhr, options]) } // Initialize pjax.state for the initial page load. Assume we're // using the container and options of the link we're loading for the // back button to the initial page. This ensures good back button // behavior. if (!pjax.state) { pjax.state = { id: uniqueId(), url: window.location.href, title: document.title, container: context.selector, fragment: options.fragment, timeout: options.timeout } window.history.replaceState(pjax.state, document.title) } // Cancel the current request if we're already pjaxing var xhr = pjax.xhr if ( xhr && xhr.readyState < 4) { xhr.onreadystatechange = $.noop xhr.abort() } pjax.options = options var xhr = pjax.xhr = $.ajax(options) if (xhr.readyState > 0) { if (options.push && !options.replace) { // Cache current container element before replacing it cachePush(pjax.state.id, context.clone().contents()) window.history.pushState(null, "", stripPjaxParam(options.requestUrl)) } fire('pjax:start', [xhr, options]) fire('pjax:send', [xhr, options]) } return pjax.xhr } // Public: Reload current page with pjax. // // Returns whatever $.pjax returns. function pjaxReload(container, options) { var defaults = { url: window.location.href, push: false, replace: true, scrollTo: false } return pjax($.extend(defaults, optionsFor(container, options))) } // Internal: Hard replace current state with url. // // Work for around WebKit // https://bugs.webkit.org/show_bug.cgi?id=93506 // // Returns nothing. function locationReplace(url) { window.history.replaceState(null, "", "#") window.location.replace(url) } var initialPop = true var initialURL = window.location.href var initialState = window.history.state // Initialize $.pjax.state if possible // Happens when reloading a page and coming forward from a different // session history. if (initialState && initialState.container) { pjax.state = initialState } // Non-webkit browsers don't fire an initial popstate event if ('state' in window.history) { initialPop = false } // popstate handler takes care of the back and forward buttons // // You probably shouldn't use pjax on pages with other pushState // stuff yet. function onPjaxPopstate(event) { var state = event.state if (state && state.container) { // When coming forward from a separate history session, will get an // initial pop with a state we are already at. Skip reloading the current // page. if (initialPop && initialURL == state.url) return // If popping back to the same state, just skip. // Could be clicking back from hashchange rather than a pushState. if (pjax.state.id === state.id) return var container = $(state.container) if (container.length) { var direction, contents = cacheMapping[state.id] if (pjax.state) { // Since state ids always increase, we can deduce the history // direction from the previous state. direction = pjax.state.id < state.id ? 'forward' : 'back' // Cache current container before replacement and inform the // cache which direction the history shifted. cachePop(direction, pjax.state.id, container.clone().contents()) } var popstateEvent = $.Event('pjax:popstate', { state: state, direction: direction }) container.trigger(popstateEvent) var options = { id: state.id, url: state.url, container: container, push: false, fragment: state.fragment, timeout: state.timeout, scrollTo: false } if (contents) { container.trigger('pjax:start', [null, options]) if (state.title) document.title = state.title container.html(contents) pjax.state = state container.trigger('pjax:end', [null, options]) } else { pjax(options) } // Force reflow/relayout before the browser tries to restore the // scroll position. container[0].offsetHeight } else { locationReplace(location.href) } } initialPop = false } // Fallback version of main pjax function for browsers that don't // support pushState. // // Returns nothing since it retriggers a hard form submission. function fallbackPjax(options) { var url = $.isFunction(options.url) ? options.url() : options.url, method = options.type ? options.type.toUpperCase() : 'GET' var form = $('<form>', { method: method === 'GET' ? 'GET' : 'POST', action: url, style: 'display:none' }) if (method !== 'GET' && method !== 'POST') { form.append($('<input>', { type: 'hidden', name: '_method', value: method.toLowerCase() })) } var data = options.data if (typeof data === 'string') { $.each(data.split('&'), function(index, value) { var pair = value.split('=') form.append($('<input>', {type: 'hidden', name: pair[0], value: pair[1]})) }) } else if (typeof data === 'object') { for (key in data) form.append($('<input>', {type: 'hidden', name: key, value: data[key]})) } $(document.body).append(form) form.submit() } // Internal: Generate unique id for state object. // // Use a timestamp instead of a counter since ids should still be // unique across page loads. // // Returns Number. function uniqueId() { return (new Date).getTime() } // Internal: Strips _pjax param from url // // url - String // // Returns String. function stripPjaxParam(url) { return url .replace(/\?_pjax=[^&]+&?/, '?') .replace(/_pjax=[^&]+&?/, '') .replace(/[\?&]$/, '') } // Internal: Parse URL components and returns a Locationish object. // // url - String URL // // Returns HTMLAnchorElement that acts like Location. function parseURL(url) { var a = document.createElement('a') a.href = url return a } // Internal: Build options Object for arguments. // // For convenience the first parameter can be either the container or // the options object. // // Examples // // optionsFor('#container') // // => {container: '#container'} // // optionsFor('#container', {push: true}) // // => {container: '#container', push: true} // // optionsFor({container: '#container', push: true}) // // => {container: '#container', push: true} // // Returns options Object. function optionsFor(container, options) { // Both container and options if ( container && options ) options.container = container // First argument is options Object else if ( $.isPlainObject(container) ) options = container // Only container else options = {container: container} // Find and validate container if (options.container) options.container = findContainerFor(options.container) return options } // Internal: Find container element for a variety of inputs. // // Because we can't persist elements using the history API, we must be // able to find a String selector that will consistently find the Element. // // container - A selector String, jQuery object, or DOM Element. // // Returns a jQuery object whose context is `document` and has a selector. function findContainerFor(container) { container = $(container) if ( !container.length ) { throw "no pjax container for " + container.selector } else if ( container.selector !== '' && container.context === document ) { return container } else if ( container.attr('id') ) { return $('#' + container.attr('id')) } else { throw "cant get selector for pjax container!" } } // Internal: Filter and find all elements matching the selector. // // Where $.fn.find only matches descendants, findAll will test all the // top level elements in the jQuery object as well. // // elems - jQuery object of Elements // selector - String selector to match // // Returns a jQuery object. function findAll(elems, selector) { return elems.filter(selector).add(elems.find(selector)); } function parseHTML(html) { return $.parseHTML(html, document, true) } // Internal: Extracts container and metadata from response. // // 1. Extracts X-PJAX-URL header if set // 2. Extracts inline <title> tags // 3. Builds response Element and extracts fragment if set // // data - String response data // xhr - XHR response // options - pjax options Object // // Returns an Object with url, title, and contents keys. function extractContainer(data, xhr, options) { var obj = {} // Prefer X-PJAX-URL header if it was set, otherwise fallback to // using the original requested url. obj.url = stripPjaxParam(xhr.getResponseHeader('X-PJAX-URL') || options.requestUrl) // Attempt to parse response html into elements if (/<html/i.test(data)) { var $head = $(parseHTML(data.match(/<head[^>]*>([\s\S.]*)<\/head>/i)[0])) var $body = $(parseHTML(data.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0])) } else { var $head = $body = $(parseHTML(data)) } // If response data is empty, return fast if ($body.length === 0) return obj // If there's a <title> tag in the header, use it as // the page's title. obj.title = findAll($head, 'title').last().text() if (options.fragment) { // If they specified a fragment, look for it in the response // and pull it out. if (options.fragment === 'body') { var $fragment = $body } else { var $fragment = findAll($body, options.fragment).first() } if ($fragment.length) { obj.contents = $fragment.contents() // If there's no title, look for data-title and title attributes // on the fragment if (!obj.title) obj.title = $fragment.attr('title') || $fragment.data('title') } } else if (!/<html/i.test(data)) { obj.contents = $body } // Clean up any <title> tags if (obj.contents) { // Remove any parent title elements obj.contents = obj.contents.not(function() { return $(this).is('title') }) // Then scrub any titles from their descendants obj.contents.find('title').remove() // Gather all script[src] elements obj.scripts = findAll(obj.contents, 'script[src]').remove() obj.contents = obj.contents.not(obj.scripts) } // Trim any whitespace off the title if (obj.title) obj.title = $.trim(obj.title) return obj } // Load an execute scripts using standard script request. // // Avoids jQuery's traditional $.getScript which does a XHR request and // globalEval. // // scripts - jQuery object of script Elements // // Returns nothing. function executeScriptTags(scripts) { if (!scripts) return var existingScripts = $('script[src]') scripts.each(function() { var src = this.src var matchedScripts = existingScripts.filter(function() { return this.src === src }) if (matchedScripts.length) return var script = document.createElement('script') script.type = $(this).attr('type') script.src = $(this).attr('src') document.head.appendChild(script) }) } // Internal: History DOM caching class. var cacheMapping = {} var cacheForwardStack = [] var cacheBackStack = [] // Push previous state id and container contents into the history // cache. Should be called in conjunction with `pushState` to save the // previous container contents. // // id - State ID Number // value - DOM Element to cache // // Returns nothing. function cachePush(id, value) { cacheMapping[id] = value cacheBackStack.push(id) // Remove all entires in forward history stack after pushing // a new page. while (cacheForwardStack.length) delete cacheMapping[cacheForwardStack.shift()] // Trim back history stack to max cache length. while (cacheBackStack.length > pjax.defaults.maxCacheLength) delete cacheMapping[cacheBackStack.shift()] } // Shifts cache from directional history cache. Should be // called on `popstate` with the previous state id and container // contents. // // direction - "forward" or "back" String // id - State ID Number // value - DOM Element to cache // // Returns nothing. function cachePop(direction, id, value) { var pushStack, popStack cacheMapping[id] = value if (direction === 'forward') { pushStack = cacheBackStack popStack = cacheForwardStack } else { pushStack = cacheForwardStack popStack = cacheBackStack } pushStack.push(id) if (id = popStack.pop()) delete cacheMapping[id] } // Public: Find version identifier for the initial page load. // // Returns String version or undefined. function findVersion() { return $('meta').filter(function() { var name = $(this).attr('http-equiv') return name && name.toUpperCase() === 'X-PJAX-VERSION' }).attr('content') } // Install pjax functions on $.pjax to enable pushState behavior. // // Does nothing if already enabled. // // Examples // // $.pjax.enable() // // Returns nothing. function enable() { $.fn.pjax = fnPjax $.pjax = pjax $.pjax.enable = $.noop $.pjax.disable = disable $.pjax.click = handleClick $.pjax.submit = handleSubmit $.pjax.reload = pjaxReload $.pjax.defaults = { timeout: 650, push: true, replace: false, type: 'GET', dataType: 'html', scrollTo: 0, maxCacheLength: 20, version: findVersion } $(window).on('popstate.pjax', onPjaxPopstate) } // Disable pushState behavior. // // This is the case when a browser doesn't support pushState. It is // sometimes useful to disable pushState for debugging on a modern // browser. // // Examples // // $.pjax.disable() // // Returns nothing. function disable() { $.fn.pjax = function() { return this } $.pjax = fallbackPjax $.pjax.enable = enable $.pjax.disable = $.noop $.pjax.click = $.noop $.pjax.submit = $.noop $.pjax.reload = function() { window.location.reload() } $(window).off('popstate.pjax', onPjaxPopstate) } // Add the state property to jQuery's event object so we can use it in // $(window).bind('popstate') if ( $.inArray('state', $.event.props) < 0 ) $.event.props.push('state') // Is pjax supported by this browser? $.support.pjax = window.history && window.history.pushState && window.history.replaceState && // pushState isn't reliable on iOS until 5. !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/) $.support.pjax ? enable() : disable() })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Countdown for jQuery v1.6.3. Written by Keith Wood (kbwood{at}iinet.com.au) January 2008. Available under the MIT (https://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt) license. Please attribute the author if you use it. */ /* Display a countdown timer. Attach it with options like: $('div selector').countdown( {until: new Date(2009, 1 - 1, 1, 0, 0, 0), onExpiry: happyNewYear}); */ (function($) { // Hide scope, no $ conflict /* Countdown manager. */ function Countdown() { this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings // The display texts for the counters labels: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'], // The display texts for the counters if only one labels1: ['Year', 'Month', 'Week', 'Day', 'Hour', 'Minute', 'Second'], compactLabels: ['y', 'm', 'w', 'd'], // The compact texts for the counters whichLabels: null, // Function to determine which labels to use digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], // The digits to display timeSeparator: ':', // Separator for time periods isRTL: false // True for right-to-left languages, false for left-to-right }; this._defaults = { until: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count down to // or numeric for seconds offset, or string for unit offset(s): // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds since: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count up from // or numeric for seconds offset, or string for unit offset(s): // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds timezone: null, // The timezone (hours or minutes from GMT) for the target times, // or null for client local serverSync: null, // A function to retrieve the current server time for synchronisation format: 'dHMS', // Format for display - upper case for always, lower case only if non-zero, // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds layout: '', // Build your own layout for the countdown compact: false, // True to display in a compact format, false for an expanded one significant: 0, // The number of periods with values to show, zero for all description: '', // The description displayed for the countdown expiryUrl: '', // A URL to load upon expiry, replacing the current page expiryText: '', // Text to display upon expiry, replacing the countdown alwaysExpire: false, // True to trigger onExpiry even if never counted down onExpiry: null, // Callback when the countdown expires - // receives no parameters and 'this' is the containing division onTick: null, // Callback when the countdown is updated - // receives int[7] being the breakdown by period (based on format) // and 'this' is the containing division tickInterval: 1 // Interval (seconds) between onTick callbacks }; $.extend(this._defaults, this.regional['']); this._serverSyncs = []; var now = (typeof Date.now == 'function' ? Date.now : function() { return new Date().getTime(); }); var perfAvail = (window.performance && typeof window.performance.now == 'function'); // Shared timer for all countdowns function timerCallBack(timestamp) { var drawStart = (timestamp < 1e12 ? // New HTML5 high resolution timer (perfAvail ? (performance.now() + performance.timing.navigationStart) : now()) : // Integer milliseconds since unix epoch timestamp || now()); if (drawStart - animationStartTime >= 1000) { plugin._updateTargets(); animationStartTime = drawStart; } requestAnimationFrame(timerCallBack); } var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || null; // This is when we expect a fall-back to setInterval as it's much more fluid var animationStartTime = 0; if (!requestAnimationFrame || $.noRequestAnimationFrame) { $.noRequestAnimationFrame = null; setInterval(function() { plugin._updateTargets(); }, 980); // Fall back to good old setInterval } else { animationStartTime = window.animationStartTime || window.webkitAnimationStartTime || window.mozAnimationStartTime || window.oAnimationStartTime || window.msAnimationStartTime || now(); requestAnimationFrame(timerCallBack); } } var Y = 0; // Years var O = 1; // Months var W = 2; // Weeks var D = 3; // Days var H = 4; // Hours var M = 5; // Minutes var S = 6; // Seconds $.extend(Countdown.prototype, { /* Class name added to elements to indicate already configured with countdown. */ markerClassName: 'hasCountdown', /* Name of the data property for instance settings. */ propertyName: 'countdown', /* Class name for the right-to-left marker. */ _rtlClass: 'countdown_rtl', /* Class name for the countdown section marker. */ _sectionClass: 'countdown_section', /* Class name for the period amount marker. */ _amountClass: 'countdown_amount', /* Class name for the countdown row marker. */ _rowClass: 'countdown_row', /* Class name for the holding countdown marker. */ _holdingClass: 'countdown_holding', /* Class name for the showing countdown marker. */ _showClass: 'countdown_show', /* Class name for the description marker. */ _descrClass: 'countdown_descr', /* List of currently active countdown targets. */ _timerTargets: [], /* Override the default settings for all instances of the countdown widget. @param options (object) the new settings to use as defaults */ setDefaults: function(options) { this._resetExtraLabels(this._defaults, options); $.extend(this._defaults, options || {}); }, /* Convert a date/time to UTC. @param tz (number) the hour or minute offset from GMT, e.g. +9, -360 @param year (Date) the date/time in that timezone or (number) the year in that timezone @param month (number, optional) the month (0 - 11) (omit if year is a Date) @param day (number, optional) the day (omit if year is a Date) @param hours (number, optional) the hour (omit if year is a Date) @param mins (number, optional) the minute (omit if year is a Date) @param secs (number, optional) the second (omit if year is a Date) @param ms (number, optional) the millisecond (omit if year is a Date) @return (Date) the equivalent UTC date/time */ UTCDate: function(tz, year, month, day, hours, mins, secs, ms) { if (typeof year == 'object' && year.constructor == Date) { ms = year.getMilliseconds(); secs = year.getSeconds(); mins = year.getMinutes(); hours = year.getHours(); day = year.getDate(); month = year.getMonth(); year = year.getFullYear(); } var d = new Date(); d.setUTCFullYear(year); d.setUTCDate(1); d.setUTCMonth(month || 0); d.setUTCDate(day || 1); d.setUTCHours(hours || 0); d.setUTCMinutes((mins || 0) - (Math.abs(tz) < 30 ? tz * 60 : tz)); d.setUTCSeconds(secs || 0); d.setUTCMilliseconds(ms || 0); return d; }, /* Convert a set of periods into seconds. Averaged for months and years. @param periods (number[7]) the periods per year/month/week/day/hour/minute/second @return (number) the corresponding number of seconds */ periodsToSeconds: function(periods) { return periods[0] * 31557600 + periods[1] * 2629800 + periods[2] * 604800 + periods[3] * 86400 + periods[4] * 3600 + periods[5] * 60 + periods[6]; }, /* Attach the countdown widget to a div. @param target (element) the containing division @param options (object) the initial settings for the countdown */ _attachPlugin: function(target, options) { target = $(target); if (target.hasClass(this.markerClassName)) { return; } var inst = {options: $.extend({}, this._defaults), _periods: [0, 0, 0, 0, 0, 0, 0]}; target.addClass(this.markerClassName).data(this.propertyName, inst); this._optionPlugin(target, options); }, /* Add a target to the list of active ones. @param target (element) the countdown target */ _addTarget: function(target) { if (!this._hasTarget(target)) { this._timerTargets.push(target); } }, /* See if a target is in the list of active ones. @param target (element) the countdown target @return (boolean) true if present, false if not */ _hasTarget: function(target) { return ($.inArray(target, this._timerTargets) > -1); }, /* Remove a target from the list of active ones. @param target (element) the countdown target */ _removeTarget: function(target) { this._timerTargets = $.map(this._timerTargets, function(value) { return (value == target ? null : value); }); // delete entry }, /* Update each active timer target. */ _updateTargets: function() { for (var i = this._timerTargets.length - 1; i >= 0; i--) { this._updateCountdown(this._timerTargets[i]); } }, /* Reconfigure the settings for a countdown div. @param target (element) the control to affect @param options (object) the new options for this instance or (string) an individual property name @param value (any) the individual property value (omit if options is an object or to retrieve the value of a setting) @return (any) if retrieving a value */ _optionPlugin: function(target, options, value) { target = $(target); var inst = target.data(this.propertyName); if (!options || (typeof options == 'string' && value == null)) { // Get option var name = options; options = (inst || {}).options; return (options && name ? options[name] : options); } if (!target.hasClass(this.markerClassName)) { return; } options = options || {}; if (typeof options == 'string') { var name = options; options = {}; options[name] = value; } if (options.layout) { options.layout = options.layout.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); } this._resetExtraLabels(inst.options, options); var timezoneChanged = (inst.options.timezone != options.timezone); $.extend(inst.options, options); this._adjustSettings(target, inst, options.until != null || options.since != null || timezoneChanged); var now = new Date(); if ((inst._since && inst._since < now) || (inst._until && inst._until > now)) { this._addTarget(target[0]); } this._updateCountdown(target, inst); }, /* Redisplay the countdown with an updated display. @param target (jQuery) the containing division @param inst (object) the current settings for this instance */ _updateCountdown: function(target, inst) { var $target = $(target); inst = inst || $target.data(this.propertyName); if (!inst) { return; } $target.html(this._generateHTML(inst)).toggleClass(this._rtlClass, inst.options.isRTL); if ($.isFunction(inst.options.onTick)) { var periods = inst._hold != 'lap' ? inst._periods : this._calculatePeriods(inst, inst._show, inst.options.significant, new Date()); if (inst.options.tickInterval == 1 || this.periodsToSeconds(periods) % inst.options.tickInterval == 0) { inst.options.onTick.apply(target, [periods]); } } var expired = inst._hold != 'pause' && (inst._since ? inst._now.getTime() < inst._since.getTime() : inst._now.getTime() >= inst._until.getTime()); if (expired && !inst._expiring) { inst._expiring = true; if (this._hasTarget(target) || inst.options.alwaysExpire) { this._removeTarget(target); if ($.isFunction(inst.options.onExpiry)) { inst.options.onExpiry.apply(target, []); } if (inst.options.expiryText) { var layout = inst.options.layout; inst.options.layout = inst.options.expiryText; this._updateCountdown(target, inst); inst.options.layout = layout; } if (inst.options.expiryUrl) { window.location = inst.options.expiryUrl; } } inst._expiring = false; } else if (inst._hold == 'pause') { this._removeTarget(target); } $target.data(this.propertyName, inst); }, /* Reset any extra labelsn and compactLabelsn entries if changing labels. @param base (object) the options to be updated @param options (object) the new option values */ _resetExtraLabels: function(base, options) { var changingLabels = false; for (var n in options) { if (n != 'whichLabels' && n.match(/[Ll]abels/)) { changingLabels = true; break; } } if (changingLabels) { for (var n in base) { // Remove custom numbered labels if (n.match(/[Ll]abels[02-9]|compactLabels1/)) { base[n] = null; } } } }, /* Calculate interal settings for an instance. @param target (element) the containing division @param inst (object) the current settings for this instance @param recalc (boolean) true if until or since are set */ _adjustSettings: function(target, inst, recalc) { var now; var serverOffset = 0; var serverEntry = null; for (var i = 0; i < this._serverSyncs.length; i++) { if (this._serverSyncs[i][0] == inst.options.serverSync) { serverEntry = this._serverSyncs[i][1]; break; } } if (serverEntry != null) { serverOffset = (inst.options.serverSync ? serverEntry : 0); now = new Date(); } else { var serverResult = ($.isFunction(inst.options.serverSync) ? inst.options.serverSync.apply(target, []) : null); now = new Date(); serverOffset = (serverResult ? now.getTime() - serverResult.getTime() : 0); this._serverSyncs.push([inst.options.serverSync, serverOffset]); } var timezone = inst.options.timezone; timezone = (timezone == null ? -now.getTimezoneOffset() : timezone); if (recalc || (!recalc && inst._until == null && inst._since == null)) { inst._since = inst.options.since; if (inst._since != null) { inst._since = this.UTCDate(timezone, this._determineTime(inst._since, null)); if (inst._since && serverOffset) { inst._since.setMilliseconds(inst._since.getMilliseconds() + serverOffset); } } inst._until = this.UTCDate(timezone, this._determineTime(inst.options.until, now)); if (serverOffset) { inst._until.setMilliseconds(inst._until.getMilliseconds() + serverOffset); } } inst._show = this._determineShow(inst); }, /* Remove the countdown widget from a div. @param target (element) the containing division */ _destroyPlugin: function(target) { target = $(target); if (!target.hasClass(this.markerClassName)) { return; } this._removeTarget(target[0]); target.removeClass(this.markerClassName).empty().removeData(this.propertyName); }, /* Pause a countdown widget at the current time. Stop it running but remember and display the current time. @param target (element) the containing division */ _pausePlugin: function(target) { this._hold(target, 'pause'); }, /* Pause a countdown widget at the current time. Stop the display but keep the countdown running. @param target (element) the containing division */ _lapPlugin: function(target) { this._hold(target, 'lap'); }, /* Resume a paused countdown widget. @param target (element) the containing division */ _resumePlugin: function(target) { this._hold(target, null); }, /* Pause or resume a countdown widget. @param target (element) the containing division @param hold (string) the new hold setting */ _hold: function(target, hold) { var inst = $.data(target, this.propertyName); if (inst) { if (inst._hold == 'pause' && !hold) { inst._periods = inst._savePeriods; var sign = (inst._since ? '-' : '+'); inst[inst._since ? '_since' : '_until'] = this._determineTime(sign + inst._periods[0] + 'y' + sign + inst._periods[1] + 'o' + sign + inst._periods[2] + 'w' + sign + inst._periods[3] + 'd' + sign + inst._periods[4] + 'h' + sign + inst._periods[5] + 'm' + sign + inst._periods[6] + 's'); this._addTarget(target); } inst._hold = hold; inst._savePeriods = (hold == 'pause' ? inst._periods : null); $.data(target, this.propertyName, inst); this._updateCountdown(target, inst); } }, /* Return the current time periods. @param target (element) the containing division @return (number[7]) the current periods for the countdown */ _getTimesPlugin: function(target) { var inst = $.data(target, this.propertyName); return (!inst ? null : (inst._hold == 'pause' ? inst._savePeriods : (!inst._hold ? inst._periods : this._calculatePeriods(inst, inst._show, inst.options.significant, new Date())))); }, /* A time may be specified as an exact value or a relative one. @param setting (string or number or Date) - the date/time value as a relative or absolute value @param defaultTime (Date) the date/time to use if no other is supplied @return (Date) the corresponding date/time */ _determineTime: function(setting, defaultTime) { var offsetNumeric = function(offset) { // e.g. +300, -2 var time = new Date(); time.setTime(time.getTime() + offset * 1000); return time; }; var offsetString = function(offset) { // e.g. '+2d', '-4w', '+3h +30m' offset = offset.toLowerCase(); var time = new Date(); var year = time.getFullYear(); var month = time.getMonth(); var day = time.getDate(); var hour = time.getHours(); var minute = time.getMinutes(); var second = time.getSeconds(); var pattern = /([+-]?[0-9]+)\s*(s|m|h|d|w|o|y)?/g; var matches = pattern.exec(offset); while (matches) { switch (matches[2] || 's') { case 's': second += parseInt(matches[1], 10); break; case 'm': minute += parseInt(matches[1], 10); break; case 'h': hour += parseInt(matches[1], 10); break; case 'd': day += parseInt(matches[1], 10); break; case 'w': day += parseInt(matches[1], 10) * 7; break; case 'o': month += parseInt(matches[1], 10); day = Math.min(day, plugin._getDaysInMonth(year, month)); break; case 'y': year += parseInt(matches[1], 10); day = Math.min(day, plugin._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day, hour, minute, second, 0); }; var time = (setting == null ? defaultTime : (typeof setting == 'string' ? offsetString(setting) : (typeof setting == 'number' ? offsetNumeric(setting) : setting))); if (time) time.setMilliseconds(0); return time; }, /* Determine the number of days in a month. @param year (number) the year @param month (number) the month @return (number) the days in that month */ _getDaysInMonth: function(year, month) { return 32 - new Date(year, month, 32).getDate(); }, /* Determine which set of labels should be used for an amount. @param num (number) the amount to be displayed @return (number) the set of labels to be used for this amount */ _normalLabels: function(num) { return num; }, /* Generate the HTML to display the countdown widget. @param inst (object) the current settings for this instance @return (string) the new HTML for the countdown display */ _generateHTML: function(inst) { var self = this; // Determine what to show inst._periods = (inst._hold ? inst._periods : this._calculatePeriods(inst, inst._show, inst.options.significant, new Date())); // Show all 'asNeeded' after first non-zero value var shownNonZero = false; var showCount = 0; var sigCount = inst.options.significant; var show = $.extend({}, inst._show); for (var period = Y; period <= S; period++) { shownNonZero |= (inst._show[period] == '?' && inst._periods[period] > 0); show[period] = (inst._show[period] == '?' && !shownNonZero ? null : inst._show[period]); showCount += (show[period] ? 1 : 0); sigCount -= (inst._periods[period] > 0 ? 1 : 0); } var showSignificant = [false, false, false, false, false, false, false]; for (var period = S; period >= Y; period--) { // Determine significant periods if (inst._show[period]) { if (inst._periods[period]) { showSignificant[period] = true; } else { showSignificant[period] = sigCount > 0; sigCount--; } } } var labels = (inst.options.compact ? inst.options.compactLabels : inst.options.labels); var whichLabels = inst.options.whichLabels || this._normalLabels; var showCompact = function(period) { var labelsNum = inst.options['compactLabels' + whichLabels(inst._periods[period])]; return (show[period] ? self._translateDigits(inst, inst._periods[period]) + (labelsNum ? labelsNum[period] : labels[period]) + ' ' : ''); }; var showFull = function(period) { var labelsNum = inst.options['labels' + whichLabels(inst._periods[period])]; return ((!inst.options.significant && show[period]) || (inst.options.significant && showSignificant[period]) ? '<span class="' + plugin._sectionClass + '">' + '<span class="' + plugin._amountClass + '">' + self._translateDigits(inst, inst._periods[period]) + '</span><br/>' + (labelsNum ? labelsNum[period] : labels[period]) + '</span>' : ''); }; return (inst.options.layout ? this._buildLayout(inst, show, inst.options.layout, inst.options.compact, inst.options.significant, showSignificant) : ((inst.options.compact ? // Compact version '<span class="' + this._rowClass + ' ' + this._amountClass + (inst._hold ? ' ' + this._holdingClass : '') + '">' + showCompact(Y) + showCompact(O) + showCompact(W) + showCompact(D) + (show[H] ? this._minDigits(inst, inst._periods[H], 2) : '') + (show[M] ? (show[H] ? inst.options.timeSeparator : '') + this._minDigits(inst, inst._periods[M], 2) : '') + (show[S] ? (show[H] || show[M] ? inst.options.timeSeparator : '') + this._minDigits(inst, inst._periods[S], 2) : '') : // Full version '<span class="' + this._rowClass + ' ' + this._showClass + (inst.options.significant || showCount) + (inst._hold ? ' ' + this._holdingClass : '') + '">' + showFull(Y) + showFull(O) + showFull(W) + showFull(D) + showFull(H) + showFull(M) + showFull(S)) + '</span>' + (inst.options.description ? '<span class="' + this._rowClass + ' ' + this._descrClass + '">' + inst.options.description + '</span>' : ''))); }, /* Construct a custom layout. @param inst (object) the current settings for this instance @param show (string[7]) flags indicating which periods are requested @param layout (string) the customised layout @param compact (boolean) true if using compact labels @param significant (number) the number of periods with values to show, zero for all @param showSignificant (boolean[7]) other periods to show for significance @return (string) the custom HTML */ _buildLayout: function(inst, show, layout, compact, significant, showSignificant) { var labels = inst.options[compact ? 'compactLabels' : 'labels']; var whichLabels = inst.options.whichLabels || this._normalLabels; var labelFor = function(index) { return (inst.options[(compact ? 'compactLabels' : 'labels') + whichLabels(inst._periods[index])] || labels)[index]; }; var digit = function(value, position) { return inst.options.digits[Math.floor(value / position) % 10]; }; var subs = {desc: inst.options.description, sep: inst.options.timeSeparator, yl: labelFor(Y), yn: this._minDigits(inst, inst._periods[Y], 1), ynn: this._minDigits(inst, inst._periods[Y], 2), ynnn: this._minDigits(inst, inst._periods[Y], 3), y1: digit(inst._periods[Y], 1), y10: digit(inst._periods[Y], 10), y100: digit(inst._periods[Y], 100), y1000: digit(inst._periods[Y], 1000), ol: labelFor(O), on: this._minDigits(inst, inst._periods[O], 1), onn: this._minDigits(inst, inst._periods[O], 2), onnn: this._minDigits(inst, inst._periods[O], 3), o1: digit(inst._periods[O], 1), o10: digit(inst._periods[O], 10), o100: digit(inst._periods[O], 100), o1000: digit(inst._periods[O], 1000), wl: labelFor(W), wn: this._minDigits(inst, inst._periods[W], 1), wnn: this._minDigits(inst, inst._periods[W], 2), wnnn: this._minDigits(inst, inst._periods[W], 3), w1: digit(inst._periods[W], 1), w10: digit(inst._periods[W], 10), w100: digit(inst._periods[W], 100), w1000: digit(inst._periods[W], 1000), dl: labelFor(D), dn: this._minDigits(inst, inst._periods[D], 1), dnn: this._minDigits(inst, inst._periods[D], 2), dnnn: this._minDigits(inst, inst._periods[D], 3), d1: digit(inst._periods[D], 1), d10: digit(inst._periods[D], 10), d100: digit(inst._periods[D], 100), d1000: digit(inst._periods[D], 1000), hl: labelFor(H), hn: this._minDigits(inst, inst._periods[H], 1), hnn: this._minDigits(inst, inst._periods[H], 2), hnnn: this._minDigits(inst, inst._periods[H], 3), h1: digit(inst._periods[H], 1), h10: digit(inst._periods[H], 10), h100: digit(inst._periods[H], 100), h1000: digit(inst._periods[H], 1000), ml: labelFor(M), mn: this._minDigits(inst, inst._periods[M], 1), mnn: this._minDigits(inst, inst._periods[M], 2), mnnn: this._minDigits(inst, inst._periods[M], 3), m1: digit(inst._periods[M], 1), m10: digit(inst._periods[M], 10), m100: digit(inst._periods[M], 100), m1000: digit(inst._periods[M], 1000), sl: labelFor(S), sn: this._minDigits(inst, inst._periods[S], 1), snn: this._minDigits(inst, inst._periods[S], 2), snnn: this._minDigits(inst, inst._periods[S], 3), s1: digit(inst._periods[S], 1), s10: digit(inst._periods[S], 10), s100: digit(inst._periods[S], 100), s1000: digit(inst._periods[S], 1000)}; var html = layout; // Replace period containers: {p<}...{p>} for (var i = Y; i <= S; i++) { var period = 'yowdhms'.charAt(i); var re = new RegExp('\\{' + period + '<\\}([\\s\\S]*)\\{' + period + '>\\}', 'g'); html = html.replace(re, ((!significant && show[i]) || (significant && showSignificant[i]) ? '$1' : '')); } // Replace period values: {pn} $.each(subs, function(n, v) { var re = new RegExp('\\{' + n + '\\}', 'g'); html = html.replace(re, v); }); return html; }, /* Ensure a numeric value has at least n digits for display. @param inst (object) the current settings for this instance @param value (number) the value to display @param len (number) the minimum length @return (string) the display text */ _minDigits: function(inst, value, len) { value = '' + value; if (value.length >= len) { return this._translateDigits(inst, value); } value = '0000000000' + value; return this._translateDigits(inst, value.substr(value.length - len)); }, /* Translate digits into other representations. @param inst (object) the current settings for this instance @param value (string) the text to translate @return (string) the translated text */ _translateDigits: function(inst, value) { return ('' + value).replace(/[0-9]/g, function(digit) { return inst.options.digits[digit]; }); }, /* Translate the format into flags for each period. @param inst (object) the current settings for this instance @return (string[7]) flags indicating which periods are requested (?) or required (!) by year, month, week, day, hour, minute, second */ _determineShow: function(inst) { var format = inst.options.format; var show = []; show[Y] = (format.match('y') ? '?' : (format.match('Y') ? '!' : null)); show[O] = (format.match('o') ? '?' : (format.match('O') ? '!' : null)); show[W] = (format.match('w') ? '?' : (format.match('W') ? '!' : null)); show[D] = (format.match('d') ? '?' : (format.match('D') ? '!' : null)); show[H] = (format.match('h') ? '?' : (format.match('H') ? '!' : null)); show[M] = (format.match('m') ? '?' : (format.match('M') ? '!' : null)); show[S] = (format.match('s') ? '?' : (format.match('S') ? '!' : null)); return show; }, /* Calculate the requested periods between now and the target time. @param inst (object) the current settings for this instance @param show (string[7]) flags indicating which periods are requested/required @param significant (number) the number of periods with values to show, zero for all @param now (Date) the current date and time @return (number[7]) the current time periods (always positive) by year, month, week, day, hour, minute, second */ _calculatePeriods: function(inst, show, significant, now) { // Find endpoints inst._now = now; inst._now.setMilliseconds(0); var until = new Date(inst._now.getTime()); if (inst._since) { if (now.getTime() < inst._since.getTime()) { inst._now = now = until; } else { now = inst._since; } } else { until.setTime(inst._until.getTime()); if (now.getTime() > inst._until.getTime()) { inst._now = now = until; } } // Calculate differences by period var periods = [0, 0, 0, 0, 0, 0, 0]; if (show[Y] || show[O]) { // Treat end of months as the same var lastNow = plugin._getDaysInMonth(now.getFullYear(), now.getMonth()); var lastUntil = plugin._getDaysInMonth(until.getFullYear(), until.getMonth()); var sameDay = (until.getDate() == now.getDate() || (until.getDate() >= Math.min(lastNow, lastUntil) && now.getDate() >= Math.min(lastNow, lastUntil))); var getSecs = function(date) { return (date.getHours() * 60 + date.getMinutes()) * 60 + date.getSeconds(); }; var months = Math.max(0, (until.getFullYear() - now.getFullYear()) * 12 + until.getMonth() - now.getMonth() + ((until.getDate() < now.getDate() && !sameDay) || (sameDay && getSecs(until) < getSecs(now)) ? -1 : 0)); periods[Y] = (show[Y] ? Math.floor(months / 12) : 0); periods[O] = (show[O] ? months - periods[Y] * 12 : 0); // Adjust for months difference and end of month if necessary now = new Date(now.getTime()); var wasLastDay = (now.getDate() == lastNow); var lastDay = plugin._getDaysInMonth(now.getFullYear() + periods[Y], now.getMonth() + periods[O]); if (now.getDate() > lastDay) { now.setDate(lastDay); } now.setFullYear(now.getFullYear() + periods[Y]); now.setMonth(now.getMonth() + periods[O]); if (wasLastDay) { now.setDate(lastDay); } } var diff = Math.floor((until.getTime() - now.getTime()) / 1000); var extractPeriod = function(period, numSecs) { periods[period] = (show[period] ? Math.floor(diff / numSecs) : 0); diff -= periods[period] * numSecs; }; extractPeriod(W, 604800); extractPeriod(D, 86400); extractPeriod(H, 3600); extractPeriod(M, 60); extractPeriod(S, 1); if (diff > 0 && !inst._since) { // Round up if left overs var multiplier = [1, 12, 4.3482, 7, 24, 60, 60]; var lastShown = S; var max = 1; for (var period = S; period >= Y; period--) { if (show[period]) { if (periods[lastShown] >= max) { periods[lastShown] = 0; diff = 1; } if (diff > 0) { periods[period]++; diff = 0; lastShown = period; max = 1; } } max *= multiplier[period]; } } if (significant) { // Zero out insignificant periods for (var period = Y; period <= S; period++) { if (significant && periods[period]) { significant--; } else if (!significant) { periods[period] = 0; } } } return periods; } }); // The list of commands that return values and don't permit chaining var getters = ['getTimes']; /* Determine whether a command is a getter and doesn't permit chaining. @param command (string, optional) the command to run @param otherArgs ([], optional) any other arguments for the command @return true if the command is a getter, false if not */ function isNotChained(command, otherArgs) { if (command == 'option' && (otherArgs.length == 0 || (otherArgs.length == 1 && typeof otherArgs[0] == 'string'))) { return true; } return $.inArray(command, getters) > -1; } /* Process the countdown functionality for a jQuery selection. @param options (object) the new settings to use for these instances (optional) or (string) the command to run (optional) @return (jQuery) for chaining further calls or (any) getter value */ $.fn.countdown = function(options) { var otherArgs = Array.prototype.slice.call(arguments, 1); if (isNotChained(options, otherArgs)) { return plugin['_' + options + 'Plugin']. apply(plugin, [this[0]].concat(otherArgs)); } return this.each(function() { if (typeof options == 'string') { if (!plugin['_' + options + 'Plugin']) { throw 'Unknown command: ' + options; } plugin['_' + options + 'Plugin']. apply(plugin, [this].concat(otherArgs)); } else { plugin._attachPlugin(this, options || {}); } }); }; /* Initialise the countdown functionality. */ var plugin = $.countdown = new Countdown(); // Singleton instance })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Traditional Chinese initialisation for the jQuery countdown extension Written by Cloudream (cloudream@gmail.com). */ (function($) { $.countdown.regional['zh-TW'] = { labels: ['年', '月', '周', '天', '時', '分', '秒'], labels1: ['年', '月', '周', '天', '時', '分', '秒'], compactLabels: ['年', '月', '周', '天'], compactLabels1: ['年', '月', '周', '天'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['zh-TW']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Turkish initialisation for the jQuery countdown extension * Written by Bekir Ahmetoğlu (bekir@cerek.com) Aug 2008. */ (function($) { $.countdown.regional['tr'] = { labels: ['Yıl', 'Ay', 'Hafta', 'Gün', 'Saat', 'Dakika', 'Saniye'], labels1: ['Yıl', 'Ay', 'Hafta', 'Gün', 'Saat', 'Dakika', 'Saniye'], compactLabels: ['y', 'a', 'h', 'g'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['tr']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Hungarian initialisation for the jQuery countdown extension * Written by Edmond L. (webmond@gmail.com). */ (function($) { $.countdown.regional['hu'] = { labels: ['Év', 'Hónap', 'Hét', 'Nap', 'Óra', 'Perc', 'Másodperc'], labels1: ['Év', 'Hónap', 'Hét', 'Nap', 'Óra', 'Perc', 'Másodperc'], compactLabels: ['É', 'H', 'Hé', 'N'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['hu']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Malayalam/(Indian>>Kerala) initialisation for the jQuery countdown extension * Written by Harilal.B (harilal1234@gmail.com) Feb 2013. */ (function($) { $.countdown.regional['ml'] = { labels: ['വര്‍ഷങ്ങള്‍', 'മാസങ്ങള്‍', 'ആഴ്ചകള്‍', 'ദിവസങ്ങള്‍', 'മണിക്കൂറുകള്‍', 'മിനിറ്റുകള്‍', 'സെക്കന്റുകള്‍'], labels1: ['വര്‍ഷം', 'മാസം', 'ആഴ്ച', 'ദിവസം', 'മണിക്കൂര്‍', 'മിനിറ്റ്', 'സെക്കന്റ്'], compactLabels: ['വ', 'മ', 'ആ', 'ദി'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], // digits: ['൦', '൧', '൨', '൩', '൪', '൫', '൬', '൭', '൮', '൯'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['ml']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html French initialisation for the jQuery countdown extension Written by Keith Wood (kbwood{at}iinet.com.au) Jan 2008. */ (function($) { $.countdown.regional['fr'] = { labels: ['Années', 'Mois', 'Semaines', 'Jours', 'Heures', 'Minutes', 'Secondes'], labels1: ['Année', 'Mois', 'Semaine', 'Jour', 'Heure', 'Minute', 'Seconde'], compactLabels: ['a', 'm', 's', 'j'], whichLabels: function(amount) { return (amount > 1 ? 0 : 1); }, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['fr']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html German initialisation for the jQuery countdown extension Written by Samuel Wulf. */ (function($) { $.countdown.regional['de'] = { labels: ['Jahre', 'Monate', 'Wochen', 'Tage', 'Stunden', 'Minuten', 'Sekunden'], labels1: ['Jahr', 'Monat', 'Woche', 'Tag', 'Stunde', 'Minute', 'Sekunde'], compactLabels: ['J', 'M', 'W', 'T'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['de']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Slovak initialisation for the jQuery countdown extension * Written by Roman Chlebec (creamd@c64.sk) (2008) */ (function($) { $.countdown.regional['sk'] = { labels: ['Rokov', 'Mesiacov', 'Týždňov', 'Dní', 'Hodín', 'Minút', 'Sekúnd'], labels1: ['Rok', 'Mesiac', 'Týždeň', 'Deň', 'Hodina', 'Minúta', 'Sekunda'], labels2: ['Roky', 'Mesiace', 'Týždne', 'Dni', 'Hodiny', 'Minúty', 'Sekundy'], compactLabels: ['r', 'm', 't', 'd'], whichLabels: function(amount) { return (amount == 1 ? 1 : (amount >= 2 && amount <= 4 ? 2 : 0)); }, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['sk']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Bulgarian initialisation for the jQuery countdown extension * Written by Manol Trendafilov manol@rastermania.com (2010) */ (function($) { $.countdown.regional['bg'] = { labels: ['Години', 'Месеца', 'Седмица', 'Дни', 'Часа', 'Минути', 'Секунди'], labels1: ['Година', 'Месец', 'Седмица', 'Ден', 'Час', 'Минута', 'Секунда'], compactLabels: ['l', 'm', 'n', 'd'], compactLabels1: ['g', 'm', 'n', 'd'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['bg']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Greek initialisation for the jQuery countdown extension Written by Philip. */ (function($) { $.countdown.regional['el'] = { labels: ['Χρόνια', 'Μήνες', 'Εβδομάδες', 'Μέρες', 'Ώρες', 'Λεπτά', 'Δευτερόλεπτα'], labels1: ['Χρόνος', 'Μήνας', 'Εβδομάδα', 'Ημέρα', 'Ώρα', 'Λεπτό', 'Δευτερόλεπτο'], compactLabels: ['Χρ.', 'Μην.', 'Εβδ.', 'Ημ.'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['el']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Hebrew initialisation for the jQuery countdown extension * Translated by Nir Livne, Dec 2008 */ (function($) { $.countdown.regional['he'] = { labels: ['שנים', 'חודשים', 'שבועות', 'ימים', 'שעות', 'דקות', 'שניות'], labels1: ['שנה', 'חודש', 'שבוע', 'יום', 'שעה', 'דקה', 'שנייה'], compactLabels: ['שנ', 'ח', 'שב', 'י'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: true}; $.countdown.setDefaults($.countdown.regional['he']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Serbian Cyrillic initialisation for the jQuery countdown extension * Written by Predrag Leka lp@lemurcake.com (2010) */ (function($) { $.countdown.regional['sr'] = { labels: ['Година', 'Месеци', 'Недеља', 'Дана', 'Часова', 'Минута', 'Секунди'], labels1: ['Година', 'месец', 'Недеља', 'Дан', 'Час', 'Минут', 'Секунда'], labels2: ['Године', 'Месеца', 'Недеље', 'Дана', 'Часа', 'Минута', 'Секунде'], compactLabels: ['г', 'м', 'н', 'д'], whichLabels: function(amount) { return (amount == 1 ? 1 : (amount >= 2 && amount <= 4 ? 2 : 0)); }, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['sr']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Finnish initialisation for the jQuery countdown extension Written by Kalle Vänskä and Juha Suni (juhis.suni@gmail.com). Corrected by Olli. */ (function($) { $.countdown.regional['fi'] = { labels: ['vuotta', 'kuukautta', 'viikkoa', 'päivää', 'tuntia', 'minuuttia', 'sekuntia'], labels1: ['vuosi', 'kuukausi', 'viikko', 'päivä', 'tunti', 'minuutti', 'sekunti'], compactLabels: ['v', 'kk', 'vk', 'pv'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['fi']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Bosnian Latin initialisation for the jQuery countdown extension * Written by Miralem Mehic miralem@mehic.info (2011) */ (function($) { $.countdown.regional['bs'] = { labels: ['Godina', 'Mjeseci', 'Sedmica', 'Dana', 'Sati', 'Minuta', 'Sekundi'], labels1: ['Godina', 'Mjesec', 'Sedmica', 'Dan', 'Sat', 'Minuta', 'Sekunda'], labels2: ['Godine', 'Mjeseca', 'Sedmica', 'Dana', 'Sata', 'Minute', 'Sekunde'], compactLabels: ['g', 'm', 't', 'd'], whichLabels: function(amount) { return (amount == 1 ? 1 : (amount >= 2 && amount <= 4 ? 2 : 0)); }, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['bs']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Romanian initialisation for the jQuery countdown extension * Written by Edmond L. (webmond@gmail.com). */ (function($) { $.countdown.regional['ro'] = { labels: ['Ani', 'Luni', 'Saptamani', 'Zile', 'Ore', 'Minute', 'Secunde'], labels1: ['An', 'Luna', 'Saptamana', 'Ziua', 'Ora', 'Minutul', 'Secunda'], compactLabels: ['A', 'L', 'S', 'Z'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['ro']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Uzbek initialisation for the jQuery countdown extension * Written by Alisher U. (ulugbekov{at}gmail.com) August 2012. */ (function($) { $.countdown.regional['uz'] = { labels: ['Yil', 'Oy', 'Hafta', 'Kun', 'Soat', 'Daqiqa', 'Soniya'], labels1: ['Yil', 'Oy', 'Hafta', 'Kun', 'Soat', 'Daqiqa', 'Soniya'], compactLabels: ['y', 'o', 'h', 'k'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['uz']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Danish initialisation for the jQuery countdown extension Written by Buch (admin@buch90.dk). */ (function($) { $.countdown.regional['da'] = { labels: ['År', 'Måneder', 'Uger', 'Dage', 'Timer', 'Minutter', 'Sekunder'], labels1: ['År', 'Månad', 'Uge', 'Dag', 'Time', 'Minut', 'Sekund'], compactLabels: ['Å', 'M', 'U', 'D'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['da']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Russian initialisation for the jQuery countdown extension * Written by Sergey K. (xslade{at}gmail.com) June 2010. */ (function($) { $.countdown.regional['ru'] = { labels: ['Лет', 'Месяцев', 'Недель', 'Дней', 'Часов', 'Минут', 'Секунд'], labels1: ['Год', 'Месяц', 'Неделя', 'День', 'Час', 'Минута', 'Секунда'], labels2: ['Года', 'Месяца', 'Недели', 'Дня', 'Часа', 'Минуты', 'Секунды'], compactLabels: ['л', 'м', 'н', 'д'], compactLabels1: ['г', 'м', 'н', 'д'], whichLabels: function(amount) { var units = amount % 10; var tens = Math.floor((amount % 100) / 10); return (amount == 1 ? 1 : (units >= 2 && units <= 4 && tens != 1 ? 2 : (units == 1 && tens != 1 ? 1 : 0))); }, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['ru']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Slovenian localisation for the jQuery countdown extension * Written by Borut Tomažin (debijan{at}gmail.com) (2011) */ (function($) { $.countdown.regional['sl'] = { labels: ['Let', 'Mesecev', 'Tednov', 'Dni', 'Ur', 'Minut', 'Sekund'], labels1: ['Leto', 'Mesec', 'Teden', 'Dan', 'Ura', 'Minuta', 'Sekunda'], compactLabels: ['l', 'm', 't', 'd'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['sl']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Estonian initialisation for the jQuery countdown extension Written by Helmer <helmer{at}city.ee> */ (function($) { $.countdown.regional['et'] = { labels: ['Aastat', 'Kuud', 'Nädalat', 'Päeva', 'Tundi', 'Minutit', 'Sekundit'], labels1: ['Aasta', 'Kuu', 'Nädal', 'Päev', 'Tund', 'Minut', 'Sekund'], compactLabels: ['a', 'k', 'n', 'p'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['et']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Galician initialisation for the jQuery countdown extension * Written by Moncho Pena ramon.pena.rodriguez@gmail.com (2009) and Angel Farrapeira */ (function($) { $.countdown.regional['gl'] = { labels: ['Anos', 'Meses', 'Semanas', 'Días', 'Horas', 'Minutos', 'Segundos'], labels1: ['Ano', 'Mes', 'Semana', 'Día', 'Hora', 'Minuto', 'Segundo'], compactLabels: ['a', 'm', 's', 'g'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['gl']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Arabic (عربي) initialisation for the jQuery countdown extension Translated by Talal Al Asmari (talal@psdgroups.com), April 2009. */ (function($) { $.countdown.regional['ar'] = { labels: ['سنوات','أشهر','أسابيع','أيام','ساعات','دقائق','ثواني'], labels1: ['سنة','شهر','أسبوع','يوم','ساعة','دقيقة','ثانية'], compactLabels: ['س', 'ش', 'أ', 'ي'], whichLabels: null, digits: ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'], timeSeparator: ':', isRTL: true}; $.countdown.setDefaults($.countdown.regional['ar']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Kannada initialization for the jQuery countdown extension * Written by Guru Chaturvedi guru@gangarasa.com (2011) */ (function($) { $.countdown.regional['kn'] = { labels: ['ವರ್ಷಗಳು', 'ತಿಂಗಳು', 'ವಾರಗಳು', 'ದಿನಗಳು', 'ಘಂಟೆಗಳು', 'ನಿಮಿಷಗಳು', 'ಕ್ಷಣಗಳು'], labels1: ['ವರ್ಷ', 'ತಿಂಗಳು', 'ವಾರ', 'ದಿನ', 'ಘಂಟೆ', 'ನಿಮಿಷ', 'ಕ್ಷಣ'], compactLabels: ['ವ', 'ತಿ', 'ವಾ', 'ದಿ'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['kn']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Simplified Chinese initialisation for the jQuery countdown extension Written by Cloudream (cloudream@gmail.com). */ (function($) { $.countdown.regional['zh-CN'] = { labels: ['年', '月', '周', '天', '时', '分', '秒'], labels1: ['年', '月', '周', '天', '时', '分', '秒'], compactLabels: ['年', '月', '周', '天'], compactLabels1: ['年', '月', '周', '天'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['zh-CN']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Spanish initialisation for the jQuery countdown extension * Written by Sergio Carracedo Martinez webmaster@neodisenoweb.com (2008) */ (function($) { $.countdown.regional['es'] = { labels: ['Años', 'Meses', 'Semanas', 'Días', 'Horas', 'Minutos', 'Segundos'], labels1: ['Año', 'Mes', 'Semana', 'Día', 'Hora', 'Minuto', 'Segundo'], compactLabels: ['a', 'm', 's', 'g'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['es']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Dutch initialisation for the jQuery countdown extension Written by Mathias Bynens <http://mathiasbynens.be/> Mar 2008. */ (function($) { $.countdown.regional['nl'] = { labels: ['Jaren', 'Maanden', 'Weken', 'Dagen', 'Uren', 'Minuten', 'Seconden'], labels1: ['Jaar', 'Maand', 'Week', 'Dag', 'Uur', 'Minuut', 'Seconde'], compactLabels: ['j', 'm', 'w', 'd'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['nl']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Serbian Latin initialisation for the jQuery countdown extension * Written by Predrag Leka lp@lemurcake.com (2010) */ (function($) { $.countdown.regional['sr-SR'] = { labels: ['Godina', 'Meseci', 'Nedelja', 'Dana', 'Časova', 'Minuta', 'Sekundi'], labels1: ['Godina', 'Mesec', 'Nedelja', 'Dan', 'Čas', 'Minut', 'Sekunda'], labels2: ['Godine', 'Meseca', 'Nedelje', 'Dana', 'Časa', 'Minuta', 'Sekunde'], compactLabels: ['g', 'm', 'n', 'd'], whichLabels: function(amount) { return (amount == 1 ? 1 : (amount >= 2 && amount <= 4 ? 2 : 0)); }, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['sr-SR']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Croatian Latin initialisation for the jQuery countdown extension * Written by Dejan Broz info@hqfactory.com (2011) */ (function($) { $.countdown.regional['hr'] = { labels: ['Godina', 'Mjeseci', 'Tjedana', 'Dana', 'Sati', 'Minuta', 'Sekundi'], labels1: ['Godina', 'Mjesec', 'Tjedan', 'Dan', 'Sat', 'Minuta', 'Sekunda'], labels2: ['Godine', 'Mjeseca', 'Tjedna', 'Dana', 'Sata', 'Minute', 'Sekunde'], compactLabels: ['g', 'm', 't', 'd'], whichLabels: function(amount) { return (amount == 1 ? 1 : (amount >= 2 && amount <= 4 ? 2 : 0)); }, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['hr']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Vietnamese initialisation for the jQuery countdown extension * Written by Pham Tien Hung phamtienhung@gmail.com (2010) */ (function($) { $.countdown.regional['vi'] = { labels: ['Năm', 'Tháng', 'Tuần', 'Ngày', 'Giờ', 'Phút', 'Giây'], labels1: ['Năm', 'Tháng', 'Tuần', 'Ngày', 'Giờ', 'Phút', 'Giây'], compactLabels: ['năm', 'th', 'tu', 'ng'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['vi']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Latvian initialisation for the jQuery countdown extension * Written by Jānis Peisenieks janis.peisenieks@gmail.com (2010) */ (function($) { $.countdown.regional['lv'] = { labels: ['Gadi', 'Mēneši', 'Nedēļas', 'Dienas', 'Stundas', 'Minūtes', 'Sekundes'], labels1: ['Gads', 'Mēnesis', 'Nedēļa', 'Diena', 'Stunda', 'Minūte', 'Sekunde'], compactLabels: ['l', 'm', 'n', 'd'], compactLabels1: ['g', 'm', 'n', 'd'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['lv']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Lithuanian localisation for the jQuery countdown extension * Written by Moacir P. de Sá Pereira (moacir{at}gmail.com) (2009) */ (function($) { $.countdown.regional['lt'] = { labels: ['Metų', 'Mėnesių', 'Savaičių', 'Dienų', 'Valandų', 'Minučių', 'Sekundžių'], labels1: ['Metai', 'Mėnuo', 'Savaitė', 'Diena', 'Valanda', 'Minutė', 'Sekundė'], compactLabels: ['m', 'm', 's', 'd'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['lt']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Norwegian Bokmål translation Written by Kristian Ravnevand */ (function($) { $.countdown.regional['nb'] = { labels: ['År', 'Måneder', 'Uker', 'Dager', 'Timer', 'Minutter', 'Sekunder'], labels1: ['År', 'Måned', 'Uke', 'Dag', 'Time', 'Minutt', 'Sekund'], compactLabels: ['Å', 'M', 'U', 'D'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['nb']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Indonesian initialisation for the jQuery countdown extension Written by Erwin Yonathan Jan 2009. */ (function($) { $.countdown.regional['id'] = { labels: ['tahun', 'bulan', 'minggu', 'hari', 'jam', 'menit', 'detik'], labels1: ['tahun', 'bulan', 'minggu', 'hari', 'jam', 'menit', 'detik'], compactLabels: ['t', 'b', 'm', 'h'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['id']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Japanese initialisation for the jQuery countdown extension Written by Ken Ishimoto (ken@ksroom.com) Aug 2009. */ (function($) { $.countdown.regional['ja'] = { labels: ['年', '月', '週', '日', '時', '分', '秒'], labels1: ['年', '月', '週', '日', '時', '分', '秒'], compactLabels: ['年', '月', '週', '日'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['ja']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Countdown for jQuery v1.6.3. Written by Keith Wood (kbwood{at}iinet.com.au) January 2008. Available under the MIT (https://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt) license. Please attribute the author if you use it. */ /* Display a countdown timer. Attach it with options like: $('div selector').countdown( {until: new Date(2009, 1 - 1, 1, 0, 0, 0), onExpiry: happyNewYear}); */ (function($) { // Hide scope, no $ conflict /* Countdown manager. */ function Countdown() { this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings // The display texts for the counters labels: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'], // The display texts for the counters if only one labels1: ['Year', 'Month', 'Week', 'Day', 'Hour', 'Minute', 'Second'], compactLabels: ['y', 'm', 'w', 'd'], // The compact texts for the counters whichLabels: null, // Function to determine which labels to use digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], // The digits to display timeSeparator: ':', // Separator for time periods isRTL: false // True for right-to-left languages, false for left-to-right }; this._defaults = { until: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count down to // or numeric for seconds offset, or string for unit offset(s): // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds since: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count up from // or numeric for seconds offset, or string for unit offset(s): // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds timezone: null, // The timezone (hours or minutes from GMT) for the target times, // or null for client local serverSync: null, // A function to retrieve the current server time for synchronisation format: 'dHMS', // Format for display - upper case for always, lower case only if non-zero, // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds layout: '', // Build your own layout for the countdown compact: false, // True to display in a compact format, false for an expanded one significant: 0, // The number of periods with values to show, zero for all description: '', // The description displayed for the countdown expiryUrl: '', // A URL to load upon expiry, replacing the current page expiryText: '', // Text to display upon expiry, replacing the countdown alwaysExpire: false, // True to trigger onExpiry even if never counted down onExpiry: null, // Callback when the countdown expires - // receives no parameters and 'this' is the containing division onTick: null, // Callback when the countdown is updated - // receives int[7] being the breakdown by period (based on format) // and 'this' is the containing division tickInterval: 1 // Interval (seconds) between onTick callbacks }; $.extend(this._defaults, this.regional['']); this._serverSyncs = []; var now = (typeof Date.now == 'function' ? Date.now : function() { return new Date().getTime(); }); var perfAvail = (window.performance && typeof window.performance.now == 'function'); // Shared timer for all countdowns function timerCallBack(timestamp) { var drawStart = (timestamp < 1e12 ? // New HTML5 high resolution timer (perfAvail ? (performance.now() + performance.timing.navigationStart) : now()) : // Integer milliseconds since unix epoch timestamp || now()); if (drawStart - animationStartTime >= 1000) { plugin._updateTargets(); animationStartTime = drawStart; } requestAnimationFrame(timerCallBack); } var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || null; // This is when we expect a fall-back to setInterval as it's much more fluid var animationStartTime = 0; if (!requestAnimationFrame || $.noRequestAnimationFrame) { $.noRequestAnimationFrame = null; setInterval(function() { plugin._updateTargets(); }, 980); // Fall back to good old setInterval } else { animationStartTime = window.animationStartTime || window.webkitAnimationStartTime || window.mozAnimationStartTime || window.oAnimationStartTime || window.msAnimationStartTime || now(); requestAnimationFrame(timerCallBack); } } var Y = 0; // Years var O = 1; // Months var W = 2; // Weeks var D = 3; // Days var H = 4; // Hours var M = 5; // Minutes var S = 6; // Seconds $.extend(Countdown.prototype, { /* Class name added to elements to indicate already configured with countdown. */ markerClassName: 'hasCountdown', /* Name of the data property for instance settings. */ propertyName: 'countdown', /* Class name for the right-to-left marker. */ _rtlClass: 'countdown_rtl', /* Class name for the countdown section marker. */ _sectionClass: 'countdown_section', /* Class name for the period amount marker. */ _amountClass: 'countdown_amount', /* Class name for the countdown row marker. */ _rowClass: 'countdown_row', /* Class name for the holding countdown marker. */ _holdingClass: 'countdown_holding', /* Class name for the showing countdown marker. */ _showClass: 'countdown_show', /* Class name for the description marker. */ _descrClass: 'countdown_descr', /* List of currently active countdown targets. */ _timerTargets: [], /* Override the default settings for all instances of the countdown widget. @param options (object) the new settings to use as defaults */ setDefaults: function(options) { this._resetExtraLabels(this._defaults, options); $.extend(this._defaults, options || {}); }, /* Convert a date/time to UTC. @param tz (number) the hour or minute offset from GMT, e.g. +9, -360 @param year (Date) the date/time in that timezone or (number) the year in that timezone @param month (number, optional) the month (0 - 11) (omit if year is a Date) @param day (number, optional) the day (omit if year is a Date) @param hours (number, optional) the hour (omit if year is a Date) @param mins (number, optional) the minute (omit if year is a Date) @param secs (number, optional) the second (omit if year is a Date) @param ms (number, optional) the millisecond (omit if year is a Date) @return (Date) the equivalent UTC date/time */ UTCDate: function(tz, year, month, day, hours, mins, secs, ms) { if (typeof year == 'object' && year.constructor == Date) { ms = year.getMilliseconds(); secs = year.getSeconds(); mins = year.getMinutes(); hours = year.getHours(); day = year.getDate(); month = year.getMonth(); year = year.getFullYear(); } var d = new Date(); d.setUTCFullYear(year); d.setUTCDate(1); d.setUTCMonth(month || 0); d.setUTCDate(day || 1); d.setUTCHours(hours || 0); d.setUTCMinutes((mins || 0) - (Math.abs(tz) < 30 ? tz * 60 : tz)); d.setUTCSeconds(secs || 0); d.setUTCMilliseconds(ms || 0); return d; }, /* Convert a set of periods into seconds. Averaged for months and years. @param periods (number[7]) the periods per year/month/week/day/hour/minute/second @return (number) the corresponding number of seconds */ periodsToSeconds: function(periods) { return periods[0] * 31557600 + periods[1] * 2629800 + periods[2] * 604800 + periods[3] * 86400 + periods[4] * 3600 + periods[5] * 60 + periods[6]; }, /* Attach the countdown widget to a div. @param target (element) the containing division @param options (object) the initial settings for the countdown */ _attachPlugin: function(target, options) { target = $(target); if (target.hasClass(this.markerClassName)) { return; } var inst = {options: $.extend({}, this._defaults), _periods: [0, 0, 0, 0, 0, 0, 0]}; target.addClass(this.markerClassName).data(this.propertyName, inst); this._optionPlugin(target, options); }, /* Add a target to the list of active ones. @param target (element) the countdown target */ _addTarget: function(target) { if (!this._hasTarget(target)) { this._timerTargets.push(target); } }, /* See if a target is in the list of active ones. @param target (element) the countdown target @return (boolean) true if present, false if not */ _hasTarget: function(target) { return ($.inArray(target, this._timerTargets) > -1); }, /* Remove a target from the list of active ones. @param target (element) the countdown target */ _removeTarget: function(target) { this._timerTargets = $.map(this._timerTargets, function(value) { return (value == target ? null : value); }); // delete entry }, /* Update each active timer target. */ _updateTargets: function() { for (var i = this._timerTargets.length - 1; i >= 0; i--) { this._updateCountdown(this._timerTargets[i]); } }, /* Reconfigure the settings for a countdown div. @param target (element) the control to affect @param options (object) the new options for this instance or (string) an individual property name @param value (any) the individual property value (omit if options is an object or to retrieve the value of a setting) @return (any) if retrieving a value */ _optionPlugin: function(target, options, value) { target = $(target); var inst = target.data(this.propertyName); if (!options || (typeof options == 'string' && value == null)) { // Get option var name = options; options = (inst || {}).options; return (options && name ? options[name] : options); } if (!target.hasClass(this.markerClassName)) { return; } options = options || {}; if (typeof options == 'string') { var name = options; options = {}; options[name] = value; } if (options.layout) { options.layout = options.layout.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); } this._resetExtraLabels(inst.options, options); var timezoneChanged = (inst.options.timezone != options.timezone); $.extend(inst.options, options); this._adjustSettings(target, inst, options.until != null || options.since != null || timezoneChanged); var now = new Date(); if ((inst._since && inst._since < now) || (inst._until && inst._until > now)) { this._addTarget(target[0]); } this._updateCountdown(target, inst); }, /* Redisplay the countdown with an updated display. @param target (jQuery) the containing division @param inst (object) the current settings for this instance */ _updateCountdown: function(target, inst) { var $target = $(target); inst = inst || $target.data(this.propertyName); if (!inst) { return; } $target.html(this._generateHTML(inst)).toggleClass(this._rtlClass, inst.options.isRTL); if ($.isFunction(inst.options.onTick)) { var periods = inst._hold != 'lap' ? inst._periods : this._calculatePeriods(inst, inst._show, inst.options.significant, new Date()); if (inst.options.tickInterval == 1 || this.periodsToSeconds(periods) % inst.options.tickInterval == 0) { inst.options.onTick.apply(target, [periods]); } } var expired = inst._hold != 'pause' && (inst._since ? inst._now.getTime() < inst._since.getTime() : inst._now.getTime() >= inst._until.getTime()); if (expired && !inst._expiring) { inst._expiring = true; if (this._hasTarget(target) || inst.options.alwaysExpire) { this._removeTarget(target); if ($.isFunction(inst.options.onExpiry)) { inst.options.onExpiry.apply(target, []); } if (inst.options.expiryText) { var layout = inst.options.layout; inst.options.layout = inst.options.expiryText; this._updateCountdown(target, inst); inst.options.layout = layout; } if (inst.options.expiryUrl) { window.location = inst.options.expiryUrl; } } inst._expiring = false; } else if (inst._hold == 'pause') { this._removeTarget(target); } $target.data(this.propertyName, inst); }, /* Reset any extra labelsn and compactLabelsn entries if changing labels. @param base (object) the options to be updated @param options (object) the new option values */ _resetExtraLabels: function(base, options) { var changingLabels = false; for (var n in options) { if (n != 'whichLabels' && n.match(/[Ll]abels/)) { changingLabels = true; break; } } if (changingLabels) { for (var n in base) { // Remove custom numbered labels if (n.match(/[Ll]abels[02-9]|compactLabels1/)) { base[n] = null; } } } }, /* Calculate interal settings for an instance. @param target (element) the containing division @param inst (object) the current settings for this instance @param recalc (boolean) true if until or since are set */ _adjustSettings: function(target, inst, recalc) { var now; var serverOffset = 0; var serverEntry = null; for (var i = 0; i < this._serverSyncs.length; i++) { if (this._serverSyncs[i][0] == inst.options.serverSync) { serverEntry = this._serverSyncs[i][1]; break; } } if (serverEntry != null) { serverOffset = (inst.options.serverSync ? serverEntry : 0); now = new Date(); } else { var serverResult = ($.isFunction(inst.options.serverSync) ? inst.options.serverSync.apply(target, []) : null); now = new Date(); serverOffset = (serverResult ? now.getTime() - serverResult.getTime() : 0); this._serverSyncs.push([inst.options.serverSync, serverOffset]); } var timezone = inst.options.timezone; timezone = (timezone == null ? -now.getTimezoneOffset() : timezone); if (recalc || (!recalc && inst._until == null && inst._since == null)) { inst._since = inst.options.since; if (inst._since != null) { inst._since = this.UTCDate(timezone, this._determineTime(inst._since, null)); if (inst._since && serverOffset) { inst._since.setMilliseconds(inst._since.getMilliseconds() + serverOffset); } } inst._until = this.UTCDate(timezone, this._determineTime(inst.options.until, now)); if (serverOffset) { inst._until.setMilliseconds(inst._until.getMilliseconds() + serverOffset); } } inst._show = this._determineShow(inst); }, /* Remove the countdown widget from a div. @param target (element) the containing division */ _destroyPlugin: function(target) { target = $(target); if (!target.hasClass(this.markerClassName)) { return; } this._removeTarget(target[0]); target.removeClass(this.markerClassName).empty().removeData(this.propertyName); }, /* Pause a countdown widget at the current time. Stop it running but remember and display the current time. @param target (element) the containing division */ _pausePlugin: function(target) { this._hold(target, 'pause'); }, /* Pause a countdown widget at the current time. Stop the display but keep the countdown running. @param target (element) the containing division */ _lapPlugin: function(target) { this._hold(target, 'lap'); }, /* Resume a paused countdown widget. @param target (element) the containing division */ _resumePlugin: function(target) { this._hold(target, null); }, /* Pause or resume a countdown widget. @param target (element) the containing division @param hold (string) the new hold setting */ _hold: function(target, hold) { var inst = $.data(target, this.propertyName); if (inst) { if (inst._hold == 'pause' && !hold) { inst._periods = inst._savePeriods; var sign = (inst._since ? '-' : '+'); inst[inst._since ? '_since' : '_until'] = this._determineTime(sign + inst._periods[0] + 'y' + sign + inst._periods[1] + 'o' + sign + inst._periods[2] + 'w' + sign + inst._periods[3] + 'd' + sign + inst._periods[4] + 'h' + sign + inst._periods[5] + 'm' + sign + inst._periods[6] + 's'); this._addTarget(target); } inst._hold = hold; inst._savePeriods = (hold == 'pause' ? inst._periods : null); $.data(target, this.propertyName, inst); this._updateCountdown(target, inst); } }, /* Return the current time periods. @param target (element) the containing division @return (number[7]) the current periods for the countdown */ _getTimesPlugin: function(target) { var inst = $.data(target, this.propertyName); return (!inst ? null : (inst._hold == 'pause' ? inst._savePeriods : (!inst._hold ? inst._periods : this._calculatePeriods(inst, inst._show, inst.options.significant, new Date())))); }, /* A time may be specified as an exact value or a relative one. @param setting (string or number or Date) - the date/time value as a relative or absolute value @param defaultTime (Date) the date/time to use if no other is supplied @return (Date) the corresponding date/time */ _determineTime: function(setting, defaultTime) { var offsetNumeric = function(offset) { // e.g. +300, -2 var time = new Date(); time.setTime(time.getTime() + offset * 1000); return time; }; var offsetString = function(offset) { // e.g. '+2d', '-4w', '+3h +30m' offset = offset.toLowerCase(); var time = new Date(); var year = time.getFullYear(); var month = time.getMonth(); var day = time.getDate(); var hour = time.getHours(); var minute = time.getMinutes(); var second = time.getSeconds(); var pattern = /([+-]?[0-9]+)\s*(s|m|h|d|w|o|y)?/g; var matches = pattern.exec(offset); while (matches) { switch (matches[2] || 's') { case 's': second += parseInt(matches[1], 10); break; case 'm': minute += parseInt(matches[1], 10); break; case 'h': hour += parseInt(matches[1], 10); break; case 'd': day += parseInt(matches[1], 10); break; case 'w': day += parseInt(matches[1], 10) * 7; break; case 'o': month += parseInt(matches[1], 10); day = Math.min(day, plugin._getDaysInMonth(year, month)); break; case 'y': year += parseInt(matches[1], 10); day = Math.min(day, plugin._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day, hour, minute, second, 0); }; var time = (setting == null ? defaultTime : (typeof setting == 'string' ? offsetString(setting) : (typeof setting == 'number' ? offsetNumeric(setting) : setting))); if (time) time.setMilliseconds(0); return time; }, /* Determine the number of days in a month. @param year (number) the year @param month (number) the month @return (number) the days in that month */ _getDaysInMonth: function(year, month) { return 32 - new Date(year, month, 32).getDate(); }, /* Determine which set of labels should be used for an amount. @param num (number) the amount to be displayed @return (number) the set of labels to be used for this amount */ _normalLabels: function(num) { return num; }, /* Generate the HTML to display the countdown widget. @param inst (object) the current settings for this instance @return (string) the new HTML for the countdown display */ _generateHTML: function(inst) { var self = this; // Determine what to show inst._periods = (inst._hold ? inst._periods : this._calculatePeriods(inst, inst._show, inst.options.significant, new Date())); // Show all 'asNeeded' after first non-zero value var shownNonZero = false; var showCount = 0; var sigCount = inst.options.significant; var show = $.extend({}, inst._show); for (var period = Y; period <= S; period++) { shownNonZero |= (inst._show[period] == '?' && inst._periods[period] > 0); show[period] = (inst._show[period] == '?' && !shownNonZero ? null : inst._show[period]); showCount += (show[period] ? 1 : 0); sigCount -= (inst._periods[period] > 0 ? 1 : 0); } var showSignificant = [false, false, false, false, false, false, false]; for (var period = S; period >= Y; period--) { // Determine significant periods if (inst._show[period]) { if (inst._periods[period]) { showSignificant[period] = true; } else { showSignificant[period] = sigCount > 0; sigCount--; } } } var labels = (inst.options.compact ? inst.options.compactLabels : inst.options.labels); var whichLabels = inst.options.whichLabels || this._normalLabels; var showCompact = function(period) { var labelsNum = inst.options['compactLabels' + whichLabels(inst._periods[period])]; return (show[period] ? self._translateDigits(inst, inst._periods[period]) + (labelsNum ? labelsNum[period] : labels[period]) + ' ' : ''); }; var showFull = function(period) { var labelsNum = inst.options['labels' + whichLabels(inst._periods[period])]; return ((!inst.options.significant && show[period]) || (inst.options.significant && showSignificant[period]) ? '<span class="' + plugin._sectionClass + '">' + '<span class="' + plugin._amountClass + '">' + self._translateDigits(inst, inst._periods[period]) + '</span><br/>' + (labelsNum ? labelsNum[period] : labels[period]) + '</span>' : ''); }; return (inst.options.layout ? this._buildLayout(inst, show, inst.options.layout, inst.options.compact, inst.options.significant, showSignificant) : ((inst.options.compact ? // Compact version '<span class="' + this._rowClass + ' ' + this._amountClass + (inst._hold ? ' ' + this._holdingClass : '') + '">' + showCompact(Y) + showCompact(O) + showCompact(W) + showCompact(D) + (show[H] ? this._minDigits(inst, inst._periods[H], 2) : '') + (show[M] ? (show[H] ? inst.options.timeSeparator : '') + this._minDigits(inst, inst._periods[M], 2) : '') + (show[S] ? (show[H] || show[M] ? inst.options.timeSeparator : '') + this._minDigits(inst, inst._periods[S], 2) : '') : // Full version '<span class="' + this._rowClass + ' ' + this._showClass + (inst.options.significant || showCount) + (inst._hold ? ' ' + this._holdingClass : '') + '">' + showFull(Y) + showFull(O) + showFull(W) + showFull(D) + showFull(H) + showFull(M) + showFull(S)) + '</span>' + (inst.options.description ? '<span class="' + this._rowClass + ' ' + this._descrClass + '">' + inst.options.description + '</span>' : ''))); }, /* Construct a custom layout. @param inst (object) the current settings for this instance @param show (string[7]) flags indicating which periods are requested @param layout (string) the customised layout @param compact (boolean) true if using compact labels @param significant (number) the number of periods with values to show, zero for all @param showSignificant (boolean[7]) other periods to show for significance @return (string) the custom HTML */ _buildLayout: function(inst, show, layout, compact, significant, showSignificant) { var labels = inst.options[compact ? 'compactLabels' : 'labels']; var whichLabels = inst.options.whichLabels || this._normalLabels; var labelFor = function(index) { return (inst.options[(compact ? 'compactLabels' : 'labels') + whichLabels(inst._periods[index])] || labels)[index]; }; var digit = function(value, position) { return inst.options.digits[Math.floor(value / position) % 10]; }; var subs = {desc: inst.options.description, sep: inst.options.timeSeparator, yl: labelFor(Y), yn: this._minDigits(inst, inst._periods[Y], 1), ynn: this._minDigits(inst, inst._periods[Y], 2), ynnn: this._minDigits(inst, inst._periods[Y], 3), y1: digit(inst._periods[Y], 1), y10: digit(inst._periods[Y], 10), y100: digit(inst._periods[Y], 100), y1000: digit(inst._periods[Y], 1000), ol: labelFor(O), on: this._minDigits(inst, inst._periods[O], 1), onn: this._minDigits(inst, inst._periods[O], 2), onnn: this._minDigits(inst, inst._periods[O], 3), o1: digit(inst._periods[O], 1), o10: digit(inst._periods[O], 10), o100: digit(inst._periods[O], 100), o1000: digit(inst._periods[O], 1000), wl: labelFor(W), wn: this._minDigits(inst, inst._periods[W], 1), wnn: this._minDigits(inst, inst._periods[W], 2), wnnn: this._minDigits(inst, inst._periods[W], 3), w1: digit(inst._periods[W], 1), w10: digit(inst._periods[W], 10), w100: digit(inst._periods[W], 100), w1000: digit(inst._periods[W], 1000), dl: labelFor(D), dn: this._minDigits(inst, inst._periods[D], 1), dnn: this._minDigits(inst, inst._periods[D], 2), dnnn: this._minDigits(inst, inst._periods[D], 3), d1: digit(inst._periods[D], 1), d10: digit(inst._periods[D], 10), d100: digit(inst._periods[D], 100), d1000: digit(inst._periods[D], 1000), hl: labelFor(H), hn: this._minDigits(inst, inst._periods[H], 1), hnn: this._minDigits(inst, inst._periods[H], 2), hnnn: this._minDigits(inst, inst._periods[H], 3), h1: digit(inst._periods[H], 1), h10: digit(inst._periods[H], 10), h100: digit(inst._periods[H], 100), h1000: digit(inst._periods[H], 1000), ml: labelFor(M), mn: this._minDigits(inst, inst._periods[M], 1), mnn: this._minDigits(inst, inst._periods[M], 2), mnnn: this._minDigits(inst, inst._periods[M], 3), m1: digit(inst._periods[M], 1), m10: digit(inst._periods[M], 10), m100: digit(inst._periods[M], 100), m1000: digit(inst._periods[M], 1000), sl: labelFor(S), sn: this._minDigits(inst, inst._periods[S], 1), snn: this._minDigits(inst, inst._periods[S], 2), snnn: this._minDigits(inst, inst._periods[S], 3), s1: digit(inst._periods[S], 1), s10: digit(inst._periods[S], 10), s100: digit(inst._periods[S], 100), s1000: digit(inst._periods[S], 1000)}; var html = layout; // Replace period containers: {p<}...{p>} for (var i = Y; i <= S; i++) { var period = 'yowdhms'.charAt(i); var re = new RegExp('\\{' + period + '<\\}([\\s\\S]*)\\{' + period + '>\\}', 'g'); html = html.replace(re, ((!significant && show[i]) || (significant && showSignificant[i]) ? '$1' : '')); } // Replace period values: {pn} $.each(subs, function(n, v) { var re = new RegExp('\\{' + n + '\\}', 'g'); html = html.replace(re, v); }); return html; }, /* Ensure a numeric value has at least n digits for display. @param inst (object) the current settings for this instance @param value (number) the value to display @param len (number) the minimum length @return (string) the display text */ _minDigits: function(inst, value, len) { value = '' + value; if (value.length >= len) { return this._translateDigits(inst, value); } value = '0000000000' + value; return this._translateDigits(inst, value.substr(value.length - len)); }, /* Translate digits into other representations. @param inst (object) the current settings for this instance @param value (string) the text to translate @return (string) the translated text */ _translateDigits: function(inst, value) { return ('' + value).replace(/[0-9]/g, function(digit) { return inst.options.digits[digit]; }); }, /* Translate the format into flags for each period. @param inst (object) the current settings for this instance @return (string[7]) flags indicating which periods are requested (?) or required (!) by year, month, week, day, hour, minute, second */ _determineShow: function(inst) { var format = inst.options.format; var show = []; show[Y] = (format.match('y') ? '?' : (format.match('Y') ? '!' : null)); show[O] = (format.match('o') ? '?' : (format.match('O') ? '!' : null)); show[W] = (format.match('w') ? '?' : (format.match('W') ? '!' : null)); show[D] = (format.match('d') ? '?' : (format.match('D') ? '!' : null)); show[H] = (format.match('h') ? '?' : (format.match('H') ? '!' : null)); show[M] = (format.match('m') ? '?' : (format.match('M') ? '!' : null)); show[S] = (format.match('s') ? '?' : (format.match('S') ? '!' : null)); return show; }, /* Calculate the requested periods between now and the target time. @param inst (object) the current settings for this instance @param show (string[7]) flags indicating which periods are requested/required @param significant (number) the number of periods with values to show, zero for all @param now (Date) the current date and time @return (number[7]) the current time periods (always positive) by year, month, week, day, hour, minute, second */ _calculatePeriods: function(inst, show, significant, now) { // Find endpoints inst._now = now; inst._now.setMilliseconds(0); var until = new Date(inst._now.getTime()); if (inst._since) { if (now.getTime() < inst._since.getTime()) { inst._now = now = until; } else { now = inst._since; } } else { until.setTime(inst._until.getTime()); if (now.getTime() > inst._until.getTime()) { inst._now = now = until; } } // Calculate differences by period var periods = [0, 0, 0, 0, 0, 0, 0]; if (show[Y] || show[O]) { // Treat end of months as the same var lastNow = plugin._getDaysInMonth(now.getFullYear(), now.getMonth()); var lastUntil = plugin._getDaysInMonth(until.getFullYear(), until.getMonth()); var sameDay = (until.getDate() == now.getDate() || (until.getDate() >= Math.min(lastNow, lastUntil) && now.getDate() >= Math.min(lastNow, lastUntil))); var getSecs = function(date) { return (date.getHours() * 60 + date.getMinutes()) * 60 + date.getSeconds(); }; var months = Math.max(0, (until.getFullYear() - now.getFullYear()) * 12 + until.getMonth() - now.getMonth() + ((until.getDate() < now.getDate() && !sameDay) || (sameDay && getSecs(until) < getSecs(now)) ? -1 : 0)); periods[Y] = (show[Y] ? Math.floor(months / 12) : 0); periods[O] = (show[O] ? months - periods[Y] * 12 : 0); // Adjust for months difference and end of month if necessary now = new Date(now.getTime()); var wasLastDay = (now.getDate() == lastNow); var lastDay = plugin._getDaysInMonth(now.getFullYear() + periods[Y], now.getMonth() + periods[O]); if (now.getDate() > lastDay) { now.setDate(lastDay); } now.setFullYear(now.getFullYear() + periods[Y]); now.setMonth(now.getMonth() + periods[O]); if (wasLastDay) { now.setDate(lastDay); } } var diff = Math.floor((until.getTime() - now.getTime()) / 1000); var extractPeriod = function(period, numSecs) { periods[period] = (show[period] ? Math.floor(diff / numSecs) : 0); diff -= periods[period] * numSecs; }; extractPeriod(W, 604800); extractPeriod(D, 86400); extractPeriod(H, 3600); extractPeriod(M, 60); extractPeriod(S, 1); if (diff > 0 && !inst._since) { // Round up if left overs var multiplier = [1, 12, 4.3482, 7, 24, 60, 60]; var lastShown = S; var max = 1; for (var period = S; period >= Y; period--) { if (show[period]) { if (periods[lastShown] >= max) { periods[lastShown] = 0; diff = 1; } if (diff > 0) { periods[period]++; diff = 0; lastShown = period; max = 1; } } max *= multiplier[period]; } } if (significant) { // Zero out insignificant periods for (var period = Y; period <= S; period++) { if (significant && periods[period]) { significant--; } else if (!significant) { periods[period] = 0; } } } return periods; } }); // The list of commands that return values and don't permit chaining var getters = ['getTimes']; /* Determine whether a command is a getter and doesn't permit chaining. @param command (string, optional) the command to run @param otherArgs ([], optional) any other arguments for the command @return true if the command is a getter, false if not */ function isNotChained(command, otherArgs) { if (command == 'option' && (otherArgs.length == 0 || (otherArgs.length == 1 && typeof otherArgs[0] == 'string'))) { return true; } return $.inArray(command, getters) > -1; } /* Process the countdown functionality for a jQuery selection. @param options (object) the new settings to use for these instances (optional) or (string) the command to run (optional) @return (jQuery) for chaining further calls or (any) getter value */ $.fn.countdown = function(options) { var otherArgs = Array.prototype.slice.call(arguments, 1); if (isNotChained(options, otherArgs)) { return plugin['_' + options + 'Plugin']. apply(plugin, [this[0]].concat(otherArgs)); } return this.each(function() { if (typeof options == 'string') { if (!plugin['_' + options + 'Plugin']) { throw 'Unknown command: ' + options; } plugin['_' + options + 'Plugin']. apply(plugin, [this].concat(otherArgs)); } else { plugin._attachPlugin(this, options || {}); } }); }; /* Initialise the countdown functionality. */ var plugin = $.countdown = new Countdown(); // Singleton instance })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Korean initialisation for the jQuery countdown extension Written by Ryan Yu (ryanyu79@gmail.com). */ (function($) { $.countdown.regional['ko'] = { labels: ['년', '월', '주', '일', '시', '분', '초'], labels1: ['년', '월', '주', '일', '시', '분', '초'], compactLabels: ['년', '월', '주', '일'], compactLabels1: ['년', '월', '주', '일'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['ko']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Malay initialisation for the jQuery countdown extension Written by Jason Ong (jason{at}portalgroove.com) May 2010. */ (function($) { $.countdown.regional['ms'] = { labels: ['Tahun', 'Bulan', 'Minggu', 'Hari', 'Jam', 'Minit', 'Saat'], labels1: ['Tahun', 'Bulan', 'Minggu', 'Hari', 'Jam', 'Minit', 'Saat'], compactLabels: ['t', 'b', 'm', 'h'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['ms']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Thai initialisation for the jQuery countdown extension Written by Pornchai Sakulsrimontri (li_sin_th@yahoo.com). */ (function($) { $.countdown.regional['th'] = { labels: ['ปี', 'เดือน', 'สัปดาห์', 'วัน', 'ชั่วโมง', 'นาที', 'วินาที'], labels1: ['ปี', 'เดือน', 'สัปดาห์', 'วัน', 'ชั่วโมง', 'นาที', 'วินาที'], compactLabels: ['ปี', 'เดือน', 'สัปดาห์', 'วัน'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['th']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Albanian initialisation for the jQuery countdown extension Written by Erzen Komoni. */ (function($) { $.countdown.regional['sq'] = { labels: ['Vite', 'Muaj', 'Javë', 'Ditë', 'Orë', 'Minuta', 'Sekonda'], labels1: ['Vit', 'Muaj', 'Javë', 'Dit', 'Orë', 'Minutë', 'Sekond'], compactLabels: ['V', 'M', 'J', 'D'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['sq']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Polish initialisation for the jQuery countdown extension * Written by Pawel Lewtak lewtak@gmail.com (2008) */ (function($) { $.countdown.regional['pl'] = { labels: ['lat', 'miesięcy', 'tygodni', 'dni', 'godzin', 'minut', 'sekund'], labels1: ['rok', 'miesiąc', 'tydzień', 'dzień', 'godzina', 'minuta', 'sekunda'], labels2: ['lata', 'miesiące', 'tygodnie', 'dni', 'godziny', 'minuty', 'sekundy'], compactLabels: ['l', 'm', 't', 'd'], compactLabels1: ['r', 'm', 't', 'd'], whichLabels: function(amount) { var units = amount % 10; var tens = Math.floor((amount % 100) / 10); return (amount == 1 ? 1 : (units >= 2 && units <= 4 && tens != 1 ? 2 : 0)); }, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['pl']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Italian initialisation for the jQuery countdown extension * Written by Davide Bellettini (davide.bellettini@gmail.com) and Roberto Chiaveri Feb 2008. */ (function($) { $.countdown.regional['it'] = { labels: ['Anni', 'Mesi', 'Settimane', 'Giorni', 'Ore', 'Minuti', 'Secondi'], labels1: ['Anno', 'Mese', 'Settimana', 'Giorno', 'Ora', 'Minuto', 'Secondo'], compactLabels: ['a', 'm', 's', 'g'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['it']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Gujarati initialization for the jQuery countdown extension * Written by Sahil Jariwala jariwala.sahil@gmail.com (2012) */ (function($) { $.countdown.regional['gu'] = { labels: ['વર્ષ', 'મહિનો', 'અઠવાડિયા', 'દિવસ', 'કલાક', 'મિનિટ','સેકન્ડ'], labels1: ['વર્ષ','મહિનો','અઠવાડિયા','દિવસ','કલાક','મિનિટ', 'સેકન્ડ'], compactLabels: ['વ', 'મ', 'અ', 'દિ'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['gu']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Swedish initialisation for the jQuery countdown extension Written by Carl (carl@nordenfelt.com). */ (function($) { $.countdown.regional['sv'] = { labels: ['År', 'Månader', 'Veckor', 'Dagar', 'Timmar', 'Minuter', 'Sekunder'], labels1: ['År', 'Månad', 'Vecka', 'Dag', 'Timme', 'Minut', 'Sekund'], compactLabels: ['Å', 'M', 'V', 'D'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['sv']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Ukrainian initialisation for the jQuery countdown extension * Written by Goloborodko M misha.gm@gmail.com (2009), corrections by Iгор Kоновал */ (function($) { $.countdown.regional['uk'] = { labels: ['Років', 'Місяців', 'Тижнів', 'Днів', 'Годин', 'Хвилин', 'Секунд'], labels1: ['Рік', 'Місяць', 'Тиждень', 'День', 'Година', 'Хвилина', 'Секунда'], labels2: ['Роки', 'Місяці', 'Тижні', 'Дні', 'Години', 'Хвилини', 'Секунди'], compactLabels: ['r', 'm', 't', 'd'], whichLabels: function(amount) { return (amount == 1 ? 1 : (amount >=2 && amount <= 4 ? 2 : 0)); }, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['uk']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Czech initialisation for the jQuery countdown extension * Written by Roman Chlebec (creamd@c64.sk) (2008) */ (function($) { $.countdown.regional['cs'] = { labels: ['Roků', 'Měsíců', 'Týdnů', 'Dní', 'Hodin', 'Minut', 'Sekund'], labels1: ['Rok', 'Měsíc', 'Týden', 'Den', 'Hodina', 'Minuta', 'Sekunda'], labels2: ['Roky', 'Měsíce', 'Týdny', 'Dny', 'Hodiny', 'Minuty', 'Sekundy'], compactLabels: ['r', 'm', 't', 'd'], whichLabels: function(amount) { return (amount == 1 ? 1 : (amount >= 2 && amount <= 4 ? 2 : 0)); }, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['cs']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Burmese initialisation for the jQuery countdown extension Written by Win Lwin Moe (winnlwinmoe@gmail.com) Dec 2009. */ (function($) { $.countdown.regional['my'] = { labels: ['နွစ္', 'လ', 'ရက္သတဿတပတ္', 'ရက္', 'နာရီ', 'မိနစ္', 'စကဿကန့္'], labels1: ['နွစ္', 'လ', 'ရက္သတဿတပတ္', 'ရက္', 'နာရီ', 'မိနစ္', 'စကဿကန့္'], compactLabels: ['နွစ္', 'လ', 'ရက္သတဿတပတ္', 'ရက္'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['my']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html * Armenian initialisation for the jQuery countdown extension * Written by Artur Martirosyan. (artur{at}zoom.am) October 2011. */ (function($) { $.countdown.regional['hy'] = { labels: ['Տարի', 'Ամիս', 'Շաբաթ', 'Օր', 'Ժամ', 'Րոպե', 'Վարկյան'], labels1: ['Տարի', 'Ամիս', 'Շաբաթ', 'Օր', 'Ժամ', 'Րոպե', 'Վարկյան'], compactLabels: ['տ', 'ա', 'շ', 'օ'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['hy']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Persian (فارسی) initialisation for the jQuery countdown extension Written by Alireza Ziaie (ziai@magfa.com) Oct 2008. Digits corrected by Hamed Ramezanian Feb 2013. */ (function($) { $.countdown.regional['fa'] = { labels: ['‌سال', 'ماه', 'هفته', 'روز', 'ساعت', 'دقیقه', 'ثانیه'], labels1: ['سال', 'ماه', 'هفته', 'روز', 'ساعت', 'دقیقه', 'ثانیه'], compactLabels: ['س', 'م', 'ه', 'ر'], whichLabels: null, digits: ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'], timeSeparator: ':', isRTL: true}; $.countdown.setDefaults($.countdown.regional['fa']); })(jQuery);
JavaScript
/* http://keith-wood.name/countdown.html Catalan initialisation for the jQuery countdown extension Written by Amanida Media www.amanidamedia.com (2010) */ (function($) { $.countdown.regional['ca'] = { labels: ['Anys', 'Mesos', 'Setmanes', 'Dies', 'Hores', 'Minuts', 'Segons'], labels1: ['Anys', 'Mesos', 'Setmanes', 'Dies', 'Hores', 'Minuts', 'Segons'], compactLabels: ['a', 'm', 's', 'g'], whichLabels: null, digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], timeSeparator: ':', isRTL: false}; $.countdown.setDefaults($.countdown.regional['ca']); })(jQuery);
JavaScript
/* * Gritter for jQuery * http://www.boedesign.com/ * * Copyright (c) 2012 Jordan Boesch * Dual licensed under the MIT and GPL licenses. * * Date: February 24, 2012 * Version: 1.7.4 */ (function($){ /** * Set it up as an object under the jQuery namespace */ $.gritter = {}; /** * Set up global options that the user can over-ride */ $.gritter.options = { position: '', class_name: '', // could be set to 'gritter-light' to use white notifications fade_in_speed: 'medium', // how fast notifications fade in fade_out_speed: 1000, // how fast the notices fade out time: 6000 // hang on the screen for... } /** * Add a gritter notification to the screen * @see Gritter#add(); */ $.gritter.add = function(params){ try { return Gritter.add(params || {}); } catch(e) { var err = 'Gritter Error: ' + e; (typeof(console) != 'undefined' && console.error) ? console.error(err, params) : alert(err); } } /** * Remove a gritter notification from the screen * @see Gritter#removeSpecific(); */ $.gritter.remove = function(id, params){ Gritter.removeSpecific(id, params || {}); } /** * Remove all notifications * @see Gritter#stop(); */ $.gritter.removeAll = function(params){ Gritter.stop(params || {}); } /** * Big fat Gritter object * @constructor (not really since its object literal) */ var Gritter = { // Public - options to over-ride with $.gritter.options in "add" position: '', fade_in_speed: '', fade_out_speed: '', time: '', // Private - no touchy the private parts _custom_timer: 0, _item_count: 0, _is_setup: 0, _tpl_close: '<div class="gritter-close"></div>', _tpl_title: '<span class="gritter-title">[[title]]</span>', _tpl_item: '<div id="gritter-item-[[number]]" class="gritter-item-wrapper [[item_class]]" style="display:none"><div class="gritter-top"></div><div class="gritter-item">[[close]][[image]]<div class="[[class_name]]">[[title]]<p>[[text]]</p></div><div style="clear:both"></div></div><div class="gritter-bottom"></div></div>', _tpl_wrap: '<div id="gritter-notice-wrapper"></div>', /** * Add a gritter notification to the screen * @param {Object} params The object that contains all the options for drawing the notification * @return {Integer} The specific numeric id to that gritter notification */ add: function(params){ // Handle straight text if(typeof(params) == 'string'){ params = {text:params}; } // We might have some issues if we don't have a title or text! if(!params.text){ throw 'You must supply "text" parameter.'; } // Check the options and set them once if(!this._is_setup){ this._runSetup(); } // Basics var title = params.title, text = params.text, image = params.image || '', sticky = params.sticky || false, item_class = params.class_name || $.gritter.options.class_name, position = $.gritter.options.position, time_alive = params.time || ''; this._verifyWrapper(); this._item_count++; var number = this._item_count, tmp = this._tpl_item; // Assign callbacks $(['before_open', 'after_open', 'before_close', 'after_close']).each(function(i, val){ Gritter['_' + val + '_' + number] = ($.isFunction(params[val])) ? params[val] : function(){} }); // Reset this._custom_timer = 0; // A custom fade time set if(time_alive){ this._custom_timer = time_alive; } var image_str = (image != '') ? '<img src="' + image + '" class="gritter-image" />' : '', class_name = (image != '') ? 'gritter-with-image' : 'gritter-without-image'; // String replacements on the template if(title){ title = this._str_replace('[[title]]',title,this._tpl_title); }else{ title = ''; } tmp = this._str_replace( ['[[title]]', '[[text]]', '[[close]]', '[[image]]', '[[number]]', '[[class_name]]', '[[item_class]]'], [title, text, this._tpl_close, image_str, this._item_count, class_name, item_class], tmp ); // If it's false, don't show another gritter message if(this['_before_open_' + number]() === false){ return false; } $('#gritter-notice-wrapper').addClass(position).append(tmp); var item = $('#gritter-item-' + this._item_count); item.fadeIn(this.fade_in_speed, function(){ Gritter['_after_open_' + number]($(this)); }); if(!sticky){ this._setFadeTimer(item, number); } // Bind the hover/unhover states $(item).bind('mouseenter mouseleave', function(event){ if(event.type == 'mouseenter'){ if(!sticky){ Gritter._restoreItemIfFading($(this), number); } } else { if(!sticky){ Gritter._setFadeTimer($(this), number); } } Gritter._hoverState($(this), event.type); }); // Clicking (X) makes the perdy thing close $(item).find('.gritter-close').click(function(){ Gritter.removeSpecific(number, {}, null, true); }); return number; }, /** * If we don't have any more gritter notifications, get rid of the wrapper using this check * @private * @param {Integer} unique_id The ID of the element that was just deleted, use it for a callback * @param {Object} e The jQuery element that we're going to perform the remove() action on * @param {Boolean} manual_close Did we close the gritter dialog with the (X) button */ _countRemoveWrapper: function(unique_id, e, manual_close){ // Remove it then run the callback function e.remove(); this['_after_close_' + unique_id](e, manual_close); // Check if the wrapper is empty, if it is.. remove the wrapper if($('.gritter-item-wrapper').length == 0){ $('#gritter-notice-wrapper').remove(); } }, /** * Fade out an element after it's been on the screen for x amount of time * @private * @param {Object} e The jQuery element to get rid of * @param {Integer} unique_id The id of the element to remove * @param {Object} params An optional list of params to set fade speeds etc. * @param {Boolean} unbind_events Unbind the mouseenter/mouseleave events if they click (X) */ _fade: function(e, unique_id, params, unbind_events){ var params = params || {}, fade = (typeof(params.fade) != 'undefined') ? params.fade : true, fade_out_speed = params.speed || this.fade_out_speed, manual_close = unbind_events; this['_before_close_' + unique_id](e, manual_close); // If this is true, then we are coming from clicking the (X) if(unbind_events){ e.unbind('mouseenter mouseleave'); } // Fade it out or remove it if(fade){ e.animate({ opacity: 0 }, fade_out_speed, function(){ e.animate({ height: 0 }, 300, function(){ Gritter._countRemoveWrapper(unique_id, e, manual_close); }) }) } else { this._countRemoveWrapper(unique_id, e); } }, /** * Perform actions based on the type of bind (mouseenter, mouseleave) * @private * @param {Object} e The jQuery element * @param {String} type The type of action we're performing: mouseenter or mouseleave */ _hoverState: function(e, type){ // Change the border styles and add the (X) close button when you hover if(type == 'mouseenter'){ e.addClass('hover'); // Show close button e.find('.gritter-close').show(); } // Remove the border styles and hide (X) close button when you mouse out else { e.removeClass('hover'); // Hide close button e.find('.gritter-close').hide(); } }, /** * Remove a specific notification based on an ID * @param {Integer} unique_id The ID used to delete a specific notification * @param {Object} params A set of options passed in to determine how to get rid of it * @param {Object} e The jQuery element that we're "fading" then removing * @param {Boolean} unbind_events If we clicked on the (X) we set this to true to unbind mouseenter/mouseleave */ removeSpecific: function(unique_id, params, e, unbind_events){ if(!e){ var e = $('#gritter-item-' + unique_id); } // We set the fourth param to let the _fade function know to // unbind the "mouseleave" event. Once you click (X) there's no going back! this._fade(e, unique_id, params || {}, unbind_events); }, /** * If the item is fading out and we hover over it, restore it! * @private * @param {Object} e The HTML element to remove * @param {Integer} unique_id The ID of the element */ _restoreItemIfFading: function(e, unique_id){ clearTimeout(this['_int_id_' + unique_id]); e.stop().css({ opacity: '', height: '' }); }, /** * Setup the global options - only once * @private */ _runSetup: function(){ for(opt in $.gritter.options){ this[opt] = $.gritter.options[opt]; } this._is_setup = 1; }, /** * Set the notification to fade out after a certain amount of time * @private * @param {Object} item The HTML element we're dealing with * @param {Integer} unique_id The ID of the element */ _setFadeTimer: function(e, unique_id){ var timer_str = (this._custom_timer) ? this._custom_timer : this.time; this['_int_id_' + unique_id] = setTimeout(function(){ Gritter._fade(e, unique_id); }, timer_str); }, /** * Bring everything to a halt * @param {Object} params A list of callback functions to pass when all notifications are removed */ stop: function(params){ // callbacks (if passed) var before_close = ($.isFunction(params.before_close)) ? params.before_close : function(){}; var after_close = ($.isFunction(params.after_close)) ? params.after_close : function(){}; var wrap = $('#gritter-notice-wrapper'); before_close(wrap); wrap.fadeOut(function(){ $(this).remove(); after_close(); }); }, /** * An extremely handy PHP function ported to JS, works well for templating * @private * @param {String/Array} search A list of things to search for * @param {String/Array} replace A list of things to replace the searches with * @return {String} sa The output */ _str_replace: function(search, replace, subject, count){ var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0, f = [].concat(search), r = [].concat(replace), s = subject, ra = r instanceof Array, sa = s instanceof Array; s = [].concat(s); if(count){ this.window[count] = 0; } for(i = 0, sl = s.length; i < sl; i++){ if(s[i] === ''){ continue; } for (j = 0, fl = f.length; j < fl; j++){ temp = s[i] + ''; repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0]; s[i] = (temp).split(f[j]).join(repl); if(count && s[i] !== temp){ this.window[count] += (temp.length-s[i].length) / f[j].length; } } } return sa ? s : s[0]; }, /** * A check to make sure we have something to wrap our notices with * @private */ _verifyWrapper: function(){ if($('#gritter-notice-wrapper').length == 0){ $('body').append(this._tpl_wrap); } } } })(jQuery);
JavaScript
(function(root, factory) { if(typeof exports === 'object') { module.exports = factory(); } else if(typeof define === 'function' && define.amd) { define('GMaps', [], factory); } root.GMaps = factory(); }(this, function() { /*! * GMaps.js v0.4.9 * http://hpneo.github.com/gmaps/ * * Copyright 2013, Gustavo Leon * Released under the MIT License. */ if (!(typeof window.google === 'object' && window.google.maps)) { throw 'Google Maps API is required. Please register the following JavaScript library http://maps.google.com/maps/api/js?sensor=true.' } var extend_object = function(obj, new_obj) { var name; if (obj === new_obj) { return obj; } for (name in new_obj) { obj[name] = new_obj[name]; } return obj; }; var replace_object = function(obj, replace) { var name; if (obj === replace) { return obj; } for (name in replace) { if (obj[name] != undefined) { obj[name] = replace[name]; } } return obj; }; var array_map = function(array, callback) { var original_callback_params = Array.prototype.slice.call(arguments, 2), array_return = [], array_length = array.length, i; if (Array.prototype.map && array.map === Array.prototype.map) { array_return = Array.prototype.map.call(array, function(item) { callback_params = original_callback_params; callback_params.splice(0, 0, item); return callback.apply(this, callback_params); }); } else { for (i = 0; i < array_length; i++) { callback_params = original_callback_params; callback_params.splice(0, 0, array[i]); array_return.push(callback.apply(this, callback_params)); } } return array_return; }; var array_flat = function(array) { var new_array = [], i; for (i = 0; i < array.length; i++) { new_array = new_array.concat(array[i]); } return new_array; }; var coordsToLatLngs = function(coords, useGeoJSON) { var first_coord = coords[0], second_coord = coords[1]; if (useGeoJSON) { first_coord = coords[1]; second_coord = coords[0]; } return new google.maps.LatLng(first_coord, second_coord); }; var arrayToLatLng = function(coords, useGeoJSON) { var i; for (i = 0; i < coords.length; i++) { if (coords[i].length > 0 && typeof(coords[i][0]) == "object") { coords[i] = arrayToLatLng(coords[i], useGeoJSON); } else { coords[i] = coordsToLatLngs(coords[i], useGeoJSON); } } return coords; }; var getElementById = function(id, context) { var element, id = id.replace('#', ''); if ('jQuery' in this && context) { element = $("#" + id, context)[0]; } else { element = document.getElementById(id); }; return element; }; var findAbsolutePosition = function(obj) { var curleft = 0, curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } return [curleft, curtop]; }; var GMaps = (function(global) { "use strict"; var doc = document; var GMaps = function(options) { if (!this) return new GMaps(options); options.zoom = options.zoom || 15; options.mapType = options.mapType || 'roadmap'; var self = this, i, events_that_hide_context_menu = ['bounds_changed', 'center_changed', 'click', 'dblclick', 'drag', 'dragend', 'dragstart', 'idle', 'maptypeid_changed', 'projection_changed', 'resize', 'tilesloaded', 'zoom_changed'], events_that_doesnt_hide_context_menu = ['mousemove', 'mouseout', 'mouseover'], options_to_be_deleted = ['el', 'lat', 'lng', 'mapType', 'width', 'height', 'markerClusterer', 'enableNewStyle'], container_id = options.el || options.div, markerClustererFunction = options.markerClusterer, mapType = google.maps.MapTypeId[options.mapType.toUpperCase()], map_center = new google.maps.LatLng(options.lat, options.lng), zoomControl = options.zoomControl || true, zoomControlOpt = options.zoomControlOpt || { style: 'DEFAULT', position: 'TOP_LEFT' }, zoomControlStyle = zoomControlOpt.style || 'DEFAULT', zoomControlPosition = zoomControlOpt.position || 'TOP_LEFT', panControl = options.panControl || true, mapTypeControl = options.mapTypeControl || true, scaleControl = options.scaleControl || true, streetViewControl = options.streetViewControl || true, overviewMapControl = overviewMapControl || true, map_options = {}, map_base_options = { zoom: this.zoom, center: map_center, mapTypeId: mapType }, map_controls_options = { panControl: panControl, zoomControl: zoomControl, zoomControlOptions: { style: google.maps.ZoomControlStyle[zoomControlStyle], position: google.maps.ControlPosition[zoomControlPosition] }, mapTypeControl: mapTypeControl, scaleControl: scaleControl, streetViewControl: streetViewControl, overviewMapControl: overviewMapControl }; if (typeof(options.el) === 'string' || typeof(options.div) === 'string') { this.el = getElementById(container_id, options.context); } else { this.el = container_id; } if (typeof(this.el) === 'undefined' || this.el === null) { throw 'No element defined.'; } window.context_menu = window.context_menu || {}; window.context_menu[self.el.id] = {}; this.controls = []; this.overlays = []; this.layers = []; // array with kml/georss and fusiontables layers, can be as many this.singleLayers = {}; // object with the other layers, only one per layer this.markers = []; this.polylines = []; this.routes = []; this.polygons = []; this.infoWindow = null; this.overlay_el = null; this.zoom = options.zoom; this.registered_events = {}; this.el.style.width = options.width || this.el.scrollWidth || this.el.offsetWidth; this.el.style.height = options.height || this.el.scrollHeight || this.el.offsetHeight; google.maps.visualRefresh = options.enableNewStyle; for (i = 0; i < options_to_be_deleted.length; i++) { delete options[options_to_be_deleted[i]]; } if(options.disableDefaultUI != true) { map_base_options = extend_object(map_base_options, map_controls_options); } map_options = extend_object(map_base_options, options); for (i = 0; i < events_that_hide_context_menu.length; i++) { delete map_options[events_that_hide_context_menu[i]]; } for (i = 0; i < events_that_doesnt_hide_context_menu.length; i++) { delete map_options[events_that_doesnt_hide_context_menu[i]]; } this.map = new google.maps.Map(this.el, map_options); if (markerClustererFunction) { this.markerClusterer = markerClustererFunction.apply(this, [this.map]); } var buildContextMenuHTML = function(control, e) { var html = '', options = window.context_menu[self.el.id][control]; for (var i in options){ if (options.hasOwnProperty(i)) { var option = options[i]; html += '<li><a id="' + control + '_' + i + '" href="#">' + option.title + '</a></li>'; } } if (!getElementById('gmaps_context_menu')) return; var context_menu_element = getElementById('gmaps_context_menu'); context_menu_element.innerHTML = html; var context_menu_items = context_menu_element.getElementsByTagName('a'), context_menu_items_count = context_menu_items.length i; for (i = 0; i < context_menu_items_count; i++) { var context_menu_item = context_menu_items[i]; var assign_menu_item_action = function(ev){ ev.preventDefault(); options[this.id.replace(control + '_', '')].action.apply(self, [e]); self.hideContextMenu(); }; google.maps.event.clearListeners(context_menu_item, 'click'); google.maps.event.addDomListenerOnce(context_menu_item, 'click', assign_menu_item_action, false); } var position = findAbsolutePosition.apply(this, [self.el]), left = position[0] + e.pixel.x - 15, top = position[1] + e.pixel.y- 15; context_menu_element.style.left = left + "px"; context_menu_element.style.top = top + "px"; context_menu_element.style.display = 'block'; }; this.buildContextMenu = function(control, e) { if (control === 'marker') { e.pixel = {}; var overlay = new google.maps.OverlayView(); overlay.setMap(self.map); overlay.draw = function() { var projection = overlay.getProjection(), position = e.marker.getPosition(); e.pixel = projection.fromLatLngToContainerPixel(position); buildContextMenuHTML(control, e); }; } else { buildContextMenuHTML(control, e); } }; this.setContextMenu = function(options) { window.context_menu[self.el.id][options.control] = {}; var i, ul = doc.createElement('ul'); for (i in options.options) { if (options.options.hasOwnProperty(i)) { var option = options.options[i]; window.context_menu[self.el.id][options.control][option.name] = { title: option.title, action: option.action }; } } ul.id = 'gmaps_context_menu'; ul.style.display = 'none'; ul.style.position = 'absolute'; ul.style.minWidth = '100px'; ul.style.background = 'white'; ul.style.listStyle = 'none'; ul.style.padding = '8px'; ul.style.boxShadow = '2px 2px 6px #ccc'; doc.body.appendChild(ul); var context_menu_element = getElementById('gmaps_context_menu') google.maps.event.addDomListener(context_menu_element, 'mouseout', function(ev) { if (!ev.relatedTarget || !this.contains(ev.relatedTarget)) { window.setTimeout(function(){ context_menu_element.style.display = 'none'; }, 400); } }, false); }; this.hideContextMenu = function() { var context_menu_element = getElementById('gmaps_context_menu'); if (context_menu_element) { context_menu_element.style.display = 'none'; } }; var setupListener = function(object, name) { google.maps.event.addListener(object, name, function(e){ if (e == undefined) { e = this; } options[name].apply(this, [e]); self.hideContextMenu(); }); }; for (var ev = 0; ev < events_that_hide_context_menu.length; ev++) { var name = events_that_hide_context_menu[ev]; if (name in options) { setupListener(this.map, name); } } for (var ev = 0; ev < events_that_doesnt_hide_context_menu.length; ev++) { var name = events_that_doesnt_hide_context_menu[ev]; if (name in options) { setupListener(this.map, name); } } google.maps.event.addListener(this.map, 'rightclick', function(e) { if (options.rightclick) { options.rightclick.apply(this, [e]); } if(window.context_menu[self.el.id]['map'] != undefined) { self.buildContextMenu('map', e); } }); this.refresh = function() { google.maps.event.trigger(this.map, 'resize'); }; this.fitZoom = function() { var latLngs = [], markers_length = this.markers.length, i; for (i = 0; i < markers_length; i++) { if(typeof(this.markers[i].visible) === 'boolean' && this.markers[i].visible) { latLngs.push(this.markers[i].getPosition()); } } this.fitLatLngBounds(latLngs); }; this.fitLatLngBounds = function(latLngs) { var total = latLngs.length; var bounds = new google.maps.LatLngBounds(); for(var i=0; i < total; i++) { bounds.extend(latLngs[i]); } this.map.fitBounds(bounds); }; this.setCenter = function(lat, lng, callback) { this.map.panTo(new google.maps.LatLng(lat, lng)); if (callback) { callback(); } }; this.getElement = function() { return this.el; }; this.zoomIn = function(value) { value = value || 1; this.zoom = this.map.getZoom() + value; this.map.setZoom(this.zoom); }; this.zoomOut = function(value) { value = value || 1; this.zoom = this.map.getZoom() - value; this.map.setZoom(this.zoom); }; var native_methods = [], method; for (method in this.map) { if (typeof(this.map[method]) == 'function' && !this[method]) { native_methods.push(method); } } for (i=0; i < native_methods.length; i++) { (function(gmaps, scope, method_name) { gmaps[method_name] = function(){ return scope[method_name].apply(scope, arguments); }; })(this, this.map, native_methods[i]); } }; return GMaps; })(this); GMaps.prototype.createControl = function(options) { var control = document.createElement('div'); control.style.cursor = 'pointer'; control.style.fontFamily = 'Arial, sans-serif'; control.style.fontSize = '13px'; control.style.boxShadow = 'rgba(0, 0, 0, 0.398438) 0px 2px 4px'; for (var option in options.style) { control.style[option] = options.style[option]; } if (options.id) { control.id = options.id; } if (options.classes) { control.className = options.classes; } if (options.content) { control.innerHTML = options.content; } for (var ev in options.events) { (function(object, name) { google.maps.event.addDomListener(object, name, function(){ options.events[name].apply(this, [this]); }); })(control, ev); } control.index = 1; return control; }; GMaps.prototype.addControl = function(options) { var position = google.maps.ControlPosition[options.position.toUpperCase()]; delete options.position; var control = this.createControl(options); this.controls.push(control); this.map.controls[position].push(control); return control; }; GMaps.prototype.createMarker = function(options) { if (options.lat == undefined && options.lng == undefined && options.position == undefined) { throw 'No latitude or longitude defined.'; } var self = this, details = options.details, fences = options.fences, outside = options.outside, base_options = { position: new google.maps.LatLng(options.lat, options.lng), map: null }; delete options.lat; delete options.lng; delete options.fences; delete options.outside; var marker_options = extend_object(base_options, options), marker = new google.maps.Marker(marker_options); marker.fences = fences; if (options.infoWindow) { marker.infoWindow = new google.maps.InfoWindow(options.infoWindow); var info_window_events = ['closeclick', 'content_changed', 'domready', 'position_changed', 'zindex_changed']; for (var ev = 0; ev < info_window_events.length; ev++) { (function(object, name) { if (options.infoWindow[name]) { google.maps.event.addListener(object, name, function(e){ options.infoWindow[name].apply(this, [e]); }); } })(marker.infoWindow, info_window_events[ev]); } } var marker_events = ['animation_changed', 'clickable_changed', 'cursor_changed', 'draggable_changed', 'flat_changed', 'icon_changed', 'position_changed', 'shadow_changed', 'shape_changed', 'title_changed', 'visible_changed', 'zindex_changed']; var marker_events_with_mouse = ['dblclick', 'drag', 'dragend', 'dragstart', 'mousedown', 'mouseout', 'mouseover', 'mouseup']; for (var ev = 0; ev < marker_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(){ options[name].apply(this, [this]); }); } })(marker, marker_events[ev]); } for (var ev = 0; ev < marker_events_with_mouse.length; ev++) { (function(map, object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(me){ if(!me.pixel){ me.pixel = map.getProjection().fromLatLngToPoint(me.latLng) } options[name].apply(this, [me]); }); } })(this.map, marker, marker_events_with_mouse[ev]); } google.maps.event.addListener(marker, 'click', function() { this.details = details; if (options.click) { options.click.apply(this, [this]); } if (marker.infoWindow) { self.hideInfoWindows(); marker.infoWindow.open(self.map, marker); } }); google.maps.event.addListener(marker, 'rightclick', function(e) { e.marker = this; if (options.rightclick) { options.rightclick.apply(this, [e]); } if (window.context_menu[self.el.id]['marker'] != undefined) { self.buildContextMenu('marker', e); } }); if (marker.fences) { google.maps.event.addListener(marker, 'dragend', function() { self.checkMarkerGeofence(marker, function(m, f) { outside(m, f); }); }); } return marker; }; GMaps.prototype.addMarker = function(options) { var marker; if(options.hasOwnProperty('gm_accessors_')) { // Native google.maps.Marker object marker = options; } else { if ((options.hasOwnProperty('lat') && options.hasOwnProperty('lng')) || options.position) { marker = this.createMarker(options); } else { throw 'No latitude or longitude defined.'; } } marker.setMap(this.map); if(this.markerClusterer) { this.markerClusterer.addMarker(marker); } this.markers.push(marker); GMaps.fire('marker_added', marker, this); return marker; }; GMaps.prototype.addMarkers = function(array) { for (var i = 0, marker; marker=array[i]; i++) { this.addMarker(marker); } return this.markers; }; GMaps.prototype.hideInfoWindows = function() { for (var i = 0, marker; marker = this.markers[i]; i++){ if (marker.infoWindow){ marker.infoWindow.close(); } } }; GMaps.prototype.removeMarker = function(marker) { for (var i = 0; i < this.markers.length; i++) { if (this.markers[i] === marker) { this.markers[i].setMap(null); this.markers.splice(i, 1); if(this.markerClusterer) { this.markerClusterer.removeMarker(marker); } GMaps.fire('marker_removed', marker, this); break; } } return marker; }; GMaps.prototype.removeMarkers = function(collection) { var collection = (collection || this.markers); for (var i = 0;i < this.markers.length; i++) { if(this.markers[i] === collection[i]) { this.markers[i].setMap(null); } } var new_markers = []; for (var i = 0;i < this.markers.length; i++) { if(this.markers[i].getMap() != null) { new_markers.push(this.markers[i]); } } this.markers = new_markers; }; GMaps.prototype.drawOverlay = function(options) { var overlay = new google.maps.OverlayView(), auto_show = true; overlay.setMap(this.map); if (options.auto_show != null) { auto_show = options.auto_show; } overlay.onAdd = function() { var el = document.createElement('div'); el.style.borderStyle = "none"; el.style.borderWidth = "0px"; el.style.position = "absolute"; el.style.zIndex = 100; el.innerHTML = options.content; overlay.el = el; if (!options.layer) { options.layer = 'overlayLayer'; } var panes = this.getPanes(), overlayLayer = panes[options.layer], stop_overlay_events = ['contextmenu', 'DOMMouseScroll', 'dblclick', 'mousedown']; overlayLayer.appendChild(el); for (var ev = 0; ev < stop_overlay_events.length; ev++) { (function(object, name) { google.maps.event.addDomListener(object, name, function(e){ if (navigator.userAgent.toLowerCase().indexOf('msie') != -1 && document.all) { e.cancelBubble = true; e.returnValue = false; } else { e.stopPropagation(); } }); })(el, stop_overlay_events[ev]); } google.maps.event.trigger(this, 'ready'); }; overlay.draw = function() { var projection = this.getProjection(), pixel = projection.fromLatLngToDivPixel(new google.maps.LatLng(options.lat, options.lng)); options.horizontalOffset = options.horizontalOffset || 0; options.verticalOffset = options.verticalOffset || 0; var el = overlay.el, content = el.children[0], content_height = content.clientHeight, content_width = content.clientWidth; switch (options.verticalAlign) { case 'top': el.style.top = (pixel.y - content_height + options.verticalOffset) + 'px'; break; default: case 'middle': el.style.top = (pixel.y - (content_height / 2) + options.verticalOffset) + 'px'; break; case 'bottom': el.style.top = (pixel.y + options.verticalOffset) + 'px'; break; } switch (options.horizontalAlign) { case 'left': el.style.left = (pixel.x - content_width + options.horizontalOffset) + 'px'; break; default: case 'center': el.style.left = (pixel.x - (content_width / 2) + options.horizontalOffset) + 'px'; break; case 'right': el.style.left = (pixel.x + options.horizontalOffset) + 'px'; break; } el.style.display = auto_show ? 'block' : 'none'; if (!auto_show) { options.show.apply(this, [el]); } }; overlay.onRemove = function() { var el = overlay.el; if (options.remove) { options.remove.apply(this, [el]); } else { overlay.el.parentNode.removeChild(overlay.el); overlay.el = null; } }; this.overlays.push(overlay); return overlay; }; GMaps.prototype.removeOverlay = function(overlay) { for (var i = 0; i < this.overlays.length; i++) { if (this.overlays[i] === overlay) { this.overlays[i].setMap(null); this.overlays.splice(i, 1); break; } } }; GMaps.prototype.removeOverlays = function() { for (var i = 0, item; item = this.overlays[i]; i++) { item.setMap(null); } this.overlays = []; }; GMaps.prototype.drawPolyline = function(options) { var path = [], points = options.path; if (points.length) { if (points[0][0] === undefined) { path = points; } else { for (var i=0, latlng; latlng=points[i]; i++) { path.push(new google.maps.LatLng(latlng[0], latlng[1])); } } } var polyline_options = { map: this.map, path: path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight, geodesic: options.geodesic, clickable: true, editable: false, visible: true }; if (options.hasOwnProperty("clickable")) { polyline_options.clickable = options.clickable; } if (options.hasOwnProperty("editable")) { polyline_options.editable = options.editable; } if (options.hasOwnProperty("icons")) { polyline_options.icons = options.icons; } if (options.hasOwnProperty("zIndex")) { polyline_options.zIndex = options.zIndex; } var polyline = new google.maps.Polyline(polyline_options); var polyline_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polyline_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polyline, polyline_events[ev]); } this.polylines.push(polyline); GMaps.fire('polyline_added', polyline, this); return polyline; }; GMaps.prototype.removePolyline = function(polyline) { for (var i = 0; i < this.polylines.length; i++) { if (this.polylines[i] === polyline) { this.polylines[i].setMap(null); this.polylines.splice(i, 1); GMaps.fire('polyline_removed', polyline, this); break; } } }; GMaps.prototype.removePolylines = function() { for (var i = 0, item; item = this.polylines[i]; i++) { item.setMap(null); } this.polylines = []; }; GMaps.prototype.drawCircle = function(options) { options = extend_object({ map: this.map, center: new google.maps.LatLng(options.lat, options.lng) }, options); delete options.lat; delete options.lng; var polygon = new google.maps.Circle(options), polygon_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polygon_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polygon, polygon_events[ev]); } this.polygons.push(polygon); return polygon; }; GMaps.prototype.drawRectangle = function(options) { options = extend_object({ map: this.map }, options); var latLngBounds = new google.maps.LatLngBounds( new google.maps.LatLng(options.bounds[0][0], options.bounds[0][1]), new google.maps.LatLng(options.bounds[1][0], options.bounds[1][1]) ); options.bounds = latLngBounds; var polygon = new google.maps.Rectangle(options), polygon_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polygon_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polygon, polygon_events[ev]); } this.polygons.push(polygon); return polygon; }; GMaps.prototype.drawPolygon = function(options) { var useGeoJSON = false; if(options.hasOwnProperty("useGeoJSON")) { useGeoJSON = options.useGeoJSON; } delete options.useGeoJSON; options = extend_object({ map: this.map }, options); if (useGeoJSON == false) { options.paths = [options.paths.slice(0)]; } if (options.paths.length > 0) { if (options.paths[0].length > 0) { options.paths = array_flat(array_map(options.paths, arrayToLatLng, useGeoJSON)); } } var polygon = new google.maps.Polygon(options), polygon_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polygon_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polygon, polygon_events[ev]); } this.polygons.push(polygon); GMaps.fire('polygon_added', polygon, this); return polygon; }; GMaps.prototype.removePolygon = function(polygon) { for (var i = 0; i < this.polygons.length; i++) { if (this.polygons[i] === polygon) { this.polygons[i].setMap(null); this.polygons.splice(i, 1); GMaps.fire('polygon_removed', polygon, this); break; } } }; GMaps.prototype.removePolygons = function() { for (var i = 0, item; item = this.polygons[i]; i++) { item.setMap(null); } this.polygons = []; }; GMaps.prototype.getFromFusionTables = function(options) { var events = options.events; delete options.events; var fusion_tables_options = options, layer = new google.maps.FusionTablesLayer(fusion_tables_options); for (var ev in events) { (function(object, name) { google.maps.event.addListener(object, name, function(e) { events[name].apply(this, [e]); }); })(layer, ev); } this.layers.push(layer); return layer; }; GMaps.prototype.loadFromFusionTables = function(options) { var layer = this.getFromFusionTables(options); layer.setMap(this.map); return layer; }; GMaps.prototype.getFromKML = function(options) { var url = options.url, events = options.events; delete options.url; delete options.events; var kml_options = options, layer = new google.maps.KmlLayer(url, kml_options); for (var ev in events) { (function(object, name) { google.maps.event.addListener(object, name, function(e) { events[name].apply(this, [e]); }); })(layer, ev); } this.layers.push(layer); return layer; }; GMaps.prototype.loadFromKML = function(options) { var layer = this.getFromKML(options); layer.setMap(this.map); return layer; }; GMaps.prototype.addLayer = function(layerName, options) { //var default_layers = ['weather', 'clouds', 'traffic', 'transit', 'bicycling', 'panoramio', 'places']; options = options || {}; var layer; switch(layerName) { case 'weather': this.singleLayers.weather = layer = new google.maps.weather.WeatherLayer(); break; case 'clouds': this.singleLayers.clouds = layer = new google.maps.weather.CloudLayer(); break; case 'traffic': this.singleLayers.traffic = layer = new google.maps.TrafficLayer(); break; case 'transit': this.singleLayers.transit = layer = new google.maps.TransitLayer(); break; case 'bicycling': this.singleLayers.bicycling = layer = new google.maps.BicyclingLayer(); break; case 'panoramio': this.singleLayers.panoramio = layer = new google.maps.panoramio.PanoramioLayer(); layer.setTag(options.filter); delete options.filter; //click event if (options.click) { google.maps.event.addListener(layer, 'click', function(event) { options.click(event); delete options.click; }); } break; case 'places': this.singleLayers.places = layer = new google.maps.places.PlacesService(this.map); //search and nearbySearch callback, Both are the same if (options.search || options.nearbySearch) { var placeSearchRequest = { bounds : options.bounds || null, keyword : options.keyword || null, location : options.location || null, name : options.name || null, radius : options.radius || null, rankBy : options.rankBy || null, types : options.types || null }; if (options.search) { layer.search(placeSearchRequest, options.search); } if (options.nearbySearch) { layer.nearbySearch(placeSearchRequest, options.nearbySearch); } } //textSearch callback if (options.textSearch) { var textSearchRequest = { bounds : options.bounds || null, location : options.location || null, query : options.query || null, radius : options.radius || null }; layer.textSearch(textSearchRequest, options.textSearch); } break; } if (layer !== undefined) { if (typeof layer.setOptions == 'function') { layer.setOptions(options); } if (typeof layer.setMap == 'function') { layer.setMap(this.map); } return layer; } }; GMaps.prototype.removeLayer = function(layer) { if (typeof(layer) == "string" && this.singleLayers[layer] !== undefined) { this.singleLayers[layer].setMap(null); delete this.singleLayers[layer]; } else { for (var i = 0; i < this.layers.length; i++) { if (this.layers[i] === layer) { this.layers[i].setMap(null); this.layers.splice(i, 1); break; } } } }; var travelMode, unitSystem; GMaps.prototype.getRoutes = function(options) { switch (options.travelMode) { case 'bicycling': travelMode = google.maps.TravelMode.BICYCLING; break; case 'transit': travelMode = google.maps.TravelMode.TRANSIT; break; case 'driving': travelMode = google.maps.TravelMode.DRIVING; break; default: travelMode = google.maps.TravelMode.WALKING; break; } if (options.unitSystem === 'imperial') { unitSystem = google.maps.UnitSystem.IMPERIAL; } else { unitSystem = google.maps.UnitSystem.METRIC; } var base_options = { avoidHighways: false, avoidTolls: false, optimizeWaypoints: false, waypoints: [] }, request_options = extend_object(base_options, options); request_options.origin = /string/.test(typeof options.origin) ? options.origin : new google.maps.LatLng(options.origin[0], options.origin[1]); request_options.destination = /string/.test(typeof options.destination) ? options.destination : new google.maps.LatLng(options.destination[0], options.destination[1]); request_options.travelMode = travelMode; request_options.unitSystem = unitSystem; delete request_options.callback; delete request_options.error; var self = this, service = new google.maps.DirectionsService(); service.route(request_options, function(result, status) { if (status === google.maps.DirectionsStatus.OK) { for (var r in result.routes) { if (result.routes.hasOwnProperty(r)) { self.routes.push(result.routes[r]); } } if (options.callback) { options.callback(self.routes); } } else { if (options.error) { options.error(result, status); } } }); }; GMaps.prototype.removeRoutes = function() { this.routes = []; }; GMaps.prototype.getElevations = function(options) { options = extend_object({ locations: [], path : false, samples : 256 }, options); if (options.locations.length > 0) { if (options.locations[0].length > 0) { options.locations = array_flat(array_map([options.locations], arrayToLatLng, false)); } } var callback = options.callback; delete options.callback; var service = new google.maps.ElevationService(); //location request if (!options.path) { delete options.path; delete options.samples; service.getElevationForLocations(options, function(result, status) { if (callback && typeof(callback) === "function") { callback(result, status); } }); //path request } else { var pathRequest = { path : options.locations, samples : options.samples }; service.getElevationAlongPath(pathRequest, function(result, status) { if (callback && typeof(callback) === "function") { callback(result, status); } }); } }; GMaps.prototype.cleanRoute = GMaps.prototype.removePolylines; GMaps.prototype.drawRoute = function(options) { var self = this; this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints: options.waypoints, unitSystem: options.unitSystem, error: options.error, callback: function(e) { if (e.length > 0) { self.drawPolyline({ path: e[e.length - 1].overview_path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }); if (options.callback) { options.callback(e[e.length - 1]); } } } }); }; GMaps.prototype.travelRoute = function(options) { if (options.origin && options.destination) { this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints : options.waypoints, error: options.error, callback: function(e) { //start callback if (e.length > 0 && options.start) { options.start(e[e.length - 1]); } //step callback if (e.length > 0 && options.step) { var route = e[e.length - 1]; if (route.legs.length > 0) { var steps = route.legs[0].steps; for (var i=0, step; step=steps[i]; i++) { step.step_number = i; options.step(step, (route.legs[0].steps.length - 1)); } } } //end callback if (e.length > 0 && options.end) { options.end(e[e.length - 1]); } } }); } else if (options.route) { if (options.route.legs.length > 0) { var steps = options.route.legs[0].steps; for (var i=0, step; step=steps[i]; i++) { step.step_number = i; options.step(step); } } } }; GMaps.prototype.drawSteppedRoute = function(options) { var self = this; if (options.origin && options.destination) { this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints : options.waypoints, error: options.error, callback: function(e) { //start callback if (e.length > 0 && options.start) { options.start(e[e.length - 1]); } //step callback if (e.length > 0 && options.step) { var route = e[e.length - 1]; if (route.legs.length > 0) { var steps = route.legs[0].steps; for (var i=0, step; step=steps[i]; i++) { step.step_number = i; self.drawPolyline({ path: step.path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }); options.step(step, (route.legs[0].steps.length - 1)); } } } //end callback if (e.length > 0 && options.end) { options.end(e[e.length - 1]); } } }); } else if (options.route) { if (options.route.legs.length > 0) { var steps = options.route.legs[0].steps; for (var i=0, step; step=steps[i]; i++) { step.step_number = i; self.drawPolyline({ path: step.path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }); options.step(step); } } } }; GMaps.Route = function(options) { this.origin = options.origin; this.destination = options.destination; this.waypoints = options.waypoints; this.map = options.map; this.route = options.route; this.step_count = 0; this.steps = this.route.legs[0].steps; this.steps_length = this.steps.length; this.polyline = this.map.drawPolyline({ path: new google.maps.MVCArray(), strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }).getPath(); }; GMaps.Route.prototype.getRoute = function(options) { var self = this; this.map.getRoutes({ origin : this.origin, destination : this.destination, travelMode : options.travelMode, waypoints : this.waypoints || [], error: options.error, callback : function() { self.route = e[0]; if (options.callback) { options.callback.call(self); } } }); }; GMaps.Route.prototype.back = function() { if (this.step_count > 0) { this.step_count--; var path = this.route.legs[0].steps[this.step_count].path; for (var p in path){ if (path.hasOwnProperty(p)){ this.polyline.pop(); } } } }; GMaps.Route.prototype.forward = function() { if (this.step_count < this.steps_length) { var path = this.route.legs[0].steps[this.step_count].path; for (var p in path){ if (path.hasOwnProperty(p)){ this.polyline.push(path[p]); } } this.step_count++; } }; GMaps.prototype.checkGeofence = function(lat, lng, fence) { return fence.containsLatLng(new google.maps.LatLng(lat, lng)); }; GMaps.prototype.checkMarkerGeofence = function(marker, outside_callback) { if (marker.fences) { for (var i = 0, fence; fence = marker.fences[i]; i++) { var pos = marker.getPosition(); if (!this.checkGeofence(pos.lat(), pos.lng(), fence)) { outside_callback(marker, fence); } } } }; GMaps.prototype.toImage = function(options) { var options = options || {}, static_map_options = {}; static_map_options['size'] = options['size'] || [this.el.clientWidth, this.el.clientHeight]; static_map_options['lat'] = this.getCenter().lat(); static_map_options['lng'] = this.getCenter().lng(); if (this.markers.length > 0) { static_map_options['markers'] = []; for (var i = 0; i < this.markers.length; i++) { static_map_options['markers'].push({ lat: this.markers[i].getPosition().lat(), lng: this.markers[i].getPosition().lng() }); } } if (this.polylines.length > 0) { var polyline = this.polylines[0]; static_map_options['polyline'] = {}; static_map_options['polyline']['path'] = google.maps.geometry.encoding.encodePath(polyline.getPath()); static_map_options['polyline']['strokeColor'] = polyline.strokeColor static_map_options['polyline']['strokeOpacity'] = polyline.strokeOpacity static_map_options['polyline']['strokeWeight'] = polyline.strokeWeight } return GMaps.staticMapURL(static_map_options); }; GMaps.staticMapURL = function(options){ var parameters = [], data, static_root = 'http://maps.googleapis.com/maps/api/staticmap'; if (options.url) { static_root = options.url; delete options.url; } static_root += '?'; var markers = options.markers; delete options.markers; if (!markers && options.marker) { markers = [options.marker]; delete options.marker; } var styles = options.styles; delete options.styles; var polyline = options.polyline; delete options.polyline; /** Map options **/ if (options.center) { parameters.push('center=' + options.center); delete options.center; } else if (options.address) { parameters.push('center=' + options.address); delete options.address; } else if (options.lat) { parameters.push(['center=', options.lat, ',', options.lng].join('')); delete options.lat; delete options.lng; } else if (options.visible) { var visible = encodeURI(options.visible.join('|')); parameters.push('visible=' + visible); } var size = options.size; if (size) { if (size.join) { size = size.join('x'); } delete options.size; } else { size = '630x300'; } parameters.push('size=' + size); if (!options.zoom && options.zoom !== false) { options.zoom = 15; } var sensor = options.hasOwnProperty('sensor') ? !!options.sensor : true; delete options.sensor; parameters.push('sensor=' + sensor); for (var param in options) { if (options.hasOwnProperty(param)) { parameters.push(param + '=' + options[param]); } } /** Markers **/ if (markers) { var marker, loc; for (var i=0; data=markers[i]; i++) { marker = []; if (data.size && data.size !== 'normal') { marker.push('size:' + data.size); delete data.size; } else if (data.icon) { marker.push('icon:' + encodeURI(data.icon)); delete data.icon; } if (data.color) { marker.push('color:' + data.color.replace('#', '0x')); delete data.color; } if (data.label) { marker.push('label:' + data.label[0].toUpperCase()); delete data.label; } loc = (data.address ? data.address : data.lat + ',' + data.lng); delete data.address; delete data.lat; delete data.lng; for(var param in data){ if (data.hasOwnProperty(param)) { marker.push(param + ':' + data[param]); } } if (marker.length || i === 0) { marker.push(loc); marker = marker.join('|'); parameters.push('markers=' + encodeURI(marker)); } // New marker without styles else { marker = parameters.pop() + encodeURI('|' + loc); parameters.push(marker); } } } /** Map Styles **/ if (styles) { for (var i = 0; i < styles.length; i++) { var styleRule = []; if (styles[i].featureType && styles[i].featureType != 'all' ) { styleRule.push('feature:' + styles[i].featureType); } if (styles[i].elementType && styles[i].elementType != 'all') { styleRule.push('element:' + styles[i].elementType); } for (var j = 0; j < styles[i].stylers.length; j++) { for (var p in styles[i].stylers[j]) { var ruleArg = styles[i].stylers[j][p]; if (p == 'hue' || p == 'color') { ruleArg = '0x' + ruleArg.substring(1); } styleRule.push(p + ':' + ruleArg); } } var rule = styleRule.join('|'); if (rule != '') { parameters.push('style=' + rule); } } } /** Polylines **/ function parseColor(color, opacity) { if (color[0] === '#'){ color = color.replace('#', '0x'); if (opacity) { opacity = parseFloat(opacity); opacity = Math.min(1, Math.max(opacity, 0)); if (opacity === 0) { return '0x00000000'; } opacity = (opacity * 255).toString(16); if (opacity.length === 1) { opacity += opacity; } color = color.slice(0,8) + opacity; } } return color; } if (polyline) { data = polyline; polyline = []; if (data.strokeWeight) { polyline.push('weight:' + parseInt(data.strokeWeight, 10)); } if (data.strokeColor) { var color = parseColor(data.strokeColor, data.strokeOpacity); polyline.push('color:' + color); } if (data.fillColor) { var fillcolor = parseColor(data.fillColor, data.fillOpacity); polyline.push('fillcolor:' + fillcolor); } var path = data.path; if (path.join) { for (var j=0, pos; pos=path[j]; j++) { polyline.push(pos.join(',')); } } else { polyline.push('enc:' + path); } polyline = polyline.join('|'); parameters.push('path=' + encodeURI(polyline)); } /** Retina support **/ var dpi = window.devicePixelRatio || 1; parameters.push('scale=' + dpi); parameters = parameters.join('&'); return static_root + parameters; }; GMaps.prototype.addMapType = function(mapTypeId, options) { if (options.hasOwnProperty("getTileUrl") && typeof(options["getTileUrl"]) == "function") { options.tileSize = options.tileSize || new google.maps.Size(256, 256); var mapType = new google.maps.ImageMapType(options); this.map.mapTypes.set(mapTypeId, mapType); } else { throw "'getTileUrl' function required."; } }; GMaps.prototype.addOverlayMapType = function(options) { if (options.hasOwnProperty("getTile") && typeof(options["getTile"]) == "function") { var overlayMapTypeIndex = options.index; delete options.index; this.map.overlayMapTypes.insertAt(overlayMapTypeIndex, options); } else { throw "'getTile' function required."; } }; GMaps.prototype.removeOverlayMapType = function(overlayMapTypeIndex) { this.map.overlayMapTypes.removeAt(overlayMapTypeIndex); }; GMaps.prototype.addStyle = function(options) { var styledMapType = new google.maps.StyledMapType(options.styles, { name: options.styledMapName }); this.map.mapTypes.set(options.mapTypeId, styledMapType); }; GMaps.prototype.setStyle = function(mapTypeId) { this.map.setMapTypeId(mapTypeId); }; GMaps.prototype.createPanorama = function(streetview_options) { if (!streetview_options.hasOwnProperty('lat') || !streetview_options.hasOwnProperty('lng')) { streetview_options.lat = this.getCenter().lat(); streetview_options.lng = this.getCenter().lng(); } this.panorama = GMaps.createPanorama(streetview_options); this.map.setStreetView(this.panorama); return this.panorama; }; GMaps.createPanorama = function(options) { var el = getElementById(options.el, options.context); options.position = new google.maps.LatLng(options.lat, options.lng); delete options.el; delete options.context; delete options.lat; delete options.lng; var streetview_events = ['closeclick', 'links_changed', 'pano_changed', 'position_changed', 'pov_changed', 'resize', 'visible_changed'], streetview_options = extend_object({visible : true}, options); for (var i = 0; i < streetview_events.length; i++) { delete streetview_options[streetview_events[i]]; } var panorama = new google.maps.StreetViewPanorama(el, streetview_options); for (var i = 0; i < streetview_events.length; i++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(){ options[name].apply(this); }); } })(panorama, streetview_events[i]); } return panorama; }; GMaps.prototype.on = function(event_name, handler) { return GMaps.on(event_name, this, handler); }; GMaps.prototype.off = function(event_name) { GMaps.off(event_name, this); }; GMaps.custom_events = ['marker_added', 'marker_removed', 'polyline_added', 'polyline_removed', 'polygon_added', 'polygon_removed', 'geolocated', 'geolocation_failed']; GMaps.on = function(event_name, object, handler) { if (GMaps.custom_events.indexOf(event_name) == -1) { return google.maps.event.addListener(object, event_name, handler); } else { var registered_event = { handler : handler, eventName : event_name }; object.registered_events[event_name] = object.registered_events[event_name] || []; object.registered_events[event_name].push(registered_event); return registered_event; } }; GMaps.off = function(event_name, object) { if (GMaps.custom_events.indexOf(event_name) == -1) { google.maps.event.clearListeners(object, event_name); } else { object.registered_events[event_name] = []; } }; GMaps.fire = function(event_name, object, scope) { if (GMaps.custom_events.indexOf(event_name) == -1) { google.maps.event.trigger(object, event_name, Array.prototype.slice.apply(arguments).slice(2)); } else { if(event_name in scope.registered_events) { var firing_events = scope.registered_events[event_name]; for(var i = 0; i < firing_events.length; i++) { (function(handler, scope, object) { handler.apply(scope, [object]); })(firing_events[i]['handler'], scope, object); } } } }; GMaps.geolocate = function(options) { var complete_callback = options.always || options.complete; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { options.success(position); if (complete_callback) { complete_callback(); } }, function(error) { options.error(error); if (complete_callback) { complete_callback(); } }, options.options); } else { options.not_supported(); if (complete_callback) { complete_callback(); } } }; GMaps.geocode = function(options) { this.geocoder = new google.maps.Geocoder(); var callback = options.callback; if (options.hasOwnProperty('lat') && options.hasOwnProperty('lng')) { options.latLng = new google.maps.LatLng(options.lat, options.lng); } delete options.lat; delete options.lng; delete options.callback; this.geocoder.geocode(options, function(results, status) { callback(results, status); }); }; //========================== // Polygon containsLatLng // https://github.com/tparkin/Google-Maps-Point-in-Polygon // Poygon getBounds extension - google-maps-extensions // http://code.google.com/p/google-maps-extensions/source/browse/google.maps.Polygon.getBounds.js if (!google.maps.Polygon.prototype.getBounds) { google.maps.Polygon.prototype.getBounds = function(latLng) { var bounds = new google.maps.LatLngBounds(); var paths = this.getPaths(); var path; for (var p = 0; p < paths.getLength(); p++) { path = paths.getAt(p); for (var i = 0; i < path.getLength(); i++) { bounds.extend(path.getAt(i)); } } return bounds; }; } if (!google.maps.Polygon.prototype.containsLatLng) { // Polygon containsLatLng - method to determine if a latLng is within a polygon google.maps.Polygon.prototype.containsLatLng = function(latLng) { // Exclude points outside of bounds as there is no way they are in the poly var bounds = this.getBounds(); if (bounds !== null && !bounds.contains(latLng)) { return false; } // Raycast point in polygon method var inPoly = false; var numPaths = this.getPaths().getLength(); for (var p = 0; p < numPaths; p++) { var path = this.getPaths().getAt(p); var numPoints = path.getLength(); var j = numPoints - 1; for (var i = 0; i < numPoints; i++) { var vertex1 = path.getAt(i); var vertex2 = path.getAt(j); if (vertex1.lng() < latLng.lng() && vertex2.lng() >= latLng.lng() || vertex2.lng() < latLng.lng() && vertex1.lng() >= latLng.lng()) { if (vertex1.lat() + (latLng.lng() - vertex1.lng()) / (vertex2.lng() - vertex1.lng()) * (vertex2.lat() - vertex1.lat()) < latLng.lat()) { inPoly = !inPoly; } } j = i; } } return inPoly; }; } google.maps.LatLngBounds.prototype.containsLatLng = function(latLng) { return this.contains(latLng); }; google.maps.Marker.prototype.setFences = function(fences) { this.fences = fences; }; google.maps.Marker.prototype.addFence = function(fence) { this.fences.push(fence); }; google.maps.Marker.prototype.getId = function() { return this['__gm_id']; }; //========================== // Array indexOf // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { "use strict"; if (this == null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it's NaN n = 0; } else if (n != 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; } } return GMaps; }));
JavaScript
/* Uniform v2.1.0 Copyright © 2009 Josh Pyles / Pixelmatrix Design LLC http://pixelmatrixdesign.com Requires jQuery 1.3 or newer Much thanks to Thomas Reynolds and Buck Wilson for their help and advice on this. Disabling text selection is made possible by Mathias Bynens <http://mathiasbynens.be/> and his noSelect plugin. <https://github.com/mathiasbynens/jquery-noselect>, which is embedded. Also, thanks to David Kaneda and Eugene Bond for their contributions to the plugin. Tyler Akins has also rewritten chunks of the plugin, helped close many issues, and ensured version 2 got out the door. License: MIT License - http://www.opensource.org/licenses/mit-license.php Enjoy! */ /*global jQuery, window, document, navigator*/ (function ($, undef) { "use strict"; /** * Use .prop() if jQuery supports it, otherwise fall back to .attr() * * @param jQuery $el jQuery'd element on which we're calling attr/prop * @param ... All other parameters are passed to jQuery's function * @return The result from jQuery */ function attrOrProp($el) { var args = Array.prototype.slice.call(arguments, 1); if ($el.prop) { // jQuery 1.6+ return $el.prop.apply($el, args); } // jQuery 1.5 and below return $el.attr.apply($el, args); } /** * For backwards compatibility with older jQuery libraries, only bind * one thing at a time. Also, this function adds our namespace to * events in one consistent location, shrinking the minified code. * * The properties on the events object are the names of the events * that we are supposed to add to. It can be a space separated list. * The namespace will be added automatically. * * @param jQuery $el * @param Object options Uniform options for this element * @param Object events Events to bind, properties are event names */ function bindMany($el, options, events) { var name, namespaced; for (name in events) { if (events.hasOwnProperty(name)) { namespaced = name.replace(/ |$/g, options.eventNamespace); $el.bind(namespaced, events[name]); } } } /** * Bind the hover, active, focus, and blur UI updates * * @param jQuery $el Original element * @param jQuery $target Target for the events (our div/span) * @param Object options Uniform options for the element $target */ function bindUi($el, $target, options) { bindMany($el, options, { focus: function () { $target.addClass(options.focusClass); }, blur: function () { $target.removeClass(options.focusClass); $target.removeClass(options.activeClass); }, mouseenter: function () { $target.addClass(options.hoverClass); }, mouseleave: function () { $target.removeClass(options.hoverClass); $target.removeClass(options.activeClass); }, "mousedown touchbegin": function () { if (!$el.is(":disabled")) { $target.addClass(options.activeClass); } }, "mouseup touchend": function () { $target.removeClass(options.activeClass); } }); } /** * Remove the hover, focus, active classes. * * @param jQuery $el Element with classes * @param Object options Uniform options for the element */ function classClearStandard($el, options) { $el.removeClass(options.hoverClass + " " + options.focusClass + " " + options.activeClass); } /** * Add or remove a class, depending on if it's "enabled" * * @param jQuery $el Element that has the class added/removed * @param String className Class or classes to add/remove * @param Boolean enabled True to add the class, false to remove */ function classUpdate($el, className, enabled) { if (enabled) { $el.addClass(className); } else { $el.removeClass(className); } } /** * Updating the "checked" property can be a little tricky. This * changed in jQuery 1.6 and now we can pass booleans to .prop(). * Prior to that, one either adds an attribute ("checked=checked") or * removes the attribute. * * @param jQuery $tag Our Uniform span/div * @param jQuery $el Original form element * @param Object options Uniform options for this element */ function classUpdateChecked($tag, $el, options) { var c = "checked", isChecked = $el.is(":" + c); if ($el.prop) { // jQuery 1.6+ $el.prop(c, isChecked); } else { // jQuery 1.5 and below if (isChecked) { $el.attr(c, c); } else { $el.removeAttr(c); } } classUpdate($tag, options.checkedClass, isChecked); } /** * Set or remove the "disabled" class for disabled elements, based on * if the * * @param jQuery $tag Our Uniform span/div * @param jQuery $el Original form element * @param Object options Uniform options for this element */ function classUpdateDisabled($tag, $el, options) { classUpdate($tag, options.disabledClass, $el.is(":disabled")); } /** * Wrap an element inside of a container or put the container next * to the element. See the code for examples of the different methods. * * Returns the container that was added to the HTML. * * @param jQuery $el Element to wrap * @param jQuery $container Add this new container around/near $el * @param String method One of "after", "before" or "wrap" * @return $container after it has been cloned for adding to $el */ function divSpanWrap($el, $container, method) { switch (method) { case "after": // Result: <element /> <container /> $el.after($container); return $el.next(); case "before": // Result: <container /> <element /> $el.before($container); return $el.prev(); case "wrap": // Result: <container> <element /> </container> $el.wrap($container); return $el.parent(); } return null; } /** * Create a div/span combo for uniforming an element * * @param jQuery $el Element to wrap * @param Object options Options for the element, set by the user * @param Object divSpanConfig Options for how we wrap the div/span * @return Object Contains the div and span as properties */ function divSpan($el, options, divSpanConfig) { var $div, $span, id; if (!divSpanConfig) { divSpanConfig = {}; } divSpanConfig = $.extend({ bind: {}, divClass: null, divWrap: "wrap", spanClass: null, spanHtml: null, spanWrap: "wrap" }, divSpanConfig); $div = $('<div />'); $span = $('<span />'); // Automatically hide this div/span if the element is hidden. // Do not hide if the element is hidden because a parent is hidden. if (options.autoHide && $el.is(':hidden') && $el.css('display') === 'none') { $div.hide(); } if (divSpanConfig.divClass) { $div.addClass(divSpanConfig.divClass); } if (options.wrapperClass) { $div.addClass(options.wrapperClass); } if (divSpanConfig.spanClass) { $span.addClass(divSpanConfig.spanClass); } id = attrOrProp($el, 'id'); if (options.useID && id) { attrOrProp($div, 'id', options.idPrefix + '-' + id); } if (divSpanConfig.spanHtml) { $span.html(divSpanConfig.spanHtml); } $div = divSpanWrap($el, $div, divSpanConfig.divWrap); $span = divSpanWrap($el, $span, divSpanConfig.spanWrap); classUpdateDisabled($div, $el, options); return { div: $div, span: $span }; } /** * Wrap an element with a span to apply a global wrapper class * * @param jQuery $el Element to wrap * @param object options * @return jQuery Wrapper element */ function wrapWithWrapperClass($el, options) { var $span; if (!options.wrapperClass) { return null; } $span = $('<span />').addClass(options.wrapperClass); $span = divSpanWrap($el, $span, "wrap"); return $span; } /** * Test if high contrast mode is enabled. * * In high contrast mode, background images can not be set and * they are always returned as 'none'. * * @return boolean True if in high contrast mode */ function highContrast() { var c, $div, el, rgb; // High contrast mode deals with white and black rgb = 'rgb(120,2,153)'; $div = $('<div style="width:0;height:0;color:' + rgb + '">'); $('body').append($div); el = $div.get(0); // $div.css() will get the style definition, not // the actually displaying style if (window.getComputedStyle) { c = window.getComputedStyle(el, '').color; } else { c = (el.currentStyle || el.style || {}).color; } $div.remove(); return c.replace(/ /g, '') !== rgb; } /** * Change text into safe HTML * * @param String text * @return String HTML version */ function htmlify(text) { if (!text) { return ""; } return $('<span />').text(text).html(); } /** * If not MSIE, return false. * If it is, return the version number. * * @return false|number */ function isMsie() { return navigator.cpuClass && !navigator.product; } /** * Return true if this version of IE allows styling * * @return boolean */ function isMsieSevenOrNewer() { if (typeof window.XMLHttpRequest !== 'undefined') { return true; } return false; } /** * Test if the element is a multiselect * * @param jQuery $el Element * @return boolean true/false */ function isMultiselect($el) { var elSize; if ($el[0].multiple) { return true; } elSize = attrOrProp($el, "size"); if (!elSize || elSize <= 1) { return false; } return true; } /** * Meaningless utility function. Used mostly for improving minification. * * @return false */ function returnFalse() { return false; } /** * noSelect plugin, very slightly modified * http://mths.be/noselect v1.0.3 * * @param jQuery $elem Element that we don't want to select * @param Object options Uniform options for the element */ function noSelect($elem, options) { var none = 'none'; bindMany($elem, options, { 'selectstart dragstart mousedown': returnFalse }); $elem.css({ MozUserSelect: none, msUserSelect: none, webkitUserSelect: none, userSelect: none }); } /** * Updates the filename tag based on the value of the real input * element. * * @param jQuery $el Actual form element * @param jQuery $filenameTag Span/div to update * @param Object options Uniform options for this element */ function setFilename($el, $filenameTag, options) { var filename = $el.val(); if (filename === "") { filename = options.fileDefaultHtml; } else { filename = filename.split(/[\/\\]+/); filename = filename[(filename.length - 1)]; } $filenameTag.text(filename); } /** * Function from jQuery to swap some CSS values, run a callback, * then restore the CSS. Modified to pass JSLint and handle undefined * values with 'use strict'. * * @param jQuery $el Element * @param object newCss CSS values to swap out * @param Function callback Function to run */ function swap($elements, newCss, callback) { var restore, item; restore = []; $elements.each(function () { var name; for (name in newCss) { if (Object.prototype.hasOwnProperty.call(newCss, name)) { restore.push({ el: this, name: name, old: this.style[name] }); this.style[name] = newCss[name]; } } }); callback(); while (restore.length) { item = restore.pop(); item.el.style[item.name] = item.old; } } /** * The browser doesn't provide sizes of elements that are not visible. * This will clone an element and add it to the DOM for calculations. * * @param jQuery $el * @param String method */ function sizingInvisible($el, callback) { var targets; // We wish to target ourselves and any parents as long as // they are not visible targets = $el.parents(); targets.push($el[0]); targets = targets.not(':visible'); swap(targets, { visibility: "hidden", display: "block", position: "absolute" }, callback); } /** * Standard way to unwrap the div/span combination from an element * * @param jQuery $el Element that we wish to preserve * @param Object options Uniform options for the element * @return Function This generated function will perform the given work */ function unwrapUnwrapUnbindFunction($el, options) { return function () { $el.unwrap().unwrap().unbind(options.eventNamespace); }; } var allowStyling = true, // False if IE6 or other unsupported browsers highContrastTest = false, // Was the high contrast test ran? uniformHandlers = [ // Objects that take care of "unification" { // Buttons match: function ($el) { return $el.is("a, button, :submit, :reset, input[type='button']"); }, apply: function ($el, options) { var $div, defaultSpanHtml, ds, getHtml, doingClickEvent; defaultSpanHtml = options.submitDefaultHtml; if ($el.is(":reset")) { defaultSpanHtml = options.resetDefaultHtml; } if ($el.is("a, button")) { // Use the HTML inside the tag getHtml = function () { return $el.html() || defaultSpanHtml; }; } else { // Use the value property of the element getHtml = function () { return htmlify(attrOrProp($el, "value")) || defaultSpanHtml; }; } ds = divSpan($el, options, { divClass: options.buttonClass, spanHtml: getHtml(), }); $div = ds.div; bindUi($el, $div, options); doingClickEvent = false; bindMany($div, options, { "click touchend": function () { var ev, res, target, href; if (doingClickEvent) { return; } if ($el.is(':disabled')) { return; } doingClickEvent = true; if ($el[0].dispatchEvent) { ev = document.createEvent("MouseEvents"); ev.initEvent("click", true, true); res = $el[0].dispatchEvent(ev); if ($el.is('a') && res) { target = attrOrProp($el, 'target'); href = attrOrProp($el, 'href'); if (!target || target === '_self') { document.location.href = href; } else { window.open(href, target); } } } else { $el.click(); } doingClickEvent = false; } }); noSelect($div, options); return { remove: function () { // Move $el out $div.after($el); // Remove div and span $div.remove(); // Unbind events $el.unbind(options.eventNamespace); return $el; }, update: function () { classClearStandard($div, options); classUpdateDisabled($div, $el, options); $el.detach(); ds.span.html(getHtml()).append($el); } }; } }, { // Checkboxes match: function ($el) { return $el.is(":checkbox"); }, apply: function ($el, options) { var ds, $div, $span; ds = divSpan($el, options, { divClass: options.checkboxClass }); $div = ds.div; $span = ds.span; // Add focus classes, toggling, active, etc. bindUi($el, $div, options); bindMany($el, options, { "click touchend": function () { classUpdateChecked($span, $el, options); } }); classUpdateChecked($span, $el, options); return { remove: unwrapUnwrapUnbindFunction($el, options), update: function () { classClearStandard($div, options); $span.removeClass(options.checkedClass); classUpdateChecked($span, $el, options); classUpdateDisabled($div, $el, options); } }; } }, { // File selection / uploads match: function ($el) { return $el.is(":file"); }, apply: function ($el, options) { var ds, $div, $filename, $button; // The "span" is the button ds = divSpan($el, options, { divClass: options.fileClass, spanClass: options.fileButtonClass, spanHtml: options.fileButtonHtml, spanWrap: "after" }); $div = ds.div; $button = ds.span; $filename = $("<span />").html(options.fileDefaultHtml); $filename.addClass(options.filenameClass); $filename = divSpanWrap($el, $filename, "after"); // Set the size if (!attrOrProp($el, "size")) { attrOrProp($el, "size", $div.width() / 10); } // Actions function filenameUpdate() { setFilename($el, $filename, options); } bindUi($el, $div, options); // Account for input saved across refreshes filenameUpdate(); // IE7 doesn't fire onChange until blur or second fire. if (isMsie()) { // IE considers browser chrome blocking I/O, so it // suspends tiemouts until after the file has // been selected. bindMany($el, options, { click: function () { $el.trigger("change"); setTimeout(filenameUpdate, 0); } }); } else { // All other browsers behave properly bindMany($el, options, { change: filenameUpdate }); } noSelect($filename, options); noSelect($button, options); return { remove: function () { // Remove filename and button $filename.remove(); $button.remove(); // Unwrap parent div, remove events return $el.unwrap().unbind(options.eventNamespace); }, update: function () { classClearStandard($div, options); setFilename($el, $filename, options); classUpdateDisabled($div, $el, options); } }; } }, { // Input fields (text) match: function ($el) { if ($el.is("input")) { var t = (" " + attrOrProp($el, "type") + " ").toLowerCase(), allowed = " color date datetime datetime-local email month number password search tel text time url week "; return allowed.indexOf(t) >= 0; } return false; }, apply: function ($el, options) { var elType, $wrapper; elType = attrOrProp($el, "type"); $el.addClass(options.inputClass); $wrapper = wrapWithWrapperClass($el, options); bindUi($el, $el, options); if (options.inputAddTypeAsClass) { $el.addClass(elType); } return { remove: function () { $el.removeClass(options.inputClass); if (options.inputAddTypeAsClass) { $el.removeClass(elType); } if ($wrapper) { $el.unwrap(); } }, update: returnFalse }; } }, { // Radio buttons match: function ($el) { return $el.is(":radio"); }, apply: function ($el, options) { var ds, $div, $span; ds = divSpan($el, options, { divClass: options.radioClass }); $div = ds.div; $span = ds.span; // Add classes for focus, handle active, checked bindUi($el, $div, options); bindMany($el, options, { "click touchend": function () { // Find all radios with the same name, then update // them with $.uniform.update() so the right // per-element options are used $.uniform.update($(':radio[name="' + attrOrProp($el, "name") + '"]')); } }); classUpdateChecked($span, $el, options); return { remove: unwrapUnwrapUnbindFunction($el, options), update: function () { classClearStandard($div, options); classUpdateChecked($span, $el, options); classUpdateDisabled($div, $el, options); } }; } }, { // Select lists, but do not style multiselects here match: function ($el) { if ($el.is("select") && !isMultiselect($el)) { return true; } return false; }, apply: function ($el, options) { var ds, $div, $span, origElemWidth; if (options.selectAutoWidth) { sizingInvisible($el, function () { origElemWidth = $el.width(); }); } ds = divSpan($el, options, { divClass: options.selectClass, spanHtml: ($el.find(":selected:first") || $el.find("option:first")).html(), spanWrap: "before" }); $div = ds.div; $span = ds.span; if (options.selectAutoWidth) { // Use the width of the select and adjust the // span and div accordingly sizingInvisible($el, function () { // Force "display: block" - related to bug #287 swap($([ $span[0], $div[0] ]), { display: "block" }, function () { var spanPad; spanPad = $span.outerWidth() - $span.width(); $div.width(origElemWidth + spanPad); $span.width(origElemWidth); }); }); } else { // Force the select to fill the size of the div $div.addClass('fixedWidth'); } // Take care of events bindUi($el, $div, options); bindMany($el, options, { change: function () { $span.html($el.find(":selected").html()); $div.removeClass(options.activeClass); }, "click touchend": function () { // IE7 and IE8 may not update the value right // until after click event - issue #238 var selHtml = $el.find(":selected").html(); if ($span.html() !== selHtml) { // Change was detected // Fire the change event on the select tag $el.trigger('change'); } }, keyup: function () { $span.html($el.find(":selected").html()); } }); noSelect($span, options); return { remove: function () { // Remove sibling span $span.remove(); // Unwrap parent div $el.unwrap().unbind(options.eventNamespace); return $el; }, update: function () { if (options.selectAutoWidth) { // Easier to remove and reapply formatting $.uniform.restore($el); $el.uniform(options); } else { classClearStandard($div, options); // Reset current selected text $span.html($el.find(":selected").html()); classUpdateDisabled($div, $el, options); } } }; } }, { // Select lists - multiselect lists only match: function ($el) { if ($el.is("select") && isMultiselect($el)) { return true; } return false; }, apply: function ($el, options) { var $wrapper; $el.addClass(options.selectMultiClass); $wrapper = wrapWithWrapperClass($el, options); bindUi($el, $el, options); return { remove: function () { $el.removeClass(options.selectMultiClass); if ($wrapper) { $el.unwrap(); } }, update: returnFalse }; } }, { // Textareas match: function ($el) { return $el.is("textarea"); }, apply: function ($el, options) { var $wrapper; $el.addClass(options.textareaClass); $wrapper = wrapWithWrapperClass($el, options); bindUi($el, $el, options); return { remove: function () { $el.removeClass(options.textareaClass); if ($wrapper) { $el.unwrap(); } }, update: returnFalse }; } } ]; // IE6 can't be styled - can't set opacity on select if (isMsie() && !isMsieSevenOrNewer()) { allowStyling = false; } $.uniform = { // Default options that can be overridden globally or when uniformed // globally: $.uniform.defaults.fileButtonHtml = "Pick A File"; // on uniform: $('input').uniform({fileButtonHtml: "Pick a File"}); defaults: { activeClass: "active", autoHide: true, buttonClass: "button", checkboxClass: "checker", checkedClass: "checked", disabledClass: "disabled", eventNamespace: ".uniform", fileButtonClass: "action", fileButtonHtml: "Choose File", fileClass: "uploader", fileDefaultHtml: "No file selected", filenameClass: "filename", focusClass: "focus", hoverClass: "hover", idPrefix: "uniform", inputAddTypeAsClass: true, inputClass: "uniform-input", radioClass: "radio", resetDefaultHtml: "Reset", resetSelector: false, // We'll use our own function when you don't specify one selectAutoWidth: true, selectClass: "selector", selectMultiClass: "uniform-multiselect", submitDefaultHtml: "Submit", // Only text allowed textareaClass: "uniform", useID: true, wrapperClass: null }, // All uniformed elements - DOM objects elements: [] }; $.fn.uniform = function (options) { var el = this; options = $.extend({}, $.uniform.defaults, options); // If we are in high contrast mode, do not allow styling if (!highContrastTest) { highContrastTest = true; if (highContrast()) { allowStyling = false; } } // Only uniform on browsers that work if (!allowStyling) { return this; } // Code for specifying a reset button if (options.resetSelector) { $(options.resetSelector).mouseup(function () { window.setTimeout(function () { $.uniform.update(el); }, 10); }); } return this.each(function () { var $el = $(this), i, handler, callbacks; // Avoid uniforming elements already uniformed - just update if ($el.data("uniformed")) { $.uniform.update($el); return; } // See if we have any handler for this type of element for (i = 0; i < uniformHandlers.length; i = i + 1) { handler = uniformHandlers[i]; if (handler.match($el, options)) { callbacks = handler.apply($el, options); $el.data("uniformed", callbacks); // Store element in our global array $.uniform.elements.push($el.get(0)); return; } } // Could not style this element }); }; $.uniform.restore = $.fn.uniform.restore = function (elem) { if (elem === undef) { elem = $.uniform.elements; } $(elem).each(function () { var $el = $(this), index, elementData; elementData = $el.data("uniformed"); // Skip elements that are not uniformed if (!elementData) { return; } // Unbind events, remove additional markup that was added elementData.remove(); // Remove item from list of uniformed elements index = $.inArray(this, $.uniform.elements); if (index >= 0) { $.uniform.elements.splice(index, 1); } $el.removeData("uniformed"); }); }; $.uniform.update = $.fn.uniform.update = function (elem) { if (elem === undef) { elem = $.uniform.elements; } $(elem).each(function () { var $el = $(this), elementData; elementData = $el.data("uniformed"); // Skip elements that are not uniformed if (!elementData) { return; } elementData.update($el, elementData.options); }); }; }(jQuery));
JavaScript
/* * Toastr * Version 2.0.1 * Copyright 2012 John Papa and Hans Fjällemark. * All Rights Reserved. * Use, reproduction, distribution, and modification of this code is subject to the terms and * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php * * Author: John Papa and Hans Fjällemark * Project: https://github.com/CodeSeven/toastr */ ; (function (define) { define(['jquery'], function ($) { return (function () { var version = '2.0.1'; var $container; var listener; var toastId = 0; var toastType = { error: 'error', info: 'info', success: 'success', warning: 'warning' }; var toastr = { clear: clear, error: error, getContainer: getContainer, info: info, options: {}, subscribe: subscribe, success: success, version: version, warning: warning }; return toastr; //#region Accessible Methods function error(message, title, optionsOverride) { return notify({ type: toastType.error, iconClass: getOptions().iconClasses.error, message: message, optionsOverride: optionsOverride, title: title }); } function info(message, title, optionsOverride) { return notify({ type: toastType.info, iconClass: getOptions().iconClasses.info, message: message, optionsOverride: optionsOverride, title: title }); } function subscribe(callback) { listener = callback; } function success(message, title, optionsOverride) { return notify({ type: toastType.success, iconClass: getOptions().iconClasses.success, message: message, optionsOverride: optionsOverride, title: title }); } function warning(message, title, optionsOverride) { return notify({ type: toastType.warning, iconClass: getOptions().iconClasses.warning, message: message, optionsOverride: optionsOverride, title: title }); } function clear($toastElement) { var options = getOptions(); if (!$container) { getContainer(options); } if ($toastElement && $(':focus', $toastElement).length === 0) { $toastElement[options.hideMethod]({ duration: options.hideDuration, easing: options.hideEasing, complete: function () { removeToast($toastElement); } }); return; } if ($container.children().length) { $container[options.hideMethod]({ duration: options.hideDuration, easing: options.hideEasing, complete: function () { $container.remove(); } }); } } //#endregion //#region Internal Methods function getDefaults() { return { tapToDismiss: true, toastClass: 'toast', containerId: 'toast-container', debug: false, showMethod: 'fadeIn', //fadeIn, slideDown, and show are built into jQuery showDuration: 300, showEasing: 'swing', //swing and linear are built into jQuery onShown: undefined, hideMethod: 'fadeOut', hideDuration: 1000, hideEasing: 'swing', onHidden: undefined, extendedTimeOut: 1000, iconClasses: { error: 'toast-error', info: 'toast-info', success: 'toast-success', warning: 'toast-warning' }, iconClass: 'toast-info', positionClass: 'toast-top-right', timeOut: 5000, // Set timeOut and extendedTimeout to 0 to make it sticky titleClass: 'toast-title', messageClass: 'toast-message', target: 'body', closeHtml: '<button>&times;</button>', newestOnTop: true }; } function publish(args) { if (!listener) { return; } listener(args); } function notify(map) { var options = getOptions(), iconClass = map.iconClass || options.iconClass; if (typeof (map.optionsOverride) !== 'undefined') { options = $.extend(options, map.optionsOverride); iconClass = map.optionsOverride.iconClass || iconClass; } toastId++; $container = getContainer(options); var intervalId = null, $toastElement = $('<div/>'), $titleElement = $('<div/>'), $messageElement = $('<div/>'), $closeElement = $(options.closeHtml), response = { toastId: toastId, state: 'visible', startTime: new Date(), options: options, map: map }; if (map.iconClass) { $toastElement.addClass(options.toastClass).addClass(iconClass); } if (map.title) { $titleElement.append(map.title).addClass(options.titleClass); $toastElement.append($titleElement); } if (map.message) { $messageElement.append(map.message).addClass(options.messageClass); $toastElement.append($messageElement); } if (options.closeButton) { $closeElement.addClass('toast-close-button'); $toastElement.prepend($closeElement); } $toastElement.hide(); if (options.newestOnTop) { $container.prepend($toastElement); } else { $container.append($toastElement); } $toastElement[options.showMethod]( { duration: options.showDuration, easing: options.showEasing, complete: options.onShown } ); if (options.timeOut > 0) { intervalId = setTimeout(hideToast, options.timeOut); } $toastElement.hover(stickAround, delayedhideToast); if (!options.onclick && options.tapToDismiss) { $toastElement.click(hideToast); } if (options.closeButton && $closeElement) { $closeElement.click(function (event) { event.stopPropagation(); hideToast(true); }); } if (options.onclick) { $toastElement.click(function () { options.onclick(); hideToast(); }); } publish(response); if (options.debug && console) { console.log(response); } return $toastElement; function hideToast(override) { if ($(':focus', $toastElement).length && !override) { return; } return $toastElement[options.hideMethod]({ duration: options.hideDuration, easing: options.hideEasing, complete: function () { removeToast($toastElement); if (options.onHidden) { options.onHidden(); } response.state = 'hidden'; response.endTime = new Date(), publish(response); } }); } function delayedhideToast() { if (options.timeOut > 0 || options.extendedTimeOut > 0) { intervalId = setTimeout(hideToast, options.extendedTimeOut); } } function stickAround() { clearTimeout(intervalId); $toastElement.stop(true, true)[options.showMethod]( { duration: options.showDuration, easing: options.showEasing } ); } } function getContainer(options) { if (!options) { options = getOptions(); } $container = $('#' + options.containerId); if ($container.length) { return $container; } $container = $('<div/>') .attr('id', options.containerId) .addClass(options.positionClass); $container.appendTo($(options.target)); return $container; } function getOptions() { return $.extend({}, getDefaults(), toastr.options); } function removeToast($toastElement) { if (!$container) { $container = getContainer(); } if ($toastElement.is(':visible')) { return; } $toastElement.remove(); $toastElement = null; if ($container.children().length === 0) { $container.remove(); } } //#endregion })(); }); }(typeof define === 'function' && define.amd ? define : function (deps, factory) { if (typeof module !== 'undefined' && module.exports) { //Node module.exports = factory(require(deps[0])); } else { window['toastr'] = factory(window['jQuery']); } }));
JavaScript
/** * @preserve * bootpag - jQuery plugin for dynamic pagination * * Copyright (c) 2013 botmonster@7items.com * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * http://botmonster.com/jquery-bootpag/ * * Version: 1.0.5 * */ (function($, window) { $.fn.bootpag = function(options){ var $owner = this, settings = $.extend({ total: 0, page: 1, maxVisible: null, leaps: true, href: 'javascript:void(0);', hrefVariable: '{{number}}', next: '&raquo;', prev: '&laquo;' }, $owner.data('settings') || {}, options || {}); if(settings.total <= 0) return this; if(!$.isNumeric(settings.maxVisible) && !settings.maxVisible){ settings.maxVisible = settings.total; } $owner.data('settings', settings); function renderPage($bootpag, page){ var lp, maxV = settings.maxVisible == 0 ? 1 : settings.maxVisible, step = settings.maxVisible == 1 ? 0 : 1, vis = Math.floor((page - 1) / maxV) * maxV, $page = $bootpag.find('li'); settings.page = page = page < 0 ? 0 : page > settings.total ? settings.total : page; $page.removeClass('disabled'); lp = page - 1 < 1 ? 1 : settings.leaps && page - 1 >= settings.maxVisible ? Math.floor((page - 1) / maxV) * maxV : page - 1; $page .first() .toggleClass('disabled', page === 1) .attr('data-lp', lp) .find('a').attr('href', href(lp)); var step = settings.maxVisible == 1 ? 0 : 1; lp = page + 1 > settings.total ? settings.total : settings.leaps && page + 1 < settings.total - settings.maxVisible ? vis + settings.maxVisible + step: page + 1; $page .last() .toggleClass('disabled', page === settings.total) .attr('data-lp', lp) .find('a').attr('href', href(lp));; var $currPage = $page.filter('[data-lp='+page+']'); if(!$currPage.not('.next,.prev').length){ var d = page <= vis ? -settings.maxVisible : 0; $page.not('.next,.prev').each(function(index){ lp = index + 1 + vis + d; $(this) .attr('data-lp', lp) .toggle(lp <= settings.total) .find('a').html(lp).attr('href', href(lp)); }); $currPage = $page.filter('[data-lp='+page+']'); } $currPage.addClass('disabled'); $owner.data('settings', settings); } function href(c){ return settings.href.replace(settings.hrefVariable, c); } return this.each(function(){ var $bootpag, lp, me = $(this), p = ['<ul class="pagination bootpag">']; if(settings.prev){ p.push('<li data-lp="1" class="prev"><a href="'+href(1)+'">'+settings.prev+'</a></li>'); } for(var c = 1; c <= Math.min(settings.total, settings.maxVisible); c++){ p.push('<li data-lp="'+c+'"><a href="'+href(c)+'">'+c+'</a></li>'); } if(settings.next){ lp = settings.leaps && settings.total > settings.maxVisible ? Math.min(settings.maxVisible + 1, settings.total) : 2; p.push('<li data-lp="'+lp+'" class="next"><a href="'+href(lp)+'">'+settings.next+'</a></li>'); } p.push('</ul>'); me.find('ul.bootpag').remove(); me.append(p.join('')); $bootpag = me.find('ul.bootpag'); me.find('li').click(function paginationClick(){ var me = $(this); if(me.hasClass('disabled')){ return; } var page = parseInt(me.attr('data-lp'), 10); renderPage($bootpag, page); $owner.trigger('page', page); }); renderPage($bootpag, settings.page); }); } })(jQuery, window);
JavaScript
/* Masked Input plugin for jQuery Copyright (c) 2007-2013 Josh Bush (digitalbush.com) Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) Version: 1.3.1 */ (function($) { function getPasteEvent() { var el = document.createElement('input'), name = 'onpaste'; el.setAttribute(name, ''); return (typeof el[name] === 'function')?'paste':'input'; } var pasteEventName = getPasteEvent() + ".mask", ua = navigator.userAgent, iPhone = /iphone/i.test(ua), android=/android/i.test(ua), caretTimeoutId; $.mask = { //Predefined character definitions definitions: { '9': "[0-9]", 'a': "[A-Za-z]", '*': "[A-Za-z0-9]" }, dataName: "rawMaskFn", placeholder: '_', }; $.fn.extend({ //Helper Function for Caret positioning caret: function(begin, end) { var range; if (this.length === 0 || this.is(":hidden")) { return; } if (typeof begin == 'number') { end = (typeof end === 'number') ? end : begin; return this.each(function() { if (this.setSelectionRange) { this.setSelectionRange(begin, end); } else if (this.createTextRange) { range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } }); } else { if (this[0].setSelectionRange) { begin = this[0].selectionStart; end = this[0].selectionEnd; } else if (document.selection && document.selection.createRange) { range = document.selection.createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } return { begin: begin, end: end }; } }, unmask: function() { return this.trigger("unmask"); }, mask: function(mask, settings) { var input, defs, tests, partialPosition, firstNonMaskPos, len; if (!mask && this.length > 0) { input = $(this[0]); return input.data($.mask.dataName)(); } settings = $.extend({ placeholder: $.mask.placeholder, // Load default placeholder completed: null }, settings); defs = $.mask.definitions; tests = []; partialPosition = len = mask.length; firstNonMaskPos = null; $.each(mask.split(""), function(i, c) { if (c == '?') { len--; partialPosition = i; } else if (defs[c]) { tests.push(new RegExp(defs[c])); if (firstNonMaskPos === null) { firstNonMaskPos = tests.length - 1; } } else { tests.push(null); } }); return this.trigger("unmask").each(function() { var input = $(this), buffer = $.map( mask.split(""), function(c, i) { if (c != '?') { return defs[c] ? settings.placeholder : c; } }), focusText = input.val(); function seekNext(pos) { while (++pos < len && !tests[pos]); return pos; } function seekPrev(pos) { while (--pos >= 0 && !tests[pos]); return pos; } function shiftL(begin,end) { var i, j; if (begin<0) { return; } for (i = begin, j = seekNext(end); i < len; i++) { if (tests[i]) { if (j < len && tests[i].test(buffer[j])) { buffer[i] = buffer[j]; buffer[j] = settings.placeholder; } else { break; } j = seekNext(j); } } writeBuffer(); input.caret(Math.max(firstNonMaskPos, begin)); } function shiftR(pos) { var i, c, j, t; for (i = pos, c = settings.placeholder; i < len; i++) { if (tests[i]) { j = seekNext(i); t = buffer[i]; buffer[i] = c; if (j < len && tests[j].test(t)) { c = t; } else { break; } } } } function keydownEvent(e) { var k = e.which, pos, begin, end; //backspace, delete, and escape get special treatment if (k === 8 || k === 46 || (iPhone && k === 127)) { pos = input.caret(); begin = pos.begin; end = pos.end; if (end - begin === 0) { begin=k!==46?seekPrev(begin):(end=seekNext(begin-1)); end=k===46?seekNext(end):end; } clearBuffer(begin, end); shiftL(begin, end - 1); e.preventDefault(); } else if (k == 27) {//escape input.val(focusText); input.caret(0, checkVal()); e.preventDefault(); } } function keypressEvent(e) { var k = e.which, pos = input.caret(), p, c, next; if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {//Ignore return; } else if (k) { if (pos.end - pos.begin !== 0){ clearBuffer(pos.begin, pos.end); shiftL(pos.begin, pos.end-1); } p = seekNext(pos.begin - 1); if (p < len) { c = String.fromCharCode(k); if (tests[p].test(c)) { shiftR(p); buffer[p] = c; writeBuffer(); next = seekNext(p); if(android){ setTimeout($.proxy($.fn.caret,input,next),0); }else{ input.caret(next); } if (settings.completed && next >= len) { settings.completed.call(input); } } } e.preventDefault(); } } function clearBuffer(start, end) { var i; for (i = start; i < end && i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; } } } function writeBuffer() { input.val(buffer.join('')); } function checkVal(allow) { //try to place characters where they belong var test = input.val(), lastMatch = -1, i, c; for (i = 0, pos = 0; i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; while (pos++ < test.length) { c = test.charAt(pos - 1); if (tests[i].test(c)) { buffer[i] = c; lastMatch = i; break; } } if (pos > test.length) { break; } } else if (buffer[i] === test.charAt(pos) && i !== partialPosition) { pos++; lastMatch = i; } } if (allow) { writeBuffer(); } else if (lastMatch + 1 < partialPosition) { input.val(""); clearBuffer(0, len); } else { writeBuffer(); input.val(input.val().substring(0, lastMatch + 1)); } return (partialPosition ? i : firstNonMaskPos); } input.data($.mask.dataName,function(){ return $.map(buffer, function(c, i) { return tests[i]&&c!=settings.placeholder ? c : null; }).join(''); }); if (!input.attr("readonly")) input .one("unmask", function() { input .unbind(".mask") .removeData($.mask.dataName); }) .bind("focus.mask", function() { clearTimeout(caretTimeoutId); var pos, moveCaret; focusText = input.val(); pos = checkVal(); caretTimeoutId = setTimeout(function(){ writeBuffer(); if (pos == mask.length) { input.caret(0, pos); } else { input.caret(pos); } }, 10); }) .bind("blur.mask", function() { checkVal(); if (input.val() != focusText) input.change(); }) .bind("keydown.mask", keydownEvent) .bind("keypress.mask", keypressEvent) .bind(pasteEventName, function() { setTimeout(function() { var pos=checkVal(true); input.caret(pos); if (settings.completed && pos == input.val().length) settings.completed.call(input); }, 0); }); checkVal(); //Perform initial check for existing values }); } }); })(jQuery);
JavaScript
/* * jQuery UI 1.7.1 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI */ ;jQuery.ui || (function($) { var _remove = $.fn.remove, isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9); //Helper functions and ui object $.ui = { version: "1.7.1", // $.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); } } } }, contains: function(a, b) { return document.compareDocumentPosition ? a.compareDocumentPosition(b) & 16 : a !== b && a.contains(b); }, 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; }, 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); }, keyCode: { BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, 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 } }; // WAI-ARIA normalization if (isFF2) { var attr = $.attr, removeAttr = $.fn.removeAttr, ariaNS = "http://www.w3.org/2005/07/aaa", ariaState = /^aria-/, ariaRole = /^wairole:/; $.attr = function(elem, name, value) { var set = value !== undefined; return (name == 'role' ? (set ? attr.call(this, elem, name, "wairole:" + value) : (attr.apply(this, arguments) || "").replace(ariaRole, "")) : (ariaState.test(name) ? (set ? elem.setAttributeNS(ariaNS, name.replace(ariaState, "aaa:"), value) : attr.call(this, elem, name.replace(ariaState, "aaa:"))) : attr.apply(this, arguments))); }; $.fn.removeAttr = function(name) { return (ariaState.test(name) ? this.each(function() { this.removeAttributeNS(ariaNS, name.replace(ariaState, "")); }) : removeAttr.call(this, name)); }; } //jQuery plugins $.fn.extend({ remove: function() { // Safari has a native remove event which actually removes DOM elements, // so we have to use triggerHandler instead of trigger (#3037). $("*", this).add(this).each(function() { $(this).triggerHandler("remove"); }); return _remove.apply(this, arguments ); }, enableSelection: function() { return this .attr('unselectable', 'off') .css('MozUserSelect', '') .unbind('selectstart.ui'); }, disableSelection: function() { return this .attr('unselectable', 'on') .css('MozUserSelect', 'none') .bind('selectstart.ui', function() { return false; }); }, 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; } }); //Additional selectors $.extend($.expr[':'], { data: function(elem, i, match) { return !!$.data(elem, match[3]); }, focusable: function(element) { var nodeName = element.nodeName.toLowerCase(), tabIndex = $.attr(element, 'tabindex'); return (/input|select|textarea|button|object/.test(nodeName) ? !element.disabled : 'a' == nodeName || 'area' == nodeName ? element.href || !isNaN(tabIndex) : !isNaN(tabIndex)) // the element and all of its ancestors must be visible // the browser may report that the area is hidden && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length; }, tabbable: function(element) { var tabIndex = $.attr(element, 'tabindex'); return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable'); } }); // $.widget is a factory to create jQuery plugins // taking some boilerplate code out of the plugin code function getter(namespace, plugin, method, args) { function getMethods(type) { var methods = $[namespace][plugin][type] || []; return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods); } var methods = getMethods('getter'); if (args.length == 1 && typeof args[0] == 'string') { methods = methods.concat(getMethods('getterSetter')); } return ($.inArray(method, methods) != -1); } $.widget = function(name, prototype) { var namespace = name.split(".")[0]; name = name.split(".")[1]; // create plugin method $.fn[name] = function(options) { var isMethodCall = (typeof options == 'string'), args = Array.prototype.slice.call(arguments, 1); // prevent calls to internal methods if (isMethodCall && options.substring(0, 1) == '_') { return this; } // handle getter methods if (isMethodCall && getter(namespace, name, options, args)) { var instance = $.data(this[0], name); return (instance ? instance[options].apply(instance, args) : undefined); } // handle initialization and non-getter methods return this.each(function() { var instance = $.data(this, name); // constructor (!instance && !isMethodCall && $.data(this, name, new $[namespace][name](this, options))._init()); // method call (instance && isMethodCall && $.isFunction(instance[options]) && instance[options].apply(instance, args)); }); }; // create widget constructor $[namespace] = $[namespace] || {}; $[namespace][name] = function(element, options) { var self = this; this.namespace = namespace; this.widgetName = name; this.widgetEventPrefix = $[namespace][name].eventPrefix || name; this.widgetBaseClass = namespace + '-' + name; this.options = $.extend({}, $.widget.defaults, $[namespace][name].defaults, $.metadata && $.metadata.get(element)[name], options); this.element = $(element) .bind('setData.' + name, function(event, key, value) { if (event.target == element) { return self._setData(key, value); } }) .bind('getData.' + name, function(event, key) { if (event.target == element) { return self._getData(key); } }) .bind('remove', function() { return self.destroy(); }); }; // add widget prototype $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype); // TODO: merge getter and getterSetter properties from widget prototype // and plugin prototype $[namespace][name].getterSetter = 'option'; }; $.widget.prototype = { _init: function() {}, destroy: function() { this.element.removeData(this.widgetName) .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .removeAttr('aria-disabled'); }, option: function(key, value) { var options = key, self = this; if (typeof key == "string") { if (value === undefined) { return this._getData(key); } options = {}; options[key] = value; } $.each(options, function(key, value) { self._setData(key, value); }); }, _getData: function(key) { return this.options[key]; }, _setData: function(key, value) { this.options[key] = value; if (key == 'disabled') { this.element [value ? 'addClass' : 'removeClass']( this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .attr("aria-disabled", value); } }, enable: function() { this._setData('disabled', false); }, disable: function() { this._setData('disabled', true); }, _trigger: function(type, event, data) { var callback = this.options[type], eventName = (type == this.widgetEventPrefix ? type : this.widgetEventPrefix + type); event = $.Event(event); event.type = eventName; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if (event.originalEvent) { for (var i = $.event.props.length, prop; i;) { prop = $.event.props[--i]; event[prop] = event.originalEvent[prop]; } } this.element.trigger(event, data); return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false || event.isDefaultPrevented()); } }; $.widget.defaults = { disabled: false }; /** Mouse Interaction Plugin **/ $.ui.mouse = { _mouseInit: function() { var self = this; this.element .bind('mousedown.'+this.widgetName, function(event) { return self._mouseDown(event); }) .bind('click.'+this.widgetName, function(event) { if(self._preventClickEvent) { self._preventClickEvent = false; event.stopImmediatePropagation(); return false; } }); // Prevent text selection in IE if ($.browser.msie) { this._mouseUnselectable = this.element.attr('unselectable'); this.element.attr('unselectable', 'on'); } this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind('.'+this.widgetName); // Restore text selection in IE ($.browser.msie && this.element.attr('unselectable', this._mouseUnselectable)); }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart // TODO: figure out why we have to use originalEvent event.originalEvent = event.originalEvent || {}; if (event.originalEvent.mouseHandled) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var self = this, btnIsLeft = (event.which == 1), elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { self.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return self._mouseMove(event); }; this._mouseUpDelegate = function(event) { return self._mouseUp(event); }; $(document) .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); // preventDefault() is used to prevent the selection of text here - // however, in Safari, this causes select boxes not to be selectable // anymore, so this fix is needed ($.browser.safari || event.preventDefault()); event.originalEvent.mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.browser.msie && !event.button) { return this._mouseUp(event); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { $(document) .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; this._preventClickEvent = (event.target == this._mouseDownEvent.target); this._mouseStop(event); } return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(event) { return this.mouseDelayMet; }, // These are placeholder methods, to be overridden by extending plugin _mouseStart: function(event) {}, _mouseDrag: function(event) {}, _mouseStop: function(event) {}, _mouseCapture: function(event) { return true; } }; $.ui.mouse.defaults = { cancel: null, distance: 1, delay: 0 }; })(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.0 * Release: 2007-07-25 */ (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; } }; //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*/ input.focus(function(){ checkVal(); writeBuffer(); setCaretPosition(this,0); }); input.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 input.keydown(function(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.keypress(function(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; }); /*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); } }; }); }; })(jQuery);
JavaScript
/* * jQuery UI Accordion 1.7.1 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Accordion * * Depends: * ui.core.js */ (function($) { $.widget("ui.accordion", { _init: function() { var o = this.options, self = this; this.running = 0; // if the user set the alwaysOpen option on init // then we need to set the collapsible option // if they set both on init, collapsible will take priority if (o.collapsible == $.ui.accordion.defaults.collapsible && o.alwaysOpen != $.ui.accordion.defaults.alwaysOpen) { o.collapsible = !o.alwaysOpen; } if ( o.navigation ) { var current = this.element.find("a").filter(o.navigationFilter); if ( current.length ) { if ( current.filter(o.header).length ) { this.active = current; } else { this.active = current.parent().parent().prev(); current.addClass("ui-accordion-content-active"); } } } this.element.addClass("ui-accordion ui-widget ui-helper-reset"); // in lack of child-selectors in CSS we need to mark top-LIs in a UL-accordion for some IE-fix if (this.element[0].nodeName == "UL") { this.element.children("li").addClass("ui-accordion-li-fix"); } this.headers = this.element.find(o.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all") .bind("mouseenter.accordion", function(){ $(this).addClass('ui-state-hover'); }) .bind("mouseleave.accordion", function(){ $(this).removeClass('ui-state-hover'); }) .bind("focus.accordion", function(){ $(this).addClass('ui-state-focus'); }) .bind("blur.accordion", function(){ $(this).removeClass('ui-state-focus'); }); this.headers .next() .addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom"); this.active = this._findActive(this.active || o.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top"); this.active.next().addClass('ui-accordion-content-active'); //Append icon elements $("<span/>").addClass("ui-icon " + o.icons.header).prependTo(this.headers); this.active.find(".ui-icon").toggleClass(o.icons.header).toggleClass(o.icons.headerSelected); // IE7-/Win - Extra vertical space in lists fixed if ($.browser.msie) { this.element.find('a').css('zoom', '1'); } this.resize(); //ARIA this.element.attr('role','tablist'); this.headers .attr('role','tab') .bind('keydown', function(event) { return self._keydown(event); }) .next() .attr('role','tabpanel'); this.headers .not(this.active || "") .attr('aria-expanded','false') .attr("tabIndex", "-1") .next() .hide(); // make sure at least one header is in the tab order if (!this.active.length) { this.headers.eq(0).attr('tabIndex','0'); } else { this.active .attr('aria-expanded','true') .attr('tabIndex', '0'); } // only need links in taborder for Safari if (!$.browser.safari) this.headers.find('a').attr('tabIndex','-1'); if (o.event) { this.headers.bind((o.event) + ".accordion", function(event) { return self._clickHandler.call(self, event, this); }); } }, destroy: function() { var o = this.options; this.element .removeClass("ui-accordion ui-widget ui-helper-reset") .removeAttr("role") .unbind('.accordion') .removeData('accordion'); this.headers .unbind(".accordion") .removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top") .removeAttr("role").removeAttr("aria-expanded").removeAttr("tabindex"); this.headers.find("a").removeAttr("tabindex"); this.headers.children(".ui-icon").remove(); var contents = this.headers.next().css("display", "").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active"); if (o.autoHeight || o.fillHeight) { contents.css("height", ""); } }, _setData: function(key, value) { if(key == 'alwaysOpen') { key = 'collapsible'; value = !value; } $.widget.prototype._setData.apply(this, arguments); }, _keydown: function(event) { var o = this.options, keyCode = $.ui.keyCode; if (o.disabled || event.altKey || event.ctrlKey) return; var length = this.headers.length; var currentIndex = this.headers.index(event.target); var toFocus = false; switch(event.keyCode) { case keyCode.RIGHT: case keyCode.DOWN: toFocus = this.headers[(currentIndex + 1) % length]; break; case keyCode.LEFT: case keyCode.UP: toFocus = this.headers[(currentIndex - 1 + length) % length]; break; case keyCode.SPACE: case keyCode.ENTER: return this._clickHandler({ target: event.target }, event.target); } if (toFocus) { $(event.target).attr('tabIndex','-1'); $(toFocus).attr('tabIndex','0'); toFocus.focus(); return false; } return true; }, resize: function() { var o = this.options, maxHeight; if (o.fillSpace) { if($.browser.msie) { var defOverflow = this.element.parent().css('overflow'); this.element.parent().css('overflow', 'hidden'); } maxHeight = this.element.parent().height(); if($.browser.msie) { this.element.parent().css('overflow', defOverflow); } this.headers.each(function() { maxHeight -= $(this).outerHeight(); }); var maxPadding = 0; this.headers.next().each(function() { maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height()); }).height(Math.max(0, maxHeight - maxPadding)) .css('overflow', 'auto'); } else if ( o.autoHeight ) { maxHeight = 0; this.headers.next().each(function() { maxHeight = Math.max(maxHeight, $(this).outerHeight()); }).height(maxHeight); } }, activate: function(index) { // call clickHandler with custom event var active = this._findActive(index)[0]; this._clickHandler({ target: active }, active); }, _findActive: function(selector) { return selector ? typeof selector == "number" ? this.headers.filter(":eq(" + selector + ")") : this.headers.not(this.headers.not(selector)) : selector === false ? $([]) : this.headers.filter(":eq(0)"); }, _clickHandler: function(event, target) { var o = this.options; if (o.disabled) return false; // called only when using activate(false) to close all parts programmatically if (!event.target && o.collapsible) { this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all") .find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header); this.active.next().addClass('ui-accordion-content-active'); var toHide = this.active.next(), data = { options: o, newHeader: $([]), oldHeader: o.active, newContent: $([]), oldContent: toHide }, toShow = (this.active = $([])); this._toggle(toShow, toHide, data); return false; } // get the click target var clicked = $(event.currentTarget || target); var clickedIsActive = clicked[0] == this.active[0]; // if animations are still active, or the active header is the target, ignore click if (this.running || (!o.collapsible && clickedIsActive)) { return false; } // switch classes this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all") .find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header); this.active.next().addClass('ui-accordion-content-active'); if (!clickedIsActive) { clicked.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top") .find(".ui-icon").removeClass(o.icons.header).addClass(o.icons.headerSelected); clicked.next().addClass('ui-accordion-content-active'); } // find elements to show and hide var toShow = clicked.next(), toHide = this.active.next(), data = { options: o, newHeader: clickedIsActive && o.collapsible ? $([]) : clicked, oldHeader: this.active, newContent: clickedIsActive && o.collapsible ? $([]) : toShow.find('> *'), oldContent: toHide.find('> *') }, down = this.headers.index( this.active[0] ) > this.headers.index( clicked[0] ); this.active = clickedIsActive ? $([]) : clicked; this._toggle(toShow, toHide, data, clickedIsActive, down); return false; }, _toggle: function(toShow, toHide, data, clickedIsActive, down) { var o = this.options, self = this; this.toShow = toShow; this.toHide = toHide; this.data = data; var complete = function() { if(!self) return; return self._completed.apply(self, arguments); }; // trigger changestart event this._trigger("changestart", null, this.data); // count elements to animate this.running = toHide.size() === 0 ? toShow.size() : toHide.size(); if (o.animated) { var animOptions = {}; if ( o.collapsible && clickedIsActive ) { animOptions = { toShow: $([]), toHide: toHide, complete: complete, down: down, autoHeight: o.autoHeight || o.fillSpace }; } else { animOptions = { toShow: toShow, toHide: toHide, complete: complete, down: down, autoHeight: o.autoHeight || o.fillSpace }; } if (!o.proxied) { o.proxied = o.animated; } if (!o.proxiedDuration) { o.proxiedDuration = o.duration; } o.animated = $.isFunction(o.proxied) ? o.proxied(animOptions) : o.proxied; o.duration = $.isFunction(o.proxiedDuration) ? o.proxiedDuration(animOptions) : o.proxiedDuration; var animations = $.ui.accordion.animations, duration = o.duration, easing = o.animated; if (!animations[easing]) { animations[easing] = function(options) { this.slide(options, { easing: easing, duration: duration || 700 }); }; } animations[easing](animOptions); } else { if (o.collapsible && clickedIsActive) { toShow.toggle(); } else { toHide.hide(); toShow.show(); } complete(true); } toHide.prev().attr('aria-expanded','false').attr("tabIndex", "-1").blur(); toShow.prev().attr('aria-expanded','true').attr("tabIndex", "0").focus(); }, _completed: function(cancel) { var o = this.options; this.running = cancel ? 0 : --this.running; if (this.running) return; if (o.clearStyle) { this.toShow.add(this.toHide).css({ height: "", overflow: "" }); } this._trigger('change', null, this.data); } }); $.extend($.ui.accordion, { version: "1.7.1", defaults: { active: null, alwaysOpen: true, //deprecated, use collapsible animated: 'slide', autoHeight: true, clearStyle: false, collapsible: false, event: "click", fillSpace: false, header: "> li > :first-child,> :not(li):even", icons: { header: "ui-icon-triangle-1-e", headerSelected: "ui-icon-triangle-1-s" }, navigation: false, navigationFilter: function() { return this.href.toLowerCase() == location.href.toLowerCase(); } }, animations: { slide: function(options, additions) { options = $.extend({ easing: "swing", duration: 300 }, options, additions); if ( !options.toHide.size() ) { options.toShow.animate({height: "show"}, options); return; } if ( !options.toShow.size() ) { options.toHide.animate({height: "hide"}, options); return; } var overflow = options.toShow.css('overflow'), percentDone, showProps = {}, hideProps = {}, fxAttrs = [ "height", "paddingTop", "paddingBottom" ], originalWidth; // fix width before calculating height of hidden element var s = options.toShow; originalWidth = s[0].style.width; s.width( parseInt(s.parent().width(),10) - parseInt(s.css("paddingLeft"),10) - parseInt(s.css("paddingRight"),10) - (parseInt(s.css("borderLeftWidth"),10) || 0) - (parseInt(s.css("borderRightWidth"),10) || 0) ); $.each(fxAttrs, function(i, prop) { hideProps[prop] = 'hide'; var parts = ('' + $.css(options.toShow[0], prop)).match(/^([\d+-.]+)(.*)$/); showProps[prop] = { value: parts[1], unit: parts[2] || 'px' }; }); options.toShow.css({ height: 0, overflow: 'hidden' }).show(); options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate(hideProps,{ step: function(now, settings) { // only calculate the percent when animating height // IE gets very inconsistent results when animating elements // with small values, which is common for padding if (settings.prop == 'height') { percentDone = (settings.now - settings.start) / (settings.end - settings.start); } options.toShow[0].style[settings.prop] = (percentDone * showProps[settings.prop].value) + showProps[settings.prop].unit; }, duration: options.duration, easing: options.easing, complete: function() { if ( !options.autoHeight ) { options.toShow.css("height", ""); } options.toShow.css("width", originalWidth); options.toShow.css({overflow: overflow}); options.complete(); } }); }, bounceslide: function(options) { this.slide(options, { easing: options.down ? "easeOutBounce" : "swing", duration: options.down ? 1000 : 200 }); }, easeslide: function(options) { this.slide(options, { easing: "easeinout", duration: 700 }); } } }); })(jQuery);
JavaScript
/*! * MockJax - jQuery Plugin to Mock Ajax requests * * Version: 1.4.0 * Released: 2011-02-04 * Source: http://github.com/appendto/jquery-mockjax * Docs: http://enterprisejquery.com/2010/07/mock-your-ajax-requests-with-mockjax-for-rapid-development * Plugin: mockjax * Author: Jonathan Sharp (http://jdsharp.com) * License: MIT,GPL * * Copyright (c) 2010 appendTo LLC. * Dual licensed under the MIT or GPL licenses. * http://appendto.com/open-source-licenses */ (function($) { var _ajax = $.ajax, mockHandlers = []; function parseXML(xml) { if ( window['DOMParser'] == undefined && window.ActiveXObject ) { DOMParser = function() { }; DOMParser.prototype.parseFromString = function( xmlString ) { var doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML( xmlString ); return doc; }; } try { var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' ); if ( $.isXMLDoc( xmlDoc ) ) { var err = $('parsererror', xmlDoc); if ( err.length == 1 ) { throw('Error: ' + $(xmlDoc).text() ); } } else { throw('Unable to parse XML'); } } catch( e ) { var msg = ( e.name == undefined ? e : e.name + ': ' + e.message ); $(document).trigger('xmlParseError', [ msg ]); return undefined; } return xmlDoc; } $.extend({ ajax: function(origSettings) { var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings), mock = false; // Iterate over our mock handlers (in registration order) until we find // one that is willing to intercept the request $.each(mockHandlers, function(k, v) { if ( !mockHandlers[k] ) { return; } var m = null; // If the mock was registered with a function, let the function decide if we // want to mock this request if ( $.isFunction(mockHandlers[k]) ) { m = mockHandlers[k](s); } else { m = mockHandlers[k]; // Inspect the URL of the request and check if the mock handler's url // matches the url for this ajax request if ( $.isFunction(m.url.test) ) { // The user provided a regex for the url, test it if ( !m.url.test( s.url ) ) { m = null; } } else { // Look for a simple wildcard '*' or a direct URL match var star = m.url.indexOf('*'); if ( ( m.url != '*' && m.url != s.url && star == -1 ) || ( star > -1 && m.url.substr(0, star) != s.url.substr(0, star) ) ) { // The url we tested did not match the wildcard * m = null; } } if ( m ) { // Inspect the data submitted in the request (either POST body or GET query string) if ( m.data && s.data ) { var identical = false; // Deep inspect the identity of the objects (function ident(mock, live) { // Test for situations where the data is a querystring (not an object) if (typeof live === 'string') { // Querystring may be a regex identical = $.isFunction( mock.test ) ? mock.test(live) : mock == live; return identical; } $.each(mock, function(k, v) { if ( live[k] === undefined ) { identical = false; return false; } else { identical = true; if ( typeof live[k] == 'object' ) { return ident(mock[k], live[k]); } else { if ( $.isFunction( mock[k].test ) ) { identical = mock[k].test(live[k]); } else { identical = ( mock[k] == live[k] ); } return identical; } } }); })(m.data, s.data); // They're not identical, do not mock this request if ( identical == false ) { m = null; } } // Inspect the request type if ( m && m.type && m.type != s.type ) { // The request type doesn't match (GET vs. POST) m = null; } } } if ( m ) { mock = true; // Handle console logging var c = $.extend({}, $.mockjaxSettings, m); if ( c.log && $.isFunction(c.log) ) { c.log('MOCK ' + s.type.toUpperCase() + ': ' + s.url, $.extend({}, s)); } var jsre = /=\?(&|$)/, jsc = (new Date()).getTime(); // Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here // because there isn't an easy hook for the cross domain script tag of jsonp if ( s.dataType === "jsonp" ) { if ( s.type.toUpperCase() === "GET" ) { if ( !jsre.test( s.url ) ) { s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; } } else if ( !s.data || !jsre.test(s.data) ) { s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; } s.dataType = "json"; } // Build temporary JSONP function if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { jsonp = s.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if ( s.data ) { s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); } s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading window[ jsonp ] = window[ jsonp ] || function( tmp ) { data = tmp; success(); complete(); // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch(e) {} if ( head ) { head.removeChild( script ); } }; } var rurl = /^(\w+:)?\/\/([^\/?#]+)/, parts = rurl.exec( s.url ), remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host); // Test if we are going to create a script tag (if so, intercept & mock) if ( s.dataType === "script" && s.type.toUpperCase() === "GET" && remote ) { // Synthesize the mock request for adding a script tag var callbackContext = origSettings && origSettings.context || s; function success() { // If a local callback was specified, fire it and pass it the data if ( s.success ) { s.success.call( callbackContext, ( m.response ? m.response.toString() : m.responseText || ''), status, {} ); } // Fire the global callback if ( s.global ) { trigger( "ajaxSuccess", [{}, s] ); } } function complete() { // Process result if ( s.complete ) { s.complete.call( callbackContext, {} , status ); } // The request was completed if ( s.global ) { trigger( "ajaxComplete", [{}, s] ); } // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } } function trigger(type, args) { (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args); } if ( m.response && $.isFunction(m.response) ) { m.response(origSettings); } else { $.globalEval(m.responseText); } success(); complete(); return false; } mock = _ajax.call($, $.extend(true, {}, origSettings, { // Mock the XHR object xhr: function() { // Extend with our default mockjax settings m = $.extend({}, $.mockjaxSettings, m); if ( m.contentType ) { m.headers['content-type'] = m.contentType; } // Return our mock xhr object return { status: m.status, readyState: 1, open: function() { }, send: function() { // This is a substitute for < 1.4 which lacks $.proxy var process = (function(that) { return function() { return (function() { // The request has returned this.status = m.status; this.readyState = 4; // We have an executable function, call it to give // the mock handler a chance to update it's data if ( $.isFunction(m.response) ) { m.response(origSettings); } // Copy over our mock to our xhr object before passing control back to // jQuery's onreadystatechange callback if ( s.dataType == 'json' && ( typeof m.responseText == 'object' ) ) { this.responseText = JSON.stringify(m.responseText); } else if ( s.dataType == 'xml' ) { if ( typeof m.responseXML == 'string' ) { this.responseXML = parseXML(m.responseXML); } else { this.responseXML = m.responseXML; } } else { this.responseText = m.responseText; } // jQuery < 1.4 doesn't have onreadystate change for xhr if ( $.isFunction(this.onreadystatechange) ) { this.onreadystatechange( m.isTimeout ? 'timeout' : undefined ); } }).apply(that); }; })(this); if ( m.proxy ) { // We're proxying this request and loading in an external file instead _ajax({ global: false, url: m.proxy, type: m.proxyType, data: m.data, dataType: s.dataType, complete: function(xhr, txt) { m.responseXML = xhr.responseXML; m.responseText = xhr.responseText; this.responseTimer = setTimeout(process, m.responseTime || 0); } }); } else { // type == 'POST' || 'GET' || 'DELETE' if ( s.async === false ) { // TODO: Blocking delay process(); } else { this.responseTimer = setTimeout(process, m.responseTime || 50); } } }, abort: function() { clearTimeout(this.responseTimer); }, setRequestHeader: function() { }, getResponseHeader: function(header) { // 'Last-modified', 'Etag', 'content-type' are all checked by jQuery if ( m.headers && m.headers[header] ) { // Return arbitrary headers return m.headers[header]; } else if ( header.toLowerCase() == 'last-modified' ) { return m.lastModified || (new Date()).toString(); } else if ( header.toLowerCase() == 'etag' ) { return m.etag || ''; } else if ( header.toLowerCase() == 'content-type' ) { return m.contentType || 'text/plain'; } }, getAllResponseHeaders: function() { var headers = ''; $.each(m.headers, function(k, v) { headers += k + ': ' + v + "\n"; }); return headers; } }; } })); return false; } }); // We don't have a mock request, trigger a normal request if ( !mock ) { return _ajax.apply($, arguments); } else { return mock; } } }); $.mockjaxSettings = { //url: null, //type: 'GET', log: function(msg) { window['console'] && window.console.log && window.console.log(msg); }, status: 200, responseTime: 500, isTimeout: false, contentType: 'text/plain', response: '', responseText: '', responseXML: '', proxy: '', proxyType: 'GET', lastModified: null, etag: '', headers: { etag: 'IJF@H#@923uf8023hFO@I#H#', 'content-type' : 'text/plain' } }; $.mockjax = function(settings) { var i = mockHandlers.length; mockHandlers[i] = settings; return i; }; $.mockjaxClear = function(i) { if ( arguments.length == 1 ) { mockHandlers[i] = null; } else { mockHandlers = []; } }; })(jQuery);
JavaScript
/*! * jQuery Form Plugin * version: 3.20 (20-NOV-2012) * @requires jQuery v1.5 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Project repository: https://github.com/malsup/form * Dual licensed under the MIT and GPL licenses: * http://malsup.github.com/mit-license.txt * http://malsup.github.com/gpl-license-v2.txt */ /*global ActiveXObject alert */ ;(function($) { "use strict"; /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are mutually exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').on('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); You can also use ajaxForm with delegation (requires jQuery v1.7+), so the form does not have to exist when you invoke ajaxForm: $('#myForm').ajaxForm({ delegation: true, target: '#output' }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * Feature detection */ var feature = {}; feature.fileapi = $("<input type='file'/>").get(0).files !== undefined; feature.formdata = window.FormData !== undefined; /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { /*jshint scripturl:true */ // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } var method, action, url, $form = this; if (typeof options == 'function') { options = { success: options }; } method = this.attr('method'); action = this.attr('action'); url = (typeof action === 'string') ? $.trim(action) : ''; url = url || window.location.href || ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: method || 'GET', iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var traditional = options.traditional; if ( traditional === undefined ) { traditional = $.ajaxSettings.traditional; } var elements = []; var qx, a = this.formToArray(options.semantic, elements); if (options.data) { options.extraData = options.data; qx = $.param(options.data, traditional); } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a, traditional); if (qx) { q = ( q ? (q + '&' + qx) : qx ); } if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(options.includeHidden); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || this ; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; // are there files to upload? // [value] (issue #113), also see comment: // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219 var fileInputs = $('input[type=file]:enabled[value!=""]', this); var hasFileInputs = fileInputs.length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); var fileAPI = feature.fileapi && feature.formdata; log("fileAPI :" + fileAPI); var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; var jqxhr; // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (options.iframe || shouldUseFrame)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, function() { jqxhr = fileUploadIframe(a); }); } else { jqxhr = fileUploadIframe(a); } } else if ((hasFileInputs || multipart) && fileAPI) { jqxhr = fileUploadXhr(a); } else { jqxhr = $.ajax(options); } $form.removeData('jqxhr').data('jqxhr', jqxhr); // clear element array for (var k=0; k < elements.length; k++) elements[k] = null; // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // utility fn for deep serialization function deepSerialize(extraData){ var serialized = $.param(extraData).split('&'); var len = serialized.length; var result = {}; var i, part; for (i=0; i < len; i++) { part = serialized[i].split('='); result[decodeURIComponent(part[0])] = decodeURIComponent(part[1]); } return result; } // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) function fileUploadXhr(a) { var formdata = new FormData(); for (var i=0; i < a.length; i++) { formdata.append(a[i].name, a[i].value); } if (options.extraData) { var serializedData = deepSerialize(options.extraData); for (var p in serializedData) if (serializedData.hasOwnProperty(p)) formdata.append(p, serializedData[p]); } options.data = null; var s = $.extend(true, {}, $.ajaxSettings, options, { contentType: false, processData: false, cache: false, type: method || 'POST' }); if (options.uploadProgress) { // workaround because jqXHR does not expose upload property s.xhr = function() { var xhr = jQuery.ajaxSettings.xhr(); if (xhr.upload) { xhr.upload.onprogress = function(event) { var percent = 0; var position = event.loaded || event.position; /*event.position is deprecated*/ var total = event.total; if (event.lengthComputable) { percent = Math.ceil(position / total * 100); } options.uploadProgress(event, position, total, percent); }; } return xhr; }; } s.data = null; var beforeSend = s.beforeSend; s.beforeSend = function(xhr, o) { o.data = formdata; if(beforeSend) beforeSend.call(this, xhr, o); }; return $.ajax(s); } // private function for handling file uploads (hat tip to YAHOO!) function fileUploadIframe(a) { var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; var useProp = !!$.fn.prop; var deferred = $.Deferred(); if ($('[name=submit],[id=submit]', form).length) { // if there is an input with a name or id of 'submit' then we won't be // able to invoke the submit fn on the form (at least not x-browser) alert('Error: Form elements must not have name or id of "submit".'); deferred.reject(); return deferred; } if (a) { // ensure that every serialized input is still enabled for (i=0; i < elements.length; i++) { el = $(elements[i]); if ( useProp ) el.prop('disabled', false); else el.removeAttr('disabled'); } } s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; id = 'jqFormIO' + (new Date().getTime()); if (s.iframeTarget) { $io = $(s.iframeTarget); n = $io.attr('name'); if (!n) $io.attr('name', id); else id = n; } else { $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />'); $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); } io = $io[0]; xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; // #214 if (io.contentWindow.document.execCommand) { try { // #214 io.contentWindow.document.execCommand('Stop'); } catch(ignore) {} } $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; if (s.error) s.error.call(s.context, xhr, e, status); if (g) $.event.trigger("ajaxError", [xhr, s, e]); if (s.complete) s.complete.call(s.context, xhr, e); } }; g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && 0 === $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } deferred.reject(); return deferred; } if (xhr.aborted) { deferred.reject(); return deferred; } // add submitting element to data if we know it sub = form.clk; if (sub) { n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } var CLIENT_TIMEOUT_ABORT = 1; var SERVER_ABORT = 2; function getDoc(frame) { var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document; return doc; } // Rails CSRF hack (thanks to Yvan Barthelemy) var csrf_token = $('meta[name=csrf-token]').attr('content'); var csrf_param = $('meta[name=csrf-param]').attr('content'); if (csrf_param && csrf_token) { s.extraData = s.extraData || {}; s.extraData[csrf_param] = csrf_token; } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (!method) { form.setAttribute('method', 'POST'); } if (a != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride && (!method || /post/i.test(method))) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout); } // look for server aborts function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state && state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); if (timeoutHandle) clearTimeout(timeoutHandle); timeoutHandle = undefined; } } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { if (s.extraData.hasOwnProperty(n)) { // if using the $.param format that allows for multiple values with the same name if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) { extraInputs.push( $('<input type="hidden" name="'+s.extraData[n].name+'">').attr('value',s.extraData[n].value) .appendTo(form)[0]); } else { extraInputs.push( $('<input type="hidden" name="'+n+'">').attr('value',s.extraData[n]) .appendTo(form)[0]); } } } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); if (io.attachEvent) io.attachEvent('onload', cb); else io.addEventListener('load', cb, false); } setTimeout(checkState,15); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } try { doc = getDoc(io); } catch(ex) { log('cannot access response document: ', ex); e = SERVER_ABORT; } if (e === CLIENT_TIMEOUT_ABORT && xhr) { xhr.abort('timeout'); deferred.reject(xhr, 'timeout'); return; } else if (e == SERVER_ABORT && xhr) { xhr.abort('server abort'); deferred.reject(xhr, 'error', 'server abort'); return; } if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } if (io.detachEvent) io.detachEvent('onload', cb); else io.removeEventListener('load', cb, false); var status = 'success', errMsg; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); var docRoot = doc.body ? doc.body : doc.documentElement; xhr.responseText = docRoot ? docRoot.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; // support for XHR 'status' & 'statusText' emulation : if (docRoot) { xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status; xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText; } var dt = (s.dataType || '').toLowerCase(); var scr = /(json|script|text)/.test(dt); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; // support for XHR 'status' & 'statusText' emulation : xhr.status = Number( ta.getAttribute('status') ) || xhr.status; xhr.statusText = ta.getAttribute('statusText') || xhr.statusText; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; } else if (b) { xhr.responseText = b.textContent ? b.textContent : b.innerText; } } } else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) { xhr.responseXML = toXml(xhr.responseText); } try { data = httpData(xhr, dt, s); } catch (e) { status = 'parsererror'; xhr.error = errMsg = (e || status); } } catch (e) { log('error caught: ',e); status = 'error'; xhr.error = errMsg = (e || status); } if (xhr.aborted) { log('upload aborted'); status = null; } if (xhr.status) { // we've set xhr.status status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (status === 'success') { if (s.success) s.success.call(s.context, data, 'success', xhr); deferred.resolve(xhr.responseText, 'success', xhr); if (g) $.event.trigger("ajaxSuccess", [xhr, s]); } else if (status) { if (errMsg === undefined) errMsg = xhr.statusText; if (s.error) s.error.call(s.context, xhr, status, errMsg); deferred.reject(xhr, 'error', errMsg); if (g) $.event.trigger("ajaxError", [xhr, s, errMsg]); } if (g) $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } if (s.complete) s.complete.call(s.context, xhr, status); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { if (!s.iframeTarget) $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { /*jslint evil:true */ return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { if ($.error) $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; return deferred; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { options = options || {}; options.delegation = options.delegation && $.isFunction($.fn.on); // in jQuery 1.3+ we can fix mistakes with the ready state if (!options.delegation && this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } if ( options.delegation ) { $(document) .off('submit.form-plugin', this.selector, doAjaxSubmit) .off('click.form-plugin', this.selector, captureSubmittingElement) .on('submit.form-plugin', this.selector, options, doAjaxSubmit) .on('click.form-plugin', this.selector, options, captureSubmittingElement); return this; } return this.ajaxFormUnbind() .bind('submit.form-plugin', options, doAjaxSubmit) .bind('click.form-plugin', options, captureSubmittingElement); }; // private event handlers function doAjaxSubmit(e) { /*jshint validthis:true */ var options = e.data; if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } } function captureSubmittingElement(e) { /*jshint validthis:true */ var target = e.target; var $el = $(target); if (!($el.is("[type=submit],[type=image]"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest('[type=submit]'); if (t.length === 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX !== undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); } // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic, elements) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) { a.push({name: n, value: $(el).val(), type: el.type }); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { if (elements) elements.push(el); for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (feature.fileapi && el.type == 'file' && !el.disabled) { if (elements) elements.push(el); var files = el.files; if (files.length) { for (j=0; j < files.length; j++) { a.push({name: n, value: files[j], type: el.type}); } } else { // #180 a.push({ name: n, value: '', type: el.type }); } } else if (v !== null && typeof v != 'undefined') { if (elements) elements.push(el); a.push({name: n, value: v, type: el.type, required: el.required}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $('input[type=text]').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $('input[type=checkbox]').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $('input[type=radio]').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } if (v.constructor == Array) $.merge(val, v); else val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function(includeHidden) { return this.each(function() { $('input,select,textarea', this).clearFields(includeHidden); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function(includeHidden) { var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (re.test(t) || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } else if (includeHidden) { // includeHidden can be the value true, or it can be a selector string // indicating a special test; for example: // $('#myForm').clearForm('.special:hidden') // the above would clean hidden inputs that have the class of 'special' if ( (includeHidden === true && /hidden/.test(t)) || (typeof includeHidden == 'string' && $(this).is(includeHidden)) ) this.value = ''; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // expose debug var $.fn.ajaxSubmit.debug = false; // helper fn for console logging function log() { if (!$.fn.ajaxSubmit.debug) return; var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } } })(jQuery);
JavaScript
/*!jQuery Knob*/ /** * Downward compatible, touchable dial * * Version: 1.2.0 (15/07/2012) * Requires: jQuery v1.7+ * * Copyright (c) 2012 Anthony Terrien * Under MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Thanks to vor, eskimoblood, spiffistan, FabrizioC */ (function($) { /** * Kontrol library */ "use strict"; /** * Definition of globals and core */ var k = {}, // kontrol max = Math.max, min = Math.min; k.c = {}; k.c.d = $(document); k.c.t = function (e) { return e.originalEvent.touches.length - 1; }; /** * Kontrol Object * * Definition of an abstract UI control * * Each concrete component must call this one. * <code> * k.o.call(this); * </code> */ k.o = function () { var s = this; this.o = null; // array of options this.$ = null; // jQuery wrapped element this.i = null; // mixed HTMLInputElement or array of HTMLInputElement this.g = null; // deprecated 2D graphics context for 'pre-rendering' this.v = null; // value ; mixed array or integer this.cv = null; // change value ; not commited value this.x = 0; // canvas x position this.y = 0; // canvas y position this.w = 0; // canvas width this.h = 0; // canvas height this.$c = null; // jQuery canvas element this.c = null; // rendered canvas context this.t = 0; // touches index this.isInit = false; this.fgColor = null; // main color this.pColor = null; // previous color this.dH = null; // draw hook this.cH = null; // change hook this.eH = null; // cancel hook this.rH = null; // release hook this.scale = 1; // scale factor this.relative = false; this.relativeWidth = false; this.relativeHeight = false; this.$div = null; // component div this.run = function () { var cf = function (e, conf) { var k; for (k in conf) { s.o[k] = conf[k]; } s.init(); s._configure() ._draw(); }; if(this.$.data('kontroled')) return; this.$.data('kontroled', true); this.extend(); this.o = $.extend( { // Config min : this.$.data('min') || 0, max : this.$.data('max') || 100, stopper : true, readOnly : this.$.data('readonly'), // UI cursor : (this.$.data('cursor') === true && 30) || this.$.data('cursor') || 0, thickness : this.$.data('thickness') || 0.35, lineCap : this.$.data('linecap') || 'butt', width : this.$.data('width') || 200, height : this.$.data('height') || 200, displayInput : this.$.data('displayinput') == null || this.$.data('displayinput'), displayPrevious : this.$.data('displayprevious'), fgColor : this.$.data('fgcolor') || '#87CEEB', inputColor: this.$.data('inputcolor') || this.$.data('fgcolor') || '#87CEEB', font: this.$.data('font') || 'Arial', fontWeight: this.$.data('font-weight') || 'bold', inline : false, step : this.$.data('step') || 1, // Hooks draw : null, // function () {} change : null, // function (value) {} cancel : null, // function () {} release : null, // function (value) {} error : null // function () {} }, this.o ); // routing value if(this.$.is('fieldset')) { // fieldset = array of integer this.v = {}; this.i = this.$.find('input') this.i.each(function(k) { var $this = $(this); s.i[k] = $this; s.v[k] = $this.val(); $this.bind( 'change' , function () { var val = {}; val[k] = $this.val(); s.val(val); } ); }); this.$.find('legend').remove(); } else { // input = integer this.i = this.$; this.v = this.$.val(); (this.v == '') && (this.v = this.o.min); this.$.bind( 'change' , function () { s.val(s._validate(s.$.val())); } ); } (!this.o.displayInput) && this.$.hide(); // adds needed DOM elements (canvas, div) this.$c = $(document.createElement('canvas')); if (typeof G_vmlCanvasManager !== 'undefined') { G_vmlCanvasManager.initElement(this.$c[0]); } this.c = this.$c[0].getContext ? this.$c[0].getContext('2d') : null; if (!this.c) { this.o.error && this.o.error(); return; } // hdpi support this.scale = (window.devicePixelRatio || 1) / ( this.c.webkitBackingStorePixelRatio || this.c.mozBackingStorePixelRatio || this.c.msBackingStorePixelRatio || this.c.oBackingStorePixelRatio || this.c.backingStorePixelRatio || 1 ); // detects relative width / height this.relativeWidth = ((this.o.width % 1 !== 0) && this.o.width.indexOf('%')); this.relativeHeight = ((this.o.height % 1 !== 0) && this.o.height.indexOf('%')); this.relative = (this.relativeWidth || this.relativeHeight); // wraps all elements in a div this.$div = $('<div style="' + (this.o.inline ? 'display:inline;' : '') + '"></div>'); this.$.wrap(this.$div).before(this.$c); this.$div = this.$.parent(); // computes size and carves the component this._carve(); // prepares props for transaction if (this.v instanceof Object) { this.cv = {}; this.copy(this.v, this.cv); } else { this.cv = this.v; } // binds configure event this.$ .bind("configure", cf) .parent() .bind("configure", cf); // finalize init this._listen() ._configure() ._xy() .init(); this.isInit = true; // the most important ! this._draw(); return this; }; this._carve = function() { if(this.relative) { var w = this.relativeWidth ? this.$div.parent().width() * parseInt(this.o.width) / 100 : this.$div.parent().width(), h = this.relativeHeight ? this.$div.parent().height() * parseInt(this.o.height) / 100 : this.$div.parent().height(); // apply relative this.w = this.h = Math.min(w, h); } else { this.w = this.o.width; this.h = this.o.height; } // finalize div this.$div.css({ 'width': this.w + 'px', 'height': this.h + 'px' }); // finalize canvas with computed width this.$c.attr({ width: this.w, height: this.h }); // scaling if (this.scale !== 1) { this.$c[0].width = this.$c[0].width * this.scale; this.$c[0].height = this.$c[0].height * this.scale; this.$c.width(this.w); this.$c.height(this.h); } return this; } this._draw = function () { // canvas pre-rendering var d = true; s.g = s.c; s.clear(); s.dH && (d = s.dH()); (d !== false) && s.draw(); }; this._touch = function (e) { var touchMove = function (e) { var v = s.xy2val( e.originalEvent.touches[s.t].pageX, e.originalEvent.touches[s.t].pageY ); if (v == s.cv) return; if ( s.cH && (s.cH(v) === false) ) return; s.change(s._validate(v)); s._draw(); }; // get touches index this.t = k.c.t(e); // First touch touchMove(e); // Touch events listeners k.c.d .bind("touchmove.k", touchMove) .bind( "touchend.k" , function () { k.c.d.unbind('touchmove.k touchend.k'); if ( s.rH && (s.rH(s.cv) === false) ) return; s.val(s.cv); } ); return this; }; this._mouse = function (e) { var mouseMove = function (e) { var v = s.xy2val(e.pageX, e.pageY); if (v == s.cv) return; if ( s.cH && (s.cH(v) === false) ) return; s.change(s._validate(v)); s._draw(); }; // First click mouseMove(e); // Mouse events listeners k.c.d .bind("mousemove.k", mouseMove) .bind( // Escape key cancel current change "keyup.k" , function (e) { if (e.keyCode === 27) { k.c.d.unbind("mouseup.k mousemove.k keyup.k"); if ( s.eH && (s.eH() === false) ) return; s.cancel(); } } ) .bind( "mouseup.k" , function (e) { k.c.d.unbind('mousemove.k mouseup.k keyup.k'); if ( s.rH && (s.rH(s.cv) === false) ) return; s.val(s.cv); } ); return this; }; this._xy = function () { var o = this.$c.offset(); this.x = o.left; this.y = o.top; return this; }; this._listen = function () { if (!this.o.readOnly) { this.$c .bind( "mousedown" , function (e) { e.preventDefault(); s._xy()._mouse(e); } ) .bind( "touchstart" , function (e) { e.preventDefault(); s._xy()._touch(e); } ); if(this.relative) { $(window).resize(function() { s._carve() .init(); s._draw(); }); } this.listen(); } else { this.$.attr('readonly', 'readonly'); } return this; }; this._configure = function () { // Hooks if (this.o.draw) this.dH = this.o.draw; if (this.o.change) this.cH = this.o.change; if (this.o.cancel) this.eH = this.o.cancel; if (this.o.release) this.rH = this.o.release; if (this.o.displayPrevious) { this.pColor = this.h2rgba(this.o.fgColor, "0.4"); this.fgColor = this.h2rgba(this.o.fgColor, "0.6"); } else { this.fgColor = this.o.fgColor; } return this; }; this._clear = function () { this.$c[0].width = this.$c[0].width; }; this._validate = function(v) { return (~~ (((v < 0) ? -0.5 : 0.5) + (v/this.o.step))) * this.o.step; }; // Abstract methods this.listen = function () {}; // on start, one time this.extend = function () {}; // each time configure triggered this.init = function () {}; // each time configure triggered this.change = function (v) {}; // on change this.val = function (v) {}; // on release this.xy2val = function (x, y) {}; // this.draw = function () {}; // on change / on release this.clear = function () { this._clear(); }; // Utils this.h2rgba = function (h, a) { var rgb; h = h.substring(1,7) rgb = [parseInt(h.substring(0,2),16) ,parseInt(h.substring(2,4),16) ,parseInt(h.substring(4,6),16)]; return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + a + ")"; }; this.copy = function (f, t) { for (var i in f) { t[i] = f[i]; } }; }; /** * k.Dial */ k.Dial = function () { k.o.call(this); this.startAngle = null; this.xy = null; this.radius = null; this.lineWidth = null; this.cursorExt = null; this.w2 = null; this.PI2 = 2*Math.PI; this.extend = function () { this.o = $.extend( { bgColor : this.$.data('bgcolor') || '#EEEEEE', angleOffset : this.$.data('angleoffset') || 0, angleArc : this.$.data('anglearc') || 360, inline : true }, this.o ); }; this.val = function (v) { if (null != v) { this.cv = this.o.stopper ? max(min(v, this.o.max), this.o.min) : v; this.v = this.cv; this.$.val(this.v); this._draw(); } else { return this.v; } }; this.xy2val = function (x, y) { var a, ret; a = Math.atan2( x - (this.x + this.w2) , - (y - this.y - this.w2) ) - this.angleOffset; if(this.angleArc != this.PI2 && (a < 0) && (a > -0.5)) { // if isset angleArc option, set to min if .5 under min a = 0; } else if (a < 0) { a += this.PI2; } ret = ~~ (0.5 + (a * (this.o.max - this.o.min) / this.angleArc)) + this.o.min; this.o.stopper && (ret = max(min(ret, this.o.max), this.o.min)); return ret; }; this.listen = function () { // bind MouseWheel var s = this, mw = function (e) { e.preventDefault(); var ori = e.originalEvent ,deltaX = ori.detail || ori.wheelDeltaX ,deltaY = ori.detail || ori.wheelDeltaY ,v = parseInt(s.$.val()) + (deltaX>0 || deltaY>0 ? s.o.step : deltaX<0 || deltaY<0 ? -s.o.step : 0); if ( s.cH && (s.cH(v) === false) ) return; s.val(v); } , kval, to, m = 1, kv = {37:-s.o.step, 38:s.o.step, 39:s.o.step, 40:-s.o.step}; this.$ .bind( "keydown" ,function (e) { var kc = e.keyCode; // numpad support if(kc >= 96 && kc <= 105) { kc = e.keyCode = kc - 48; } kval = parseInt(String.fromCharCode(kc)); if (isNaN(kval)) { (kc !== 13) // enter && (kc !== 8) // bs && (kc !== 9) // tab && (kc !== 189) // - && e.preventDefault(); // arrows if ($.inArray(kc,[37,38,39,40]) > -1) { e.preventDefault(); var v = parseInt(s.$.val()) + kv[kc] * m; s.o.stopper && (v = max(min(v, s.o.max), s.o.min)); s.change(v); s._draw(); // long time keydown speed-up to = window.setTimeout( function () { m*=2; } ,30 ); } } } ) .bind( "keyup" ,function (e) { if (isNaN(kval)) { if (to) { window.clearTimeout(to); to = null; m = 1; s.val(s.$.val()); } } else { // kval postcond (s.$.val() > s.o.max && s.$.val(s.o.max)) || (s.$.val() < s.o.min && s.$.val(s.o.min)); } } ); this.$c.bind("mousewheel DOMMouseScroll", mw); this.$.bind("mousewheel DOMMouseScroll", mw) }; this.init = function () { if ( this.v < this.o.min || this.v > this.o.max ) this.v = this.o.min; this.$.val(this.v); this.w2 = this.w / 2; this.cursorExt = this.o.cursor / 100; this.xy = this.w2 * this.scale; this.lineWidth = this.xy * this.o.thickness; this.lineCap = this.o.lineCap; this.radius = this.xy - this.lineWidth / 2; this.o.angleOffset && (this.o.angleOffset = isNaN(this.o.angleOffset) ? 0 : this.o.angleOffset); this.o.angleArc && (this.o.angleArc = isNaN(this.o.angleArc) ? this.PI2 : this.o.angleArc); // deg to rad this.angleOffset = this.o.angleOffset * Math.PI / 180; this.angleArc = this.o.angleArc * Math.PI / 180; // compute start and end angles this.startAngle = 1.5 * Math.PI + this.angleOffset; this.endAngle = 1.5 * Math.PI + this.angleOffset + this.angleArc; var s = max( String(Math.abs(this.o.max)).length , String(Math.abs(this.o.min)).length , 2 ) + 2; this.o.displayInput && this.i.css({ 'width' : ((this.w / 2 + 4) >> 0) + 'px' ,'height' : ((this.w / 3) >> 0) + 'px' ,'position' : 'absolute' ,'vertical-align' : 'middle' ,'margin-top' : ((this.w / 3) >> 0) + 'px' ,'margin-left' : '-' + ((this.w * 3 / 4 + 2) >> 0) + 'px' ,'border' : 0 ,'background' : 'none' ,'font' : this.o.fontWeight + ' ' + ((this.w / s) >> 0) + 'px ' + this.o.font ,'text-align' : 'center' ,'color' : this.o.inputColor || this.o.fgColor ,'padding' : '0px' ,'-webkit-appearance': 'none' }) || this.i.css({ 'width' : '0px' ,'visibility' : 'hidden' }); }; this.change = function (v) { this.cv = v; this.$.val(v); }; this.angle = function (v) { return (v - this.o.min) * this.angleArc / (this.o.max - this.o.min); }; this.draw = function () { var c = this.g, // context a = this.angle(this.cv) // Angle , sat = this.startAngle // Start angle , eat = sat + a // End angle , sa, ea // Previous angles , r = 1; c.lineWidth = this.lineWidth; c.lineCap = this.lineCap; this.o.cursor && (sat = eat - this.cursorExt) && (eat = eat + this.cursorExt); c.beginPath(); c.strokeStyle = this.o.bgColor; c.arc(this.xy, this.xy, this.radius, this.endAngle, this.startAngle, true); c.stroke(); if (this.o.displayPrevious) { ea = this.startAngle + this.angle(this.v); sa = this.startAngle; this.o.cursor && (sa = ea - this.cursorExt) && (ea = ea + this.cursorExt); c.beginPath(); c.strokeStyle = this.pColor; c.arc(this.xy, this.xy, this.radius, sa, ea, false); c.stroke(); r = (this.cv == this.v); } c.beginPath(); c.strokeStyle = r ? this.o.fgColor : this.fgColor ; c.arc(this.xy, this.xy, this.radius, sat, eat, false); c.stroke(); }; this.cancel = function () { this.val(this.v); }; }; $.fn.dial = $.fn.knob = function (o) { return this.each( function () { var d = new k.Dial(); d.o = o; d.$ = $(this); d.run(); } ).parent(); }; })(jQuery);
JavaScript
/*! Copyright (c) 2011 Piotr Rochala (http://rocha.la) * 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.2 * */ (function($) { jQuery.fn.extend({ slimScroll: function(options) { var defaults = { // width in pixels of the visible scroll area width : 'auto', // height in pixels of the visible scroll area height : '250px', // width in pixels of the scrollbar and rail size : '7px', // scrollbar color, accepts any hex/color value color: '#000', // scrollbar position - left/right position : 'right', // distance in pixels between the side edge and the scrollbar distance : '1px', // default scroll position on load - top / bottom / $('selector') start : 'top', // sets scrollbar opacity opacity : .4, // enables always-on mode for the scrollbar alwaysVisible : false, // check if we should hide the scrollbar when user is hovering over disableFadeOut : false, // sets visibility of the rail railVisible : false, // sets rail color railColor : '#333', // sets rail opacity railOpacity : .2, // whether we should use jQuery UI Draggable to enable bar dragging railDraggable : true, // defautlt CSS class of the slimscroll rail railClass : 'slimScrollRail', // defautlt CSS class of the slimscroll bar barClass : 'slimScrollBar', // defautlt CSS class of the slimscroll wrapper wrapperClass : 'slimScrollDiv', // check if mousewheel should scroll the window if we reach top/bottom allowPageScroll : false, // scroll amount applied to each mouse wheel step wheelStep : 20, // scroll amount applied when user is using gestures touchScrollStep : 200, // sets border radius borderRadius: '7px', // sets border radius of the rail railBorderRadius : '7px' }; var o = $.extend(defaults, options); // do it for every element that matches selector this.each(function(){ var isOverPanel, isOverBar, isDragg, queueHide, touchDif, barHeight, percentScroll, lastScroll, divS = '<div></div>', minBarHeight = 30, releaseScroll = false; // used in event handlers and for better minification var me = $(this); // ensure we are not binding it again if (me.parent().hasClass(o.wrapperClass)) { // start from last bar position var offset = me.scrollTop(); // find bar and rail bar = me.parent().find('.' + o.barClass); rail = me.parent().find('.' + o.railClass); getBarHeight(); // check if we should scroll existing instance if ($.isPlainObject(options)) { // Pass height: auto to an existing slimscroll object to force a resize after contents have changed if ( 'height' in options && options.height == 'auto' ) { me.parent().css('height', 'auto'); me.css('height', 'auto'); var height = me.parent().parent().height(); me.parent().css('height', height); me.css('height', height); } if ('scrollTo' in options) { // jump to a static point offset = parseInt(o.scrollTo); } else if ('scrollBy' in options) { // jump by value pixels offset += parseInt(o.scrollBy); } else if ('destroy' in options) { // remove slimscroll elements bar.remove(); rail.remove(); me.unwrap(); return; } // scroll content by the given offset scrollContent(offset, false, true); } return; } // optionally set height to the parent's height o.height = (options.height == 'auto') ? me.parent().height() : options.height; // wrap content var wrapper = $(divS) .addClass(o.wrapperClass) .css({ position: 'relative', overflow: 'hidden', width: o.width, height: o.height }); // update style for the div me.css({ overflow: 'hidden', width: o.width, height: o.height }); // create scrollbar rail var rail = $(divS) .addClass(o.railClass) .css({ width: o.size, height: '100%', position: 'absolute', top: 0, display: (o.alwaysVisible && o.railVisible) ? 'block' : 'none', 'border-radius': o.railBorderRadius, background: o.railColor, opacity: o.railOpacity, zIndex: 90 }); // create scrollbar var bar = $(divS) .addClass(o.barClass) .css({ background: o.color, width: o.size, position: 'absolute', top: 0, opacity: o.opacity, display: o.alwaysVisible ? 'block' : 'none', 'border-radius' : o.borderRadius, BorderRadius: o.borderRadius, MozBorderRadius: o.borderRadius, WebkitBorderRadius: o.borderRadius, zIndex: 99 }); // set position var posCss = (o.position == 'right') ? { right: o.distance } : { left: o.distance }; rail.css(posCss); bar.css(posCss); // wrap it me.wrap(wrapper); // append to parent div me.parent().append(bar); me.parent().append(rail); // make it draggable and no longer dependent on the jqueryUI if (o.railDraggable){ bar.bind("mousedown", function(e) { var $doc = $(document); isDragg = true; t = parseFloat(bar.css('top')); pageY = e.pageY; $doc.bind("mousemove.slimscroll", function(e){ currTop = t + e.pageY - pageY; bar.css('top', currTop); scrollContent(0, bar.position().top, false);// scroll content }); $doc.bind("mouseup.slimscroll", function(e) { isDragg = false;hideBar(); $doc.unbind('.slimscroll'); }); return false; }).bind("selectstart.slimscroll", function(e){ e.stopPropagation(); e.preventDefault(); return false; }); } // on rail over rail.hover(function(){ showBar(); }, function(){ hideBar(); }); // on bar over bar.hover(function(){ isOverBar = true; }, function(){ isOverBar = false; }); // show on parent mouseover me.hover(function(){ isOverPanel = true; showBar(); hideBar(); }, function(){ isOverPanel = false; hideBar(); }); // support for mobile me.bind('touchstart', function(e,b){ if (e.originalEvent.touches.length) { // record where touch started touchDif = e.originalEvent.touches[0].pageY; } }); me.bind('touchmove', function(e){ // prevent scrolling the page if necessary if(!releaseScroll) { e.originalEvent.preventDefault(); } if (e.originalEvent.touches.length) { // see how far user swiped var diff = (touchDif - e.originalEvent.touches[0].pageY) / o.touchScrollStep; // scroll content scrollContent(diff, true); touchDif = e.originalEvent.touches[0].pageY; } }); // set up initial height getBarHeight(); // check start position if (o.start === 'bottom') { // scroll content to bottom bar.css({ top: me.outerHeight() - bar.outerHeight() }); scrollContent(0, true); } else if (o.start !== 'top') { // assume jQuery selector scrollContent($(o.start).position().top, null, true); // make sure bar stays hidden if (!o.alwaysVisible) { bar.hide(); } } // attach scroll events attachWheel(); function _onWheel(e) { // use mouse wheel only when mouse is over if (!isOverPanel) { return; } var e = e || window.event; var delta = 0; if (e.wheelDelta) { delta = -e.wheelDelta/120; } if (e.detail) { delta = e.detail / 3; } var target = e.target || e.srcTarget || e.srcElement; if ($(target).closest('.' + o.wrapperClass).is(me.parent())) { // scroll content scrollContent(delta, true); } // stop window scroll if (e.preventDefault && !releaseScroll) { e.preventDefault(); } if (!releaseScroll) { e.returnValue = false; } } function scrollContent(y, isWheel, isJump) { releaseScroll = false; var delta = y; var maxTop = me.outerHeight() - bar.outerHeight(); if (isWheel) { // move bar with mouse wheel delta = parseInt(bar.css('top')) + y * parseInt(o.wheelStep) / 100 * bar.outerHeight(); // move bar, make sure it doesn't go out delta = Math.min(Math.max(delta, 0), maxTop); // if scrolling down, make sure a fractional change to the // scroll position isn't rounded away when the scrollbar's CSS is set // this flooring of delta would happened automatically when // bar.css is set below, but we floor here for clarity delta = (y > 0) ? Math.ceil(delta) : Math.floor(delta); // scroll the scrollbar bar.css({ top: delta + 'px' }); } // calculate actual scroll amount percentScroll = parseInt(bar.css('top')) / (me.outerHeight() - bar.outerHeight()); delta = percentScroll * (me[0].scrollHeight - me.outerHeight()); if (isJump) { delta = y; var offsetTop = delta / me[0].scrollHeight * me.outerHeight(); offsetTop = Math.min(Math.max(offsetTop, 0), maxTop); bar.css({ top: offsetTop + 'px' }); } // scroll content me.scrollTop(delta); // fire scrolling event me.trigger('slimscrolling', ~~delta); // ensure bar is visible showBar(); // trigger hide when scroll is stopped hideBar(); } function attachWheel() { if (window.addEventListener) { this.addEventListener('DOMMouseScroll', _onWheel, false ); this.addEventListener('mousewheel', _onWheel, false ); } else { document.attachEvent("onmousewheel", _onWheel) } } function getBarHeight() { // calculate scrollbar height and make sure it is not too small barHeight = Math.max((me.outerHeight() / me[0].scrollHeight) * me.outerHeight(), minBarHeight); bar.css({ height: barHeight + 'px' }); // hide scrollbar if content is not long enough var display = barHeight == me.outerHeight() ? 'none' : 'block'; bar.css({ display: display }); } function showBar() { // recalculate bar height getBarHeight(); clearTimeout(queueHide); // when bar reached top or bottom if (percentScroll == ~~percentScroll) { //release wheel releaseScroll = o.allowPageScroll; // publish approporiate event if (lastScroll != percentScroll) { var msg = (~~percentScroll == 0) ? 'top' : 'bottom'; me.trigger('slimscroll', msg); } } else { releaseScroll = false; } lastScroll = percentScroll; // show only when required if(barHeight >= me.outerHeight()) { //allow window scroll releaseScroll = true; return; } bar.stop(true,true).fadeIn('fast'); if (o.railVisible) { rail.stop(true,true).fadeIn('fast'); } } function hideBar() { // only hide when options allow it if (!o.alwaysVisible) { queueHide = setTimeout(function(){ if (!(o.disableFadeOut && isOverPanel) && !isOverBar && !isDragg) { bar.fadeOut('slow'); rail.fadeOut('slow'); } }, 1000); } } }); // maintain chainability return this; } }); jQuery.fn.extend({ slimscroll: jQuery.fn.slimScroll }); })(jQuery);
JavaScript
/* Flot plugin for stacking data sets rather than overlyaing them. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The plugin assumes the data is sorted on x (or y if stacking horizontally). For line charts, it is assumed that if a line has an undefined gap (from a null point), then the line above it should have the same gap - insert zeros instead of "null" if you want another behaviour. This also holds for the start and end of the chart. Note that stacking a mix of positive and negative values in most instances doesn't make sense (so it looks weird). Two or more series are stacked when their "stack" attribute is set to the same key (which can be any number or string or just "true"). To specify the default stack, you can set the stack option like this: series: { stack: null/false, true, or a key (number/string) } You can also specify it for a single series, like this: $.plot( $("#placeholder"), [{ data: [ ... ], stack: true }]) The stacking order is determined by the order of the data series in the array (later series end up on top of the previous). Internally, the plugin modifies the datapoints in each series, adding an offset to the y value. For line series, extra data points are inserted through interpolation. If there's a second y value, it's also adjusted (e.g for bar charts or filled areas). */ (function ($) { var options = { series: { stack: null } // or number/string }; function init(plot) { function findMatchingSeries(s, allseries) { var res = null; for (var i = 0; i < allseries.length; ++i) { if (s == allseries[i]) break; if (allseries[i].stack == s.stack) res = allseries[i]; } return res; } function stackData(plot, s, datapoints) { if (s.stack == null || s.stack === false) return; var other = findMatchingSeries(s, plot.getData()); if (!other) return; var ps = datapoints.pointsize, points = datapoints.points, otherps = other.datapoints.pointsize, otherpoints = other.datapoints.points, newpoints = [], px, py, intery, qx, qy, bottom, withlines = s.lines.show, horizontal = s.bars.horizontal, withbottom = ps > 2 && (horizontal ? datapoints.format[2].x : datapoints.format[2].y), withsteps = withlines && s.lines.steps, fromgap = true, keyOffset = horizontal ? 1 : 0, accumulateOffset = horizontal ? 0 : 1, i = 0, j = 0, l, m; while (true) { if (i >= points.length) break; l = newpoints.length; if (points[i] == null) { // copy gaps for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); i += ps; } else if (j >= otherpoints.length) { // for lines, we can't use the rest of the points if (!withlines) { for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); } i += ps; } else if (otherpoints[j] == null) { // oops, got a gap for (m = 0; m < ps; ++m) newpoints.push(null); fromgap = true; j += otherps; } else { // cases where we actually got two points px = points[i + keyOffset]; py = points[i + accumulateOffset]; qx = otherpoints[j + keyOffset]; qy = otherpoints[j + accumulateOffset]; bottom = 0; if (px == qx) { for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); newpoints[l + accumulateOffset] += qy; bottom = qy; i += ps; j += otherps; } else if (px > qx) { // we got past point below, might need to // insert interpolated extra point if (withlines && i > 0 && points[i - ps] != null) { intery = py + (points[i - ps + accumulateOffset] - py) * (qx - px) / (points[i - ps + keyOffset] - px); newpoints.push(qx); newpoints.push(intery + qy); for (m = 2; m < ps; ++m) newpoints.push(points[i + m]); bottom = qy; } j += otherps; } else { // px < qx if (fromgap && withlines) { // if we come from a gap, we just skip this point i += ps; continue; } for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); // we might be able to interpolate a point below, // this can give us a better y if (withlines && j > 0 && otherpoints[j - otherps] != null) bottom = qy + (otherpoints[j - otherps + accumulateOffset] - qy) * (px - qx) / (otherpoints[j - otherps + keyOffset] - qx); newpoints[l + accumulateOffset] += bottom; i += ps; } fromgap = false; if (l != newpoints.length && withbottom) newpoints[l + 2] += bottom; } // maintain the line steps invariant if (withsteps && l != newpoints.length && l > 0 && newpoints[l] != null && newpoints[l] != newpoints[l - ps] && newpoints[l + 1] != newpoints[l - ps + 1]) { for (m = 0; m < ps; ++m) newpoints[l + ps + m] = newpoints[l + m]; newpoints[l + 1] = newpoints[l - ps + 1]; } } datapoints.points = newpoints; } plot.hooks.processDatapoints.push(stackData); } $.plot.plugins.push({ init: init, options: options, name: 'stack', version: '1.2' }); })(jQuery);
JavaScript
/* Flot plugin for plotting error bars. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. Error bars are used to show standard deviation and other statistical properties in a plot. * Created by Rui Pereira - rui (dot) pereira (at) gmail (dot) com This plugin allows you to plot error-bars over points. Set "errorbars" inside the points series to the axis name over which there will be error values in your data array (*even* if you do not intend to plot them later, by setting "show: null" on xerr/yerr). The plugin supports these options: series: { points: { errorbars: "x" or "y" or "xy", xerr: { show: null/false or true, asymmetric: null/false or true, upperCap: null or "-" or function, lowerCap: null or "-" or function, color: null or color, radius: null or number }, yerr: { same options as xerr } } } Each data point array is expected to be of the type: "x" [ x, y, xerr ] "y" [ x, y, yerr ] "xy" [ x, y, xerr, yerr ] Where xerr becomes xerr_lower,xerr_upper for the asymmetric error case, and equivalently for yerr. Eg., a datapoint for the "xy" case with symmetric error-bars on X and asymmetric on Y would be: [ x, y, xerr, yerr_lower, yerr_upper ] By default no end caps are drawn. Setting upperCap and/or lowerCap to "-" will draw a small cap perpendicular to the error bar. They can also be set to a user-defined drawing function, with (ctx, x, y, radius) as parameters, as eg. function drawSemiCircle( ctx, x, y, radius ) { ctx.beginPath(); ctx.arc( x, y, radius, 0, Math.PI, false ); ctx.moveTo( x - radius, y ); ctx.lineTo( x + radius, y ); ctx.stroke(); } Color and radius both default to the same ones of the points series if not set. The independent radius parameter on xerr/yerr is useful for the case when we may want to add error-bars to a line, without showing the interconnecting points (with radius: 0), and still showing end caps on the error-bars. shadowSize and lineWidth are derived as well from the points series. */ (function ($) { var options = { series: { points: { errorbars: null, //should be 'x', 'y' or 'xy' xerr: { err: 'x', show: null, asymmetric: null, upperCap: null, lowerCap: null, color: null, radius: null}, yerr: { err: 'y', show: null, asymmetric: null, upperCap: null, lowerCap: null, color: null, radius: null} } } }; function processRawData(plot, series, data, datapoints){ if (!series.points.errorbars) return; // x,y values var format = [ { x: true, number: true, required: true }, { y: true, number: true, required: true } ]; var errors = series.points.errorbars; // error bars - first X then Y if (errors == 'x' || errors == 'xy') { // lower / upper error if (series.points.xerr.asymmetric) { format.push({ x: true, number: true, required: true }); format.push({ x: true, number: true, required: true }); } else format.push({ x: true, number: true, required: true }); } if (errors == 'y' || errors == 'xy') { // lower / upper error if (series.points.yerr.asymmetric) { format.push({ y: true, number: true, required: true }); format.push({ y: true, number: true, required: true }); } else format.push({ y: true, number: true, required: true }); } datapoints.format = format; } function parseErrors(series, i){ var points = series.datapoints.points; // read errors from points array var exl = null, exu = null, eyl = null, eyu = null; var xerr = series.points.xerr, yerr = series.points.yerr; var eb = series.points.errorbars; // error bars - first X if (eb == 'x' || eb == 'xy') { if (xerr.asymmetric) { exl = points[i + 2]; exu = points[i + 3]; if (eb == 'xy') if (yerr.asymmetric){ eyl = points[i + 4]; eyu = points[i + 5]; } else eyl = points[i + 4]; } else { exl = points[i + 2]; if (eb == 'xy') if (yerr.asymmetric) { eyl = points[i + 3]; eyu = points[i + 4]; } else eyl = points[i + 3]; } // only Y } else if (eb == 'y') if (yerr.asymmetric) { eyl = points[i + 2]; eyu = points[i + 3]; } else eyl = points[i + 2]; // symmetric errors? if (exu == null) exu = exl; if (eyu == null) eyu = eyl; var errRanges = [exl, exu, eyl, eyu]; // nullify if not showing if (!xerr.show){ errRanges[0] = null; errRanges[1] = null; } if (!yerr.show){ errRanges[2] = null; errRanges[3] = null; } return errRanges; } function drawSeriesErrors(plot, ctx, s){ var points = s.datapoints.points, ps = s.datapoints.pointsize, ax = [s.xaxis, s.yaxis], radius = s.points.radius, err = [s.points.xerr, s.points.yerr]; //sanity check, in case some inverted axis hack is applied to flot var invertX = false; if (ax[0].p2c(ax[0].max) < ax[0].p2c(ax[0].min)) { invertX = true; var tmp = err[0].lowerCap; err[0].lowerCap = err[0].upperCap; err[0].upperCap = tmp; } var invertY = false; if (ax[1].p2c(ax[1].min) < ax[1].p2c(ax[1].max)) { invertY = true; var tmp = err[1].lowerCap; err[1].lowerCap = err[1].upperCap; err[1].upperCap = tmp; } for (var i = 0; i < s.datapoints.points.length; i += ps) { //parse var errRanges = parseErrors(s, i); //cycle xerr & yerr for (var e = 0; e < err.length; e++){ var minmax = [ax[e].min, ax[e].max]; //draw this error? if (errRanges[e * err.length]){ //data coordinates var x = points[i], y = points[i + 1]; //errorbar ranges var upper = [x, y][e] + errRanges[e * err.length + 1], lower = [x, y][e] - errRanges[e * err.length]; //points outside of the canvas if (err[e].err == 'x') if (y > ax[1].max || y < ax[1].min || upper < ax[0].min || lower > ax[0].max) continue; if (err[e].err == 'y') if (x > ax[0].max || x < ax[0].min || upper < ax[1].min || lower > ax[1].max) continue; // prevent errorbars getting out of the canvas var drawUpper = true, drawLower = true; if (upper > minmax[1]) { drawUpper = false; upper = minmax[1]; } if (lower < minmax[0]) { drawLower = false; lower = minmax[0]; } //sanity check, in case some inverted axis hack is applied to flot if ((err[e].err == 'x' && invertX) || (err[e].err == 'y' && invertY)) { //swap coordinates var tmp = lower; lower = upper; upper = tmp; tmp = drawLower; drawLower = drawUpper; drawUpper = tmp; tmp = minmax[0]; minmax[0] = minmax[1]; minmax[1] = tmp; } // convert to pixels x = ax[0].p2c(x), y = ax[1].p2c(y), upper = ax[e].p2c(upper); lower = ax[e].p2c(lower); minmax[0] = ax[e].p2c(minmax[0]); minmax[1] = ax[e].p2c(minmax[1]); //same style as points by default var lw = err[e].lineWidth ? err[e].lineWidth : s.points.lineWidth, sw = s.points.shadowSize != null ? s.points.shadowSize : s.shadowSize; //shadow as for points if (lw > 0 && sw > 0) { var w = sw / 2; ctx.lineWidth = w; ctx.strokeStyle = "rgba(0,0,0,0.1)"; drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, w + w/2, minmax); ctx.strokeStyle = "rgba(0,0,0,0.2)"; drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, w/2, minmax); } ctx.strokeStyle = err[e].color? err[e].color: s.color; ctx.lineWidth = lw; //draw it drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, 0, minmax); } } } } function drawError(ctx,err,x,y,upper,lower,drawUpper,drawLower,radius,offset,minmax){ //shadow offset y += offset; upper += offset; lower += offset; // error bar - avoid plotting over circles if (err.err == 'x'){ if (upper > x + radius) drawPath(ctx, [[upper,y],[Math.max(x + radius,minmax[0]),y]]); else drawUpper = false; if (lower < x - radius) drawPath(ctx, [[Math.min(x - radius,minmax[1]),y],[lower,y]] ); else drawLower = false; } else { if (upper < y - radius) drawPath(ctx, [[x,upper],[x,Math.min(y - radius,minmax[0])]] ); else drawUpper = false; if (lower > y + radius) drawPath(ctx, [[x,Math.max(y + radius,minmax[1])],[x,lower]] ); else drawLower = false; } //internal radius value in errorbar, allows to plot radius 0 points and still keep proper sized caps //this is a way to get errorbars on lines without visible connecting dots radius = err.radius != null? err.radius: radius; // upper cap if (drawUpper) { if (err.upperCap == '-'){ if (err.err=='x') drawPath(ctx, [[upper,y - radius],[upper,y + radius]] ); else drawPath(ctx, [[x - radius,upper],[x + radius,upper]] ); } else if ($.isFunction(err.upperCap)){ if (err.err=='x') err.upperCap(ctx, upper, y, radius); else err.upperCap(ctx, x, upper, radius); } } // lower cap if (drawLower) { if (err.lowerCap == '-'){ if (err.err=='x') drawPath(ctx, [[lower,y - radius],[lower,y + radius]] ); else drawPath(ctx, [[x - radius,lower],[x + radius,lower]] ); } else if ($.isFunction(err.lowerCap)){ if (err.err=='x') err.lowerCap(ctx, lower, y, radius); else err.lowerCap(ctx, x, lower, radius); } } } function drawPath(ctx, pts){ ctx.beginPath(); ctx.moveTo(pts[0][0], pts[0][1]); for (var p=1; p < pts.length; p++) ctx.lineTo(pts[p][0], pts[p][1]); ctx.stroke(); } function draw(plot, ctx){ var plotOffset = plot.getPlotOffset(); ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); $.each(plot.getData(), function (i, s) { if (s.points.errorbars && (s.points.xerr.show || s.points.yerr.show)) drawSeriesErrors(plot, ctx, s); }); ctx.restore(); } function init(plot) { plot.hooks.processRawData.push(processRawData); plot.hooks.draw.push(draw); } $.plot.plugins.push({ init: init, options: options, name: 'errorbars', version: '1.0' }); })(jQuery);
JavaScript
/* Javascript plotting library for jQuery, version 0.8.2. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. */ // first an inline dependency, jquery.colorhelpers.js, we inline it here // for convenience /* Plugin for jQuery for working with colors. * * Version 1.1. * * Inspiration from jQuery color animation plugin by John Resig. * * Released under the MIT license by Ole Laursen, October 2009. * * Examples: * * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString() * var c = $.color.extract($("#mydiv"), 'background-color'); * console.log(c.r, c.g, c.b, c.a); * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)" * * Note that .scale() and .add() return the same modified object * instead of making a new one. * * V. 1.1: Fix error handling so e.g. parsing an empty string does * produce a color rather than just crashing. */ (function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i<c.length;++i)o[c.charAt(i)]+=d;return o.normalize()};o.scale=function(c,f){for(var i=0;i<c.length;++i)o[c.charAt(i)]*=f;return o.normalize()};o.toString=function(){if(o.a>=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return value<min?min:value>max?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/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(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery); // the actual Flot code (function($) { // Cache the prototype hasOwnProperty for faster access var hasOwnProperty = Object.prototype.hasOwnProperty; /////////////////////////////////////////////////////////////////////////// // The Canvas object is a wrapper around an HTML5 <canvas> tag. // // @constructor // @param {string} cls List of classes to apply to the canvas. // @param {element} container Element onto which to append the canvas. // // Requiring a container is a little iffy, but unfortunately canvas // operations don't work unless the canvas is attached to the DOM. function Canvas(cls, container) { var element = container.children("." + cls)[0]; if (element == null) { element = document.createElement("canvas"); element.className = cls; $(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 }) .appendTo(container); // If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas if (!element.getContext) { if (window.G_vmlCanvasManager) { element = window.G_vmlCanvasManager.initElement(element); } else { throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode."); } } } this.element = element; var context = this.context = element.getContext("2d"); // Determine the screen's ratio of physical to device-independent // pixels. This is the ratio between the canvas width that the browser // advertises and the number of pixels actually present in that space. // The iPhone 4, for example, has a device-independent width of 320px, // but its screen is actually 640px wide. It therefore has a pixel // ratio of 2, while most normal devices have a ratio of 1. var devicePixelRatio = window.devicePixelRatio || 1, backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; this.pixelRatio = devicePixelRatio / backingStoreRatio; // Size the canvas to match the internal dimensions of its container this.resize(container.width(), container.height()); // Collection of HTML div layers for text overlaid onto the canvas this.textContainer = null; this.text = {}; // Cache of text fragments and metrics, so we can avoid expensively // re-calculating them when the plot is re-rendered in a loop. this._textCache = {}; } // Resizes the canvas to the given dimensions. // // @param {number} width New width of the canvas, in pixels. // @param {number} width New height of the canvas, in pixels. Canvas.prototype.resize = function(width, height) { if (width <= 0 || height <= 0) { throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height); } var element = this.element, context = this.context, pixelRatio = this.pixelRatio; // Resize the canvas, increasing its density based on the display's // pixel ratio; basically giving it more pixels without increasing the // size of its element, to take advantage of the fact that retina // displays have that many more pixels in the same advertised space. // Resizing should reset the state (excanvas seems to be buggy though) if (this.width != width) { element.width = width * pixelRatio; element.style.width = width + "px"; this.width = width; } if (this.height != height) { element.height = height * pixelRatio; element.style.height = height + "px"; this.height = height; } // Save the context, so we can reset in case we get replotted. The // restore ensure that we're really back at the initial state, and // should be safe even if we haven't saved the initial state yet. context.restore(); context.save(); // Scale the coordinate space to match the display density; so even though we // may have twice as many pixels, we still want lines and other drawing to // appear at the same size; the extra pixels will just make them crisper. context.scale(pixelRatio, pixelRatio); }; // Clears the entire canvas area, not including any overlaid HTML text Canvas.prototype.clear = function() { this.context.clearRect(0, 0, this.width, this.height); }; // Finishes rendering the canvas, including managing the text overlay. Canvas.prototype.render = function() { var cache = this._textCache; // For each text layer, add elements marked as active that haven't // already been rendered, and remove those that are no longer active. for (var layerKey in cache) { if (hasOwnProperty.call(cache, layerKey)) { var layer = this.getTextLayer(layerKey), layerCache = cache[layerKey]; layer.hide(); for (var styleKey in layerCache) { if (hasOwnProperty.call(layerCache, styleKey)) { var styleCache = layerCache[styleKey]; for (var key in styleCache) { if (hasOwnProperty.call(styleCache, key)) { var positions = styleCache[key].positions; for (var i = 0, position; position = positions[i]; i++) { if (position.active) { if (!position.rendered) { layer.append(position.element); position.rendered = true; } } else { positions.splice(i--, 1); if (position.rendered) { position.element.detach(); } } } if (positions.length == 0) { delete styleCache[key]; } } } } } layer.show(); } } }; // Creates (if necessary) and returns the text overlay container. // // @param {string} classes String of space-separated CSS classes used to // uniquely identify the text layer. // @return {object} The jQuery-wrapped text-layer div. Canvas.prototype.getTextLayer = function(classes) { var layer = this.text[classes]; // Create the text layer if it doesn't exist if (layer == null) { // Create the text layer container, if it doesn't exist if (this.textContainer == null) { this.textContainer = $("<div class='flot-text'></div>") .css({ position: "absolute", top: 0, left: 0, bottom: 0, right: 0, 'font-size': "smaller", color: "#545454" }) .insertAfter(this.element); } layer = this.text[classes] = $("<div></div>") .addClass(classes) .css({ position: "absolute", top: 0, left: 0, bottom: 0, right: 0 }) .appendTo(this.textContainer); } return layer; }; // Creates (if necessary) and returns a text info object. // // The object looks like this: // // { // width: Width of the text's wrapper div. // height: Height of the text's wrapper div. // element: The jQuery-wrapped HTML div containing the text. // positions: Array of positions at which this text is drawn. // } // // The positions array contains objects that look like this: // // { // active: Flag indicating whether the text should be visible. // rendered: Flag indicating whether the text is currently visible. // element: The jQuery-wrapped HTML div containing the text. // x: X coordinate at which to draw the text. // y: Y coordinate at which to draw the text. // } // // Each position after the first receives a clone of the original element. // // The idea is that that the width, height, and general 'identity' of the // text is constant no matter where it is placed; the placements are a // secondary property. // // Canvas maintains a cache of recently-used text info objects; getTextInfo // either returns the cached element or creates a new entry. // // @param {string} layer A string of space-separated CSS classes uniquely // identifying the layer containing this text. // @param {string} text Text string to retrieve info for. // @param {(string|object)=} font Either a string of space-separated CSS // classes or a font-spec object, defining the text's font and style. // @param {number=} angle Angle at which to rotate the text, in degrees. // Angle is currently unused, it will be implemented in the future. // @param {number=} width Maximum width of the text before it wraps. // @return {object} a text info object. Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) { var textStyle, layerCache, styleCache, info; // Cast the value to a string, in case we were given a number or such text = "" + text; // If the font is a font-spec object, generate a CSS font definition if (typeof font === "object") { textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family; } else { textStyle = font; } // Retrieve (or create) the cache for the text's layer and styles layerCache = this._textCache[layer]; if (layerCache == null) { layerCache = this._textCache[layer] = {}; } styleCache = layerCache[textStyle]; if (styleCache == null) { styleCache = layerCache[textStyle] = {}; } info = styleCache[text]; // If we can't find a matching element in our cache, create a new one if (info == null) { var element = $("<div></div>").html(text) .css({ position: "absolute", 'max-width': width, top: -9999 }) .appendTo(this.getTextLayer(layer)); if (typeof font === "object") { element.css({ font: textStyle, color: font.color }); } else if (typeof font === "string") { element.addClass(font); } info = styleCache[text] = { width: element.outerWidth(true), height: element.outerHeight(true), element: element, positions: [] }; element.detach(); } return info; }; // Adds a text string to the canvas text overlay. // // The text isn't drawn immediately; it is marked as rendering, which will // result in its addition to the canvas on the next render pass. // // @param {string} layer A string of space-separated CSS classes uniquely // identifying the layer containing this text. // @param {number} x X coordinate at which to draw the text. // @param {number} y Y coordinate at which to draw the text. // @param {string} text Text string to draw. // @param {(string|object)=} font Either a string of space-separated CSS // classes or a font-spec object, defining the text's font and style. // @param {number=} angle Angle at which to rotate the text, in degrees. // Angle is currently unused, it will be implemented in the future. // @param {number=} width Maximum width of the text before it wraps. // @param {string=} halign Horizontal alignment of the text; either "left", // "center" or "right". // @param {string=} valign Vertical alignment of the text; either "top", // "middle" or "bottom". Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) { var info = this.getTextInfo(layer, text, font, angle, width), positions = info.positions; // Tweak the div's position to match the text's alignment if (halign == "center") { x -= info.width / 2; } else if (halign == "right") { x -= info.width; } if (valign == "middle") { y -= info.height / 2; } else if (valign == "bottom") { y -= info.height; } // Determine whether this text already exists at this position. // If so, mark it for inclusion in the next render pass. for (var i = 0, position; position = positions[i]; i++) { if (position.x == x && position.y == y) { position.active = true; return; } } // If the text doesn't exist at this position, create a new entry // For the very first position we'll re-use the original element, // while for subsequent ones we'll clone it. position = { active: true, rendered: false, element: positions.length ? info.element.clone() : info.element, x: x, y: y }; positions.push(position); // Move the element to its final position within the container position.element.css({ top: Math.round(y), left: Math.round(x), 'text-align': halign // In case the text wraps }); }; // Removes one or more text strings from the canvas text overlay. // // If no parameters are given, all text within the layer is removed. // // Note that the text is not immediately removed; it is simply marked as // inactive, which will result in its removal on the next render pass. // This avoids the performance penalty for 'clear and redraw' behavior, // where we potentially get rid of all text on a layer, but will likely // add back most or all of it later, as when redrawing axes, for example. // // @param {string} layer A string of space-separated CSS classes uniquely // identifying the layer containing this text. // @param {number=} x X coordinate of the text. // @param {number=} y Y coordinate of the text. // @param {string=} text Text string to remove. // @param {(string|object)=} font Either a string of space-separated CSS // classes or a font-spec object, defining the text's font and style. // @param {number=} angle Angle at which the text is rotated, in degrees. // Angle is currently unused, it will be implemented in the future. Canvas.prototype.removeText = function(layer, x, y, text, font, angle) { if (text == null) { var layerCache = this._textCache[layer]; if (layerCache != null) { for (var styleKey in layerCache) { if (hasOwnProperty.call(layerCache, styleKey)) { var styleCache = layerCache[styleKey]; for (var key in styleCache) { if (hasOwnProperty.call(styleCache, key)) { var positions = styleCache[key].positions; for (var i = 0, position; position = positions[i]; i++) { position.active = false; } } } } } } } else { var positions = this.getTextInfo(layer, text, font, angle).positions; for (var i = 0, position; position = positions[i]; i++) { if (position.x == x && position.y == y) { position.active = false; } } } }; /////////////////////////////////////////////////////////////////////////// // The top-level container for the entire plot. function Plot(placeholder, data_, options_, plugins) { // data is on the form: // [ series1, series2 ... ] // where series is either just the data as [ [x1, y1], [x2, y2], ... ] // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... } var series = [], options = { // the color theme used for graphs colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"], legend: { show: true, noColumns: 1, // number of colums in legend table labelFormatter: null, // fn: string -> string labelBoxBorderColor: "#ccc", // border color for the little label boxes container: null, // container (as jQuery object) to put legend in, null means default on top of graph position: "ne", // position of default legend container within plot margin: 5, // distance from grid edge to default legend container within plot backgroundColor: null, // null means auto-detect backgroundOpacity: 0.85, // set to 0 to avoid background sorted: null // default to no legend sorting }, xaxis: { show: null, // null = auto-detect, true = always, false = never position: "bottom", // or "top" mode: null, // null or "time" font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" } color: null, // base color, labels, ticks tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)" transform: null, // null or f: number -> number to transform axis inverseTransform: null, // if transform is set, this should be the inverse function min: null, // min. value to show, null means set automatically max: null, // max. value to show, null means set automatically autoscaleMargin: null, // margin in % to add if auto-setting min/max ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks tickFormatter: null, // fn: number -> string labelWidth: null, // size of tick labels in pixels labelHeight: null, reserveSpace: null, // whether to reserve space even if axis isn't shown tickLength: null, // size in pixels of ticks, or "full" for whole line alignTicksWithAxis: null, // axis number or null for no sync tickDecimals: null, // no. of decimals, null means auto tickSize: null, // number or [number, "unit"] minTickSize: null // number or [number, "unit"] }, yaxis: { autoscaleMargin: 0.02, position: "left" // or "right" }, xaxes: [], yaxes: [], series: { points: { show: false, radius: 3, lineWidth: 2, // in pixels fill: true, fillColor: "#ffffff", symbol: "circle" // or callback }, lines: { // we don't put in show: false so we can see // whether lines were actively disabled lineWidth: 2, // in pixels fill: false, fillColor: null, steps: false // Omit 'zero', so we can later default its value to // match that of the 'fill' option. }, bars: { show: false, lineWidth: 2, // in pixels barWidth: 1, // in units of the x axis fill: true, fillColor: null, align: "left", // "left", "right", or "center" horizontal: false, zero: true }, shadowSize: 3, highlightColor: null }, grid: { show: true, aboveData: false, color: "#545454", // primary color used for outline and labels backgroundColor: null, // null for transparent, else color borderColor: null, // set if different from the grid color tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)" margin: 0, // distance from the canvas edge to the grid labelMargin: 5, // in pixels axisMargin: 8, // in pixels borderWidth: 2, // in pixels minBorderMargin: null, // in pixels, null means taken from points radius markings: null, // array of ranges or fn: axes -> array of ranges markingsColor: "#f4f4f4", markingsLineWidth: 2, // interactive stuff clickable: false, hoverable: false, autoHighlight: true, // highlight in case mouse is near mouseActiveRadius: 10 // how far the mouse can be away to activate an item }, interaction: { redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow }, hooks: {} }, surface = null, // the canvas for the plot itself overlay = null, // canvas for interactive stuff on top of plot eventHolder = null, // jQuery object that events should be bound to ctx = null, octx = null, xaxes = [], yaxes = [], plotOffset = { left: 0, right: 0, top: 0, bottom: 0}, plotWidth = 0, plotHeight = 0, hooks = { processOptions: [], processRawData: [], processDatapoints: [], processOffset: [], drawBackground: [], drawSeries: [], draw: [], bindEvents: [], drawOverlay: [], shutdown: [] }, plot = this; // public functions plot.setData = setData; plot.setupGrid = setupGrid; plot.draw = draw; plot.getPlaceholder = function() { return placeholder; }; plot.getCanvas = function() { return surface.element; }; plot.getPlotOffset = function() { return plotOffset; }; plot.width = function () { return plotWidth; }; plot.height = function () { return plotHeight; }; plot.offset = function () { var o = eventHolder.offset(); o.left += plotOffset.left; o.top += plotOffset.top; return o; }; plot.getData = function () { return series; }; plot.getAxes = function () { var res = {}, i; $.each(xaxes.concat(yaxes), function (_, axis) { if (axis) res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis; }); return res; }; plot.getXAxes = function () { return xaxes; }; plot.getYAxes = function () { return yaxes; }; plot.c2p = canvasToAxisCoords; plot.p2c = axisToCanvasCoords; plot.getOptions = function () { return options; }; plot.highlight = highlight; plot.unhighlight = unhighlight; plot.triggerRedrawOverlay = triggerRedrawOverlay; plot.pointOffset = function(point) { return { left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10), top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10) }; }; plot.shutdown = shutdown; plot.destroy = function () { shutdown(); placeholder.removeData("plot").empty(); series = []; options = null; surface = null; overlay = null; eventHolder = null; ctx = null; octx = null; xaxes = []; yaxes = []; hooks = null; highlights = []; plot = null; }; plot.resize = function () { var width = placeholder.width(), height = placeholder.height(); surface.resize(width, height); overlay.resize(width, height); }; // public attributes plot.hooks = hooks; // initialize initPlugins(plot); parseOptions(options_); setupCanvases(); setData(data_); setupGrid(); draw(); bindEvents(); function executeHooks(hook, args) { args = [plot].concat(args); for (var i = 0; i < hook.length; ++i) hook[i].apply(this, args); } function initPlugins() { // References to key classes, allowing plugins to modify them var classes = { Canvas: Canvas }; for (var i = 0; i < plugins.length; ++i) { var p = plugins[i]; p.init(plot, classes); if (p.options) $.extend(true, options, p.options); } } function parseOptions(opts) { $.extend(true, options, opts); // $.extend merges arrays, rather than replacing them. When less // colors are provided than the size of the default palette, we // end up with those colors plus the remaining defaults, which is // not expected behavior; avoid it by replacing them here. if (opts && opts.colors) { options.colors = opts.colors; } if (options.xaxis.color == null) options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString(); if (options.yaxis.color == null) options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString(); if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color; if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color; if (options.grid.borderColor == null) options.grid.borderColor = options.grid.color; if (options.grid.tickColor == null) options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString(); // Fill in defaults for axis options, including any unspecified // font-spec fields, if a font-spec was provided. // If no x/y axis options were provided, create one of each anyway, // since the rest of the code assumes that they exist. var i, axisOptions, axisCount, fontSize = placeholder.css("font-size"), fontSizeDefault = fontSize ? +fontSize.replace("px", "") : 13, fontDefaults = { style: placeholder.css("font-style"), size: Math.round(0.8 * fontSizeDefault), variant: placeholder.css("font-variant"), weight: placeholder.css("font-weight"), family: placeholder.css("font-family") }; axisCount = options.xaxes.length || 1; for (i = 0; i < axisCount; ++i) { axisOptions = options.xaxes[i]; if (axisOptions && !axisOptions.tickColor) { axisOptions.tickColor = axisOptions.color; } axisOptions = $.extend(true, {}, options.xaxis, axisOptions); options.xaxes[i] = axisOptions; if (axisOptions.font) { axisOptions.font = $.extend({}, fontDefaults, axisOptions.font); if (!axisOptions.font.color) { axisOptions.font.color = axisOptions.color; } if (!axisOptions.font.lineHeight) { axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15); } } } axisCount = options.yaxes.length || 1; for (i = 0; i < axisCount; ++i) { axisOptions = options.yaxes[i]; if (axisOptions && !axisOptions.tickColor) { axisOptions.tickColor = axisOptions.color; } axisOptions = $.extend(true, {}, options.yaxis, axisOptions); options.yaxes[i] = axisOptions; if (axisOptions.font) { axisOptions.font = $.extend({}, fontDefaults, axisOptions.font); if (!axisOptions.font.color) { axisOptions.font.color = axisOptions.color; } if (!axisOptions.font.lineHeight) { axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15); } } } // backwards compatibility, to be removed in future if (options.xaxis.noTicks && options.xaxis.ticks == null) options.xaxis.ticks = options.xaxis.noTicks; if (options.yaxis.noTicks && options.yaxis.ticks == null) options.yaxis.ticks = options.yaxis.noTicks; if (options.x2axis) { options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis); options.xaxes[1].position = "top"; } if (options.y2axis) { options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis); options.yaxes[1].position = "right"; } if (options.grid.coloredAreas) options.grid.markings = options.grid.coloredAreas; if (options.grid.coloredAreasColor) options.grid.markingsColor = options.grid.coloredAreasColor; if (options.lines) $.extend(true, options.series.lines, options.lines); if (options.points) $.extend(true, options.series.points, options.points); if (options.bars) $.extend(true, options.series.bars, options.bars); if (options.shadowSize != null) options.series.shadowSize = options.shadowSize; if (options.highlightColor != null) options.series.highlightColor = options.highlightColor; // save options on axes for future reference for (i = 0; i < options.xaxes.length; ++i) getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i]; for (i = 0; i < options.yaxes.length; ++i) getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i]; // add hooks from options for (var n in hooks) if (options.hooks[n] && options.hooks[n].length) hooks[n] = hooks[n].concat(options.hooks[n]); executeHooks(hooks.processOptions, [options]); } function setData(d) { series = parseData(d); fillInSeriesOptions(); processData(); } function parseData(d) { var res = []; for (var i = 0; i < d.length; ++i) { var s = $.extend(true, {}, options.series); if (d[i].data != null) { s.data = d[i].data; // move the data instead of deep-copy delete d[i].data; $.extend(true, s, d[i]); d[i].data = s.data; } else s.data = d[i]; res.push(s); } return res; } function axisNumber(obj, coord) { var a = obj[coord + "axis"]; if (typeof a == "object") // if we got a real axis, extract number a = a.n; if (typeof a != "number") a = 1; // default to first axis return a; } function allAxes() { // return flat array without annoying null entries return $.grep(xaxes.concat(yaxes), function (a) { return a; }); } function canvasToAxisCoords(pos) { // return an object with x/y corresponding to all used axes var res = {}, i, axis; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; if (axis && axis.used) res["x" + axis.n] = axis.c2p(pos.left); } for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) res["y" + axis.n] = axis.c2p(pos.top); } if (res.x1 !== undefined) res.x = res.x1; if (res.y1 !== undefined) res.y = res.y1; return res; } function axisToCanvasCoords(pos) { // get canvas coords from the first pair of x/y found in pos var res = {}, i, axis, key; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; if (axis && axis.used) { key = "x" + axis.n; if (pos[key] == null && axis.n == 1) key = "x"; if (pos[key] != null) { res.left = axis.p2c(pos[key]); break; } } } for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) { key = "y" + axis.n; if (pos[key] == null && axis.n == 1) key = "y"; if (pos[key] != null) { res.top = axis.p2c(pos[key]); break; } } } return res; } function getOrCreateAxis(axes, number) { if (!axes[number - 1]) axes[number - 1] = { n: number, // save the number for future reference direction: axes == xaxes ? "x" : "y", options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis) }; return axes[number - 1]; } function fillInSeriesOptions() { var neededColors = series.length, maxIndex = -1, i; // Subtract the number of series that already have fixed colors or // color indexes from the number that we still need to generate. for (i = 0; i < series.length; ++i) { var sc = series[i].color; if (sc != null) { neededColors--; if (typeof sc == "number" && sc > maxIndex) { maxIndex = sc; } } } // If any of the series have fixed color indexes, then we need to // generate at least as many colors as the highest index. if (neededColors <= maxIndex) { neededColors = maxIndex + 1; } // Generate all the colors, using first the option colors and then // variations on those colors once they're exhausted. var c, colors = [], colorPool = options.colors, colorPoolSize = colorPool.length, variation = 0; for (i = 0; i < neededColors; i++) { c = $.color.parse(colorPool[i % colorPoolSize] || "#666"); // Each time we exhaust the colors in the pool we adjust // a scaling factor used to produce more variations on // those colors. The factor alternates negative/positive // to produce lighter/darker colors. // Reset the variation after every few cycles, or else // it will end up producing only white or black colors. if (i % colorPoolSize == 0 && i) { if (variation >= 0) { if (variation < 0.5) { variation = -variation - 0.2; } else variation = 0; } else variation = -variation; } colors[i] = c.scale('rgb', 1 + variation); } // Finalize the series options, filling in their colors var colori = 0, s; for (i = 0; i < series.length; ++i) { s = series[i]; // assign colors if (s.color == null) { s.color = colors[colori].toString(); ++colori; } else if (typeof s.color == "number") s.color = colors[s.color].toString(); // turn on lines automatically in case nothing is set if (s.lines.show == null) { var v, show = true; for (v in s) if (s[v] && s[v].show) { show = false; break; } if (show) s.lines.show = true; } // If nothing was provided for lines.zero, default it to match // lines.fill, since areas by default should extend to zero. if (s.lines.zero == null) { s.lines.zero = !!s.lines.fill; } // setup axes s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x")); s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y")); } } function processData() { var topSentry = Number.POSITIVE_INFINITY, bottomSentry = Number.NEGATIVE_INFINITY, fakeInfinity = Number.MAX_VALUE, i, j, k, m, length, s, points, ps, x, y, axis, val, f, p, data, format; function updateAxis(axis, min, max) { if (min < axis.datamin && min != -fakeInfinity) axis.datamin = min; if (max > axis.datamax && max != fakeInfinity) axis.datamax = max; } $.each(allAxes(), function (_, axis) { // init axis axis.datamin = topSentry; axis.datamax = bottomSentry; axis.used = false; }); for (i = 0; i < series.length; ++i) { s = series[i]; s.datapoints = { points: [] }; executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]); } // first pass: clean and copy data for (i = 0; i < series.length; ++i) { s = series[i]; data = s.data; format = s.datapoints.format; if (!format) { format = []; // find out how to copy format.push({ x: true, number: true, required: true }); format.push({ y: true, number: true, required: true }); if (s.bars.show || (s.lines.show && s.lines.fill)) { var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero)); format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale }); if (s.bars.horizontal) { delete format[format.length - 1].y; format[format.length - 1].x = true; } } s.datapoints.format = format; } if (s.datapoints.pointsize != null) continue; // already filled in s.datapoints.pointsize = format.length; ps = s.datapoints.pointsize; points = s.datapoints.points; var insertSteps = s.lines.show && s.lines.steps; s.xaxis.used = s.yaxis.used = true; for (j = k = 0; j < data.length; ++j, k += ps) { p = data[j]; var nullify = p == null; if (!nullify) { for (m = 0; m < ps; ++m) { val = p[m]; f = format[m]; if (f) { if (f.number && val != null) { val = +val; // convert to number if (isNaN(val)) val = null; else if (val == Infinity) val = fakeInfinity; else if (val == -Infinity) val = -fakeInfinity; } if (val == null) { if (f.required) nullify = true; if (f.defaultValue != null) val = f.defaultValue; } } points[k + m] = val; } } if (nullify) { for (m = 0; m < ps; ++m) { val = points[k + m]; if (val != null) { f = format[m]; // extract min/max info if (f.autoscale !== false) { if (f.x) { updateAxis(s.xaxis, val, val); } if (f.y) { updateAxis(s.yaxis, val, val); } } } points[k + m] = null; } } else { // a little bit of line specific stuff that // perhaps shouldn't be here, but lacking // better means... if (insertSteps && k > 0 && points[k - ps] != null && points[k - ps] != points[k] && points[k - ps + 1] != points[k + 1]) { // copy the point to make room for a middle point for (m = 0; m < ps; ++m) points[k + ps + m] = points[k + m]; // middle point has same y points[k + 1] = points[k - ps + 1]; // we've added a point, better reflect that k += ps; } } } } // give the hooks a chance to run for (i = 0; i < series.length; ++i) { s = series[i]; executeHooks(hooks.processDatapoints, [ s, s.datapoints]); } // second pass: find datamax/datamin for auto-scaling for (i = 0; i < series.length; ++i) { s = series[i]; points = s.datapoints.points; ps = s.datapoints.pointsize; format = s.datapoints.format; var xmin = topSentry, ymin = topSentry, xmax = bottomSentry, ymax = bottomSentry; for (j = 0; j < points.length; j += ps) { if (points[j] == null) continue; for (m = 0; m < ps; ++m) { val = points[j + m]; f = format[m]; if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity) continue; if (f.x) { if (val < xmin) xmin = val; if (val > xmax) xmax = val; } if (f.y) { if (val < ymin) ymin = val; if (val > ymax) ymax = val; } } } if (s.bars.show) { // make sure we got room for the bar on the dancing floor var delta; switch (s.bars.align) { case "left": delta = 0; break; case "right": delta = -s.bars.barWidth; break; default: delta = -s.bars.barWidth / 2; } if (s.bars.horizontal) { ymin += delta; ymax += delta + s.bars.barWidth; } else { xmin += delta; xmax += delta + s.bars.barWidth; } } updateAxis(s.xaxis, xmin, xmax); updateAxis(s.yaxis, ymin, ymax); } $.each(allAxes(), function (_, axis) { if (axis.datamin == topSentry) axis.datamin = null; if (axis.datamax == bottomSentry) axis.datamax = null; }); } function setupCanvases() { // Make sure the placeholder is clear of everything except canvases // from a previous plot in this container that we'll try to re-use. placeholder.css("padding", 0) // padding messes up the positioning .children().filter(function(){ return !$(this).hasClass("flot-overlay") && !$(this).hasClass('flot-base'); }).remove(); if (placeholder.css("position") == 'static') placeholder.css("position", "relative"); // for positioning labels and overlay surface = new Canvas("flot-base", placeholder); overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features ctx = surface.context; octx = overlay.context; // define which element we're listening for events on eventHolder = $(overlay.element).unbind(); // If we're re-using a plot object, shut down the old one var existing = placeholder.data("plot"); if (existing) { existing.shutdown(); overlay.clear(); } // save in case we get replotted placeholder.data("plot", plot); } function bindEvents() { // bind events if (options.grid.hoverable) { eventHolder.mousemove(onMouseMove); // Use bind, rather than .mouseleave, because we officially // still support jQuery 1.2.6, which doesn't define a shortcut // for mouseenter or mouseleave. This was a bug/oversight that // was fixed somewhere around 1.3.x. We can return to using // .mouseleave when we drop support for 1.2.6. eventHolder.bind("mouseleave", onMouseLeave); } if (options.grid.clickable) eventHolder.click(onClick); executeHooks(hooks.bindEvents, [eventHolder]); } function shutdown() { if (redrawTimeout) clearTimeout(redrawTimeout); eventHolder.unbind("mousemove", onMouseMove); eventHolder.unbind("mouseleave", onMouseLeave); eventHolder.unbind("click", onClick); executeHooks(hooks.shutdown, [eventHolder]); } function setTransformationHelpers(axis) { // set helper functions on the axis, assumes plot area // has been computed already function identity(x) { return x; } var s, m, t = axis.options.transform || identity, it = axis.options.inverseTransform; // precompute how much the axis is scaling a point // in canvas space if (axis.direction == "x") { s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min)); m = Math.min(t(axis.max), t(axis.min)); } else { s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min)); s = -s; m = Math.max(t(axis.max), t(axis.min)); } // data point to canvas coordinate if (t == identity) // slight optimization axis.p2c = function (p) { return (p - m) * s; }; else axis.p2c = function (p) { return (t(p) - m) * s; }; // canvas coordinate to data point if (!it) axis.c2p = function (c) { return m + c / s; }; else axis.c2p = function (c) { return it(m + c / s); }; } function measureTickLabels(axis) { var opts = axis.options, ticks = axis.ticks || [], labelWidth = opts.labelWidth || 0, labelHeight = opts.labelHeight || 0, maxWidth = labelWidth || (axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null), legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis", layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles, font = opts.font || "flot-tick-label tickLabel"; for (var i = 0; i < ticks.length; ++i) { var t = ticks[i]; if (!t.label) continue; var info = surface.getTextInfo(layer, t.label, font, null, maxWidth); labelWidth = Math.max(labelWidth, info.width); labelHeight = Math.max(labelHeight, info.height); } axis.labelWidth = opts.labelWidth || labelWidth; axis.labelHeight = opts.labelHeight || labelHeight; } function allocateAxisBoxFirstPhase(axis) { // find the bounding box of the axis by looking at label // widths/heights and ticks, make room by diminishing the // plotOffset; this first phase only looks at one // dimension per axis, the other dimension depends on the // other axes so will have to wait var lw = axis.labelWidth, lh = axis.labelHeight, pos = axis.options.position, isXAxis = axis.direction === "x", tickLength = axis.options.tickLength, axisMargin = options.grid.axisMargin, padding = options.grid.labelMargin, innermost = true, outermost = true, first = true, found = false; // Determine the axis's position in its direction and on its side $.each(isXAxis ? xaxes : yaxes, function(i, a) { if (a && a.reserveSpace) { if (a === axis) { found = true; } else if (a.options.position === pos) { if (found) { outermost = false; } else { innermost = false; } } if (!found) { first = false; } } }); // The outermost axis on each side has no margin if (outermost) { axisMargin = 0; } // The ticks for the first axis in each direction stretch across if (tickLength == null) { tickLength = first ? "full" : 5; } if (!isNaN(+tickLength)) padding += +tickLength; if (isXAxis) { lh += padding; if (pos == "bottom") { plotOffset.bottom += lh + axisMargin; axis.box = { top: surface.height - plotOffset.bottom, height: lh }; } else { axis.box = { top: plotOffset.top + axisMargin, height: lh }; plotOffset.top += lh + axisMargin; } } else { lw += padding; if (pos == "left") { axis.box = { left: plotOffset.left + axisMargin, width: lw }; plotOffset.left += lw + axisMargin; } else { plotOffset.right += lw + axisMargin; axis.box = { left: surface.width - plotOffset.right, width: lw }; } } // save for future reference axis.position = pos; axis.tickLength = tickLength; axis.box.padding = padding; axis.innermost = innermost; } function allocateAxisBoxSecondPhase(axis) { // now that all axis boxes have been placed in one // dimension, we can set the remaining dimension coordinates if (axis.direction == "x") { axis.box.left = plotOffset.left - axis.labelWidth / 2; axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth; } else { axis.box.top = plotOffset.top - axis.labelHeight / 2; axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight; } } function adjustLayoutForThingsStickingOut() { // possibly adjust plot offset to ensure everything stays // inside the canvas and isn't clipped off var minMargin = options.grid.minBorderMargin, axis, i; // check stuff from the plot (FIXME: this should just read // a value from the series, otherwise it's impossible to // customize) if (minMargin == null) { minMargin = 0; for (i = 0; i < series.length; ++i) minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth/2)); } var margins = { left: minMargin, right: minMargin, top: minMargin, bottom: minMargin }; // check axis labels, note we don't check the actual // labels but instead use the overall width/height to not // jump as much around with replots $.each(allAxes(), function (_, axis) { if (axis.reserveSpace && axis.ticks && axis.ticks.length) { var lastTick = axis.ticks[axis.ticks.length - 1]; if (axis.direction === "x") { margins.left = Math.max(margins.left, axis.labelWidth / 2); if (lastTick.v <= axis.max) { margins.right = Math.max(margins.right, axis.labelWidth / 2); } } else { margins.bottom = Math.max(margins.bottom, axis.labelHeight / 2); if (lastTick.v <= axis.max) { margins.top = Math.max(margins.top, axis.labelHeight / 2); } } } }); plotOffset.left = Math.ceil(Math.max(margins.left, plotOffset.left)); plotOffset.right = Math.ceil(Math.max(margins.right, plotOffset.right)); plotOffset.top = Math.ceil(Math.max(margins.top, plotOffset.top)); plotOffset.bottom = Math.ceil(Math.max(margins.bottom, plotOffset.bottom)); } function setupGrid() { var i, axes = allAxes(), showGrid = options.grid.show; // Initialize the plot's offset from the edge of the canvas for (var a in plotOffset) { var margin = options.grid.margin || 0; plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0; } executeHooks(hooks.processOffset, [plotOffset]); // If the grid is visible, add its border width to the offset for (var a in plotOffset) { if(typeof(options.grid.borderWidth) == "object") { plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0; } else { plotOffset[a] += showGrid ? options.grid.borderWidth : 0; } } // init axes $.each(axes, function (_, axis) { axis.show = axis.options.show; if (axis.show == null) axis.show = axis.used; // by default an axis is visible if it's got data axis.reserveSpace = axis.show || axis.options.reserveSpace; setRange(axis); }); if (showGrid) { var allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; }); $.each(allocatedAxes, function (_, axis) { // make the ticks setupTickGeneration(axis); setTicks(axis); snapRangeToTicks(axis, axis.ticks); // find labelWidth/Height for axis measureTickLabels(axis); }); // with all dimensions calculated, we can compute the // axis bounding boxes, start from the outside // (reverse order) for (i = allocatedAxes.length - 1; i >= 0; --i) allocateAxisBoxFirstPhase(allocatedAxes[i]); // make sure we've got enough space for things that // might stick out adjustLayoutForThingsStickingOut(); $.each(allocatedAxes, function (_, axis) { allocateAxisBoxSecondPhase(axis); }); } plotWidth = surface.width - plotOffset.left - plotOffset.right; plotHeight = surface.height - plotOffset.bottom - plotOffset.top; // now we got the proper plot dimensions, we can compute the scaling $.each(axes, function (_, axis) { setTransformationHelpers(axis); }); if (showGrid) { drawAxisLabels(); } insertLegend(); } function setRange(axis) { var opts = axis.options, min = +(opts.min != null ? opts.min : axis.datamin), max = +(opts.max != null ? opts.max : axis.datamax), delta = max - min; if (delta == 0.0) { // degenerate case var widen = max == 0 ? 1 : 0.01; if (opts.min == null) min -= widen; // always widen max if we couldn't widen min to ensure we // don't fall into min == max which doesn't work if (opts.max == null || opts.min != null) max += widen; } else { // consider autoscaling var margin = opts.autoscaleMargin; if (margin != null) { if (opts.min == null) { min -= delta * margin; // make sure we don't go below zero if all values // are positive if (min < 0 && axis.datamin != null && axis.datamin >= 0) min = 0; } if (opts.max == null) { max += delta * margin; if (max > 0 && axis.datamax != null && axis.datamax <= 0) max = 0; } } } axis.min = min; axis.max = max; } function setupTickGeneration(axis) { var opts = axis.options; // estimate number of ticks var noTicks; if (typeof opts.ticks == "number" && opts.ticks > 0) noTicks = opts.ticks; else // heuristic based on the model a*sqrt(x) fitted to // some data points that seemed reasonable noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height); var delta = (axis.max - axis.min) / noTicks, dec = -Math.floor(Math.log(delta) / Math.LN10), maxDec = opts.tickDecimals; if (maxDec != null && dec > maxDec) { dec = maxDec; } var magn = Math.pow(10, -dec), norm = delta / magn, // norm is between 1.0 and 10.0 size; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; // special case for 2.5, requires an extra decimal if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) { size = 2.5; ++dec; } } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; if (opts.minTickSize != null && size < opts.minTickSize) { size = opts.minTickSize; } axis.delta = delta; axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec); axis.tickSize = opts.tickSize || size; // Time mode was moved to a plug-in in 0.8, but since so many people use this // we'll add an especially friendly make sure they remembered to include it. if (opts.mode == "time" && !axis.tickGenerator) { throw new Error("Time mode requires the flot.time plugin."); } // Flot supports base-10 axes; any other mode else is handled by a plug-in, // like flot.time.js. if (!axis.tickGenerator) { axis.tickGenerator = function (axis) { var ticks = [], start = floorInBase(axis.min, axis.tickSize), i = 0, v = Number.NaN, prev; do { prev = v; v = start + i * axis.tickSize; ticks.push(v); ++i; } while (v < axis.max && v != prev); return ticks; }; axis.tickFormatter = function (value, axis) { var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1; var formatted = "" + Math.round(value * factor) / factor; // If tickDecimals was specified, ensure that we have exactly that // much precision; otherwise default to the value's own precision. if (axis.tickDecimals != null) { var decimal = formatted.indexOf("."); var precision = decimal == -1 ? 0 : formatted.length - decimal - 1; if (precision < axis.tickDecimals) { return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision); } } return formatted; }; } if ($.isFunction(opts.tickFormatter)) axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); }; if (opts.alignTicksWithAxis != null) { var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1]; if (otherAxis && otherAxis.used && otherAxis != axis) { // consider snapping min/max to outermost nice ticks var niceTicks = axis.tickGenerator(axis); if (niceTicks.length > 0) { if (opts.min == null) axis.min = Math.min(axis.min, niceTicks[0]); if (opts.max == null && niceTicks.length > 1) axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]); } axis.tickGenerator = function (axis) { // copy ticks, scaled to this axis var ticks = [], v, i; for (i = 0; i < otherAxis.ticks.length; ++i) { v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min); v = axis.min + v * (axis.max - axis.min); ticks.push(v); } return ticks; }; // we might need an extra decimal since forced // ticks don't necessarily fit naturally if (!axis.mode && opts.tickDecimals == null) { var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1), ts = axis.tickGenerator(axis); // only proceed if the tick interval rounded // with an extra decimal doesn't give us a // zero at end if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec)))) axis.tickDecimals = extraDec; } } } } function setTicks(axis) { var oticks = axis.options.ticks, ticks = []; if (oticks == null || (typeof oticks == "number" && oticks > 0)) ticks = axis.tickGenerator(axis); else if (oticks) { if ($.isFunction(oticks)) // generate the ticks ticks = oticks(axis); else ticks = oticks; } // clean up/labelify the supplied ticks, copy them over var i, v; axis.ticks = []; for (i = 0; i < ticks.length; ++i) { var label = null; var t = ticks[i]; if (typeof t == "object") { v = +t[0]; if (t.length > 1) label = t[1]; } else v = +t; if (label == null) label = axis.tickFormatter(v, axis); if (!isNaN(v)) axis.ticks.push({ v: v, label: label }); } } function snapRangeToTicks(axis, ticks) { if (axis.options.autoscaleMargin && ticks.length > 0) { // snap to ticks if (axis.options.min == null) axis.min = Math.min(axis.min, ticks[0].v); if (axis.options.max == null && ticks.length > 1) axis.max = Math.max(axis.max, ticks[ticks.length - 1].v); } } function draw() { surface.clear(); executeHooks(hooks.drawBackground, [ctx]); var grid = options.grid; // draw background, if any if (grid.show && grid.backgroundColor) drawBackground(); if (grid.show && !grid.aboveData) { drawGrid(); } for (var i = 0; i < series.length; ++i) { executeHooks(hooks.drawSeries, [ctx, series[i]]); drawSeries(series[i]); } executeHooks(hooks.draw, [ctx]); if (grid.show && grid.aboveData) { drawGrid(); } surface.render(); // A draw implies that either the axes or data have changed, so we // should probably update the overlay highlights as well. triggerRedrawOverlay(); } function extractRange(ranges, coord) { var axis, from, to, key, axes = allAxes(); for (var i = 0; i < axes.length; ++i) { axis = axes[i]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? xaxes[0] : yaxes[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; } function drawBackground() { ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)"); ctx.fillRect(0, 0, plotWidth, plotHeight); ctx.restore(); } function drawGrid() { var i, axes, bw, bc; ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // draw markings var markings = options.grid.markings; if (markings) { if ($.isFunction(markings)) { axes = plot.getAxes(); // xmin etc. is backwards compatibility, to be // removed in the future axes.xmin = axes.xaxis.min; axes.xmax = axes.xaxis.max; axes.ymin = axes.yaxis.min; axes.ymax = axes.yaxis.max; markings = markings(axes); } for (i = 0; i < markings.length; ++i) { var m = markings[i], xrange = extractRange(m, "x"), yrange = extractRange(m, "y"); // fill in missing if (xrange.from == null) xrange.from = xrange.axis.min; if (xrange.to == null) xrange.to = xrange.axis.max; if (yrange.from == null) yrange.from = yrange.axis.min; if (yrange.to == null) yrange.to = yrange.axis.max; // clip if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max || yrange.to < yrange.axis.min || yrange.from > yrange.axis.max) continue; xrange.from = Math.max(xrange.from, xrange.axis.min); xrange.to = Math.min(xrange.to, xrange.axis.max); yrange.from = Math.max(yrange.from, yrange.axis.min); yrange.to = Math.min(yrange.to, yrange.axis.max); if (xrange.from == xrange.to && yrange.from == yrange.to) continue; // then draw xrange.from = xrange.axis.p2c(xrange.from); xrange.to = xrange.axis.p2c(xrange.to); yrange.from = yrange.axis.p2c(yrange.from); yrange.to = yrange.axis.p2c(yrange.to); if (xrange.from == xrange.to || yrange.from == yrange.to) { // draw line ctx.beginPath(); ctx.strokeStyle = m.color || options.grid.markingsColor; ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth; ctx.moveTo(xrange.from, yrange.from); ctx.lineTo(xrange.to, yrange.to); ctx.stroke(); } else { // fill area ctx.fillStyle = m.color || options.grid.markingsColor; ctx.fillRect(xrange.from, yrange.to, xrange.to - xrange.from, yrange.from - yrange.to); } } } // draw the ticks axes = allAxes(); bw = options.grid.borderWidth; for (var j = 0; j < axes.length; ++j) { var axis = axes[j], box = axis.box, t = axis.tickLength, x, y, xoff, yoff; if (!axis.show || axis.ticks.length == 0) continue; ctx.lineWidth = 1; // find the edges if (axis.direction == "x") { x = 0; if (t == "full") y = (axis.position == "top" ? 0 : plotHeight); else y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0); } else { y = 0; if (t == "full") x = (axis.position == "left" ? 0 : plotWidth); else x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0); } // draw tick bar if (!axis.innermost) { ctx.strokeStyle = axis.options.color; ctx.beginPath(); xoff = yoff = 0; if (axis.direction == "x") xoff = plotWidth + 1; else yoff = plotHeight + 1; if (ctx.lineWidth == 1) { if (axis.direction == "x") { y = Math.floor(y) + 0.5; } else { x = Math.floor(x) + 0.5; } } ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); ctx.stroke(); } // draw ticks ctx.strokeStyle = axis.options.tickColor; ctx.beginPath(); for (i = 0; i < axis.ticks.length; ++i) { var v = axis.ticks[i].v; xoff = yoff = 0; if (isNaN(v) || v < axis.min || v > axis.max // skip those lying on the axes if we got a border || (t == "full" && ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0) && (v == axis.min || v == axis.max))) continue; if (axis.direction == "x") { x = axis.p2c(v); yoff = t == "full" ? -plotHeight : t; if (axis.position == "top") yoff = -yoff; } else { y = axis.p2c(v); xoff = t == "full" ? -plotWidth : t; if (axis.position == "left") xoff = -xoff; } if (ctx.lineWidth == 1) { if (axis.direction == "x") x = Math.floor(x) + 0.5; else y = Math.floor(y) + 0.5; } ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); } ctx.stroke(); } // draw border if (bw) { // If either borderWidth or borderColor is an object, then draw the border // line by line instead of as one rectangle bc = options.grid.borderColor; if(typeof bw == "object" || typeof bc == "object") { if (typeof bw !== "object") { bw = {top: bw, right: bw, bottom: bw, left: bw}; } if (typeof bc !== "object") { bc = {top: bc, right: bc, bottom: bc, left: bc}; } if (bw.top > 0) { ctx.strokeStyle = bc.top; ctx.lineWidth = bw.top; ctx.beginPath(); ctx.moveTo(0 - bw.left, 0 - bw.top/2); ctx.lineTo(plotWidth, 0 - bw.top/2); ctx.stroke(); } if (bw.right > 0) { ctx.strokeStyle = bc.right; ctx.lineWidth = bw.right; ctx.beginPath(); ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top); ctx.lineTo(plotWidth + bw.right / 2, plotHeight); ctx.stroke(); } if (bw.bottom > 0) { ctx.strokeStyle = bc.bottom; ctx.lineWidth = bw.bottom; ctx.beginPath(); ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2); ctx.lineTo(0, plotHeight + bw.bottom / 2); ctx.stroke(); } if (bw.left > 0) { ctx.strokeStyle = bc.left; ctx.lineWidth = bw.left; ctx.beginPath(); ctx.moveTo(0 - bw.left/2, plotHeight + bw.bottom); ctx.lineTo(0- bw.left/2, 0); ctx.stroke(); } } else { ctx.lineWidth = bw; ctx.strokeStyle = options.grid.borderColor; ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw); } } ctx.restore(); } function drawAxisLabels() { $.each(allAxes(), function (_, axis) { var box = axis.box, legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis", layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles, font = axis.options.font || "flot-tick-label tickLabel", tick, x, y, halign, valign; // Remove text before checking for axis.show and ticks.length; // otherwise plugins, like flot-tickrotor, that draw their own // tick labels will end up with both theirs and the defaults. surface.removeText(layer); if (!axis.show || axis.ticks.length == 0) return; for (var i = 0; i < axis.ticks.length; ++i) { tick = axis.ticks[i]; if (!tick.label || tick.v < axis.min || tick.v > axis.max) continue; if (axis.direction == "x") { halign = "center"; x = plotOffset.left + axis.p2c(tick.v); if (axis.position == "bottom") { y = box.top + box.padding; } else { y = box.top + box.height - box.padding; valign = "bottom"; } } else { valign = "middle"; y = plotOffset.top + axis.p2c(tick.v); if (axis.position == "left") { x = box.left + box.width - box.padding; halign = "right"; } else { x = box.left + box.padding; } } surface.addText(layer, x, y, tick.label, font, null, null, halign, valign); } }); } function drawSeries(series) { if (series.lines.show) drawSeriesLines(series); if (series.bars.show) drawSeriesBars(series); if (series.points.show) drawSeriesPoints(series); } function drawSeriesLines(series) { function plotLine(datapoints, xoffset, yoffset, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, prevx = null, prevy = null; ctx.beginPath(); for (var i = ps; i < points.length; i += ps) { var x1 = points[i - ps], y1 = points[i - ps + 1], x2 = points[i], y2 = points[i + 1]; if (x1 == null || x2 == null) continue; // clip with ymin if (y1 <= y2 && y1 < axisy.min) { if (y2 < axisy.min) continue; // line segment is outside // compute new intersection point x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min) { if (y1 < axisy.min) continue; x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max) { if (y2 > axisy.max) continue; x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max) { if (y1 > axisy.max) continue; x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (x1 != prevx || y1 != prevy) ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset); prevx = x2; prevy = y2; ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset); } ctx.stroke(); } function plotLineArea(datapoints, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, bottom = Math.min(Math.max(0, axisy.min), axisy.max), i = 0, top, areaOpen = false, ypos = 1, segmentStart = 0, segmentEnd = 0; // we process each segment in two turns, first forward // direction to sketch out top, then once we hit the // end we go backwards to sketch the bottom while (true) { if (ps > 0 && i > points.length + ps) break; i += ps; // ps is negative if going backwards var x1 = points[i - ps], y1 = points[i - ps + ypos], x2 = points[i], y2 = points[i + ypos]; if (areaOpen) { if (ps > 0 && x1 != null && x2 == null) { // at turning point segmentEnd = i; ps = -ps; ypos = 2; continue; } if (ps < 0 && i == segmentStart + ps) { // done with the reverse sweep ctx.fill(); areaOpen = false; ps = -ps; ypos = 1; i = segmentStart = segmentEnd + ps; continue; } } if (x1 == null || x2 == null) continue; // clip x values // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (!areaOpen) { // open area ctx.beginPath(); ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom)); areaOpen = true; } // now first check the case where both is outside if (y1 >= axisy.max && y2 >= axisy.max) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max)); continue; } else if (y1 <= axisy.min && y2 <= axisy.min) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min)); continue; } // else it's a bit more complicated, there might // be a flat maxed out rectangle first, then a // triangular cutout or reverse; to find these // keep track of the current x values var x1old = x1, x2old = x2; // clip the y values, without shortcutting, we // go through all cases in turn // clip with ymin if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) { x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) { x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) { x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) { x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // if the x value was changed we got a rectangle // to fill if (x1 != x1old) { ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1)); // it goes to (x1, y1), but we fill that below } // fill triangular section, this sometimes result // in redundant points if (x1, y1) hasn't changed // from previous line to, but we just ignore that ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); // fill the other rectangle if it's there if (x2 != x2old) { ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2)); } } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.lineJoin = "round"; var lw = series.lines.lineWidth, sw = series.shadowSize; // FIXME: consider another form of shadow when filling is turned on if (lw > 0 && sw > 0) { // draw shadow as a thick and thin line with transparency ctx.lineWidth = sw; ctx.strokeStyle = "rgba(0,0,0,0.1)"; // position shadow at angle from the mid of line var angle = Math.PI/18; plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis); ctx.lineWidth = sw/2; plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight); if (fillStyle) { ctx.fillStyle = fillStyle; plotLineArea(series.datapoints, series.xaxis, series.yaxis); } if (lw > 0) plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis); ctx.restore(); } function drawSeriesPoints(series) { function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { var x = points[i], y = points[i + 1]; if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) continue; ctx.beginPath(); x = axisx.p2c(x); y = axisy.p2c(y) + offset; if (symbol == "circle") ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false); else symbol(ctx, x, y, radius, shadow); ctx.closePath(); if (fillStyle) { ctx.fillStyle = fillStyle; ctx.fill(); } ctx.stroke(); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); var lw = series.points.lineWidth, sw = series.shadowSize, radius = series.points.radius, symbol = series.points.symbol; // If the user sets the line width to 0, we change it to a very // small value. A line width of 0 seems to force the default of 1. // Doing the conditional here allows the shadow setting to still be // optional even with a lineWidth of 0. if( lw == 0 ) lw = 0.0001; if (lw > 0 && sw > 0) { // draw shadow in two steps var w = sw / 2; ctx.lineWidth = w; ctx.strokeStyle = "rgba(0,0,0,0.1)"; plotPoints(series.datapoints, radius, null, w + w/2, true, series.xaxis, series.yaxis, symbol); ctx.strokeStyle = "rgba(0,0,0,0.2)"; plotPoints(series.datapoints, radius, null, w/2, true, series.xaxis, series.yaxis, symbol); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; plotPoints(series.datapoints, radius, getFillStyle(series.points, series.color), 0, false, series.xaxis, series.yaxis, symbol); ctx.restore(); } function drawBar(x, y, b, barLeft, barRight, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) { var left, right, bottom, top, drawLeft, drawRight, drawTop, drawBottom, tmp; // in horizontal mode, we start the bar from the left // instead of from the bottom so it appears to be // horizontal rather than vertical if (horizontal) { drawBottom = drawRight = drawTop = true; drawLeft = false; left = b; right = x; top = y + barLeft; bottom = y + barRight; // account for negative bars if (right < left) { tmp = right; right = left; left = tmp; drawLeft = true; drawRight = false; } } else { drawLeft = drawRight = drawTop = true; drawBottom = false; left = x + barLeft; right = x + barRight; bottom = b; top = y; // account for negative bars if (top < bottom) { tmp = top; top = bottom; bottom = tmp; drawBottom = true; drawTop = false; } } // clip if (right < axisx.min || left > axisx.max || top < axisy.min || bottom > axisy.max) return; if (left < axisx.min) { left = axisx.min; drawLeft = false; } if (right > axisx.max) { right = axisx.max; drawRight = false; } if (bottom < axisy.min) { bottom = axisy.min; drawBottom = false; } if (top > axisy.max) { top = axisy.max; drawTop = false; } left = axisx.p2c(left); bottom = axisy.p2c(bottom); right = axisx.p2c(right); top = axisy.p2c(top); // fill the bar if (fillStyleCallback) { c.fillStyle = fillStyleCallback(bottom, top); c.fillRect(left, top, right - left, bottom - top) } // draw outline if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) { c.beginPath(); // FIXME: inline moveTo is buggy with excanvas c.moveTo(left, bottom); if (drawLeft) c.lineTo(left, top); else c.moveTo(left, top); if (drawTop) c.lineTo(right, top); else c.moveTo(right, top); if (drawRight) c.lineTo(right, bottom); else c.moveTo(right, bottom); if (drawBottom) c.lineTo(left, bottom); else c.moveTo(left, bottom); c.stroke(); } } function drawSeriesBars(series) { function plotBars(datapoints, barLeft, barRight, fillStyleCallback, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { if (points[i] == null) continue; drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // FIXME: figure out a way to add shadows (for instance along the right edge) ctx.lineWidth = series.bars.lineWidth; ctx.strokeStyle = series.color; var barLeft; switch (series.bars.align) { case "left": barLeft = 0; break; case "right": barLeft = -series.bars.barWidth; break; default: barLeft = -series.bars.barWidth / 2; } var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null; plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, fillStyleCallback, series.xaxis, series.yaxis); ctx.restore(); } function getFillStyle(filloptions, seriesColor, bottom, top) { var fill = filloptions.fill; if (!fill) return null; if (filloptions.fillColor) return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor); var c = $.color.parse(seriesColor); c.a = typeof fill == "number" ? fill : 0.4; c.normalize(); return c.toString(); } function insertLegend() { if (options.legend.container != null) { $(options.legend.container).html(""); } else { placeholder.find(".legend").remove(); } if (!options.legend.show) { return; } var fragments = [], entries = [], rowStarted = false, lf = options.legend.labelFormatter, s, label; // Build a list of legend entries, with each having a label and a color for (var i = 0; i < series.length; ++i) { s = series[i]; if (s.label) { label = lf ? lf(s.label, s) : s.label; if (label) { entries.push({ label: label, color: s.color }); } } } // Sort the legend using either the default or a custom comparator if (options.legend.sorted) { if ($.isFunction(options.legend.sorted)) { entries.sort(options.legend.sorted); } else if (options.legend.sorted == "reverse") { entries.reverse(); } else { var ascending = options.legend.sorted != "descending"; entries.sort(function(a, b) { return a.label == b.label ? 0 : ( (a.label < b.label) != ascending ? 1 : -1 // Logical XOR ); }); } } // Generate markup for the list of entries, in their final order for (var i = 0; i < entries.length; ++i) { var entry = entries[i]; if (i % options.legend.noColumns == 0) { if (rowStarted) fragments.push('</tr>'); fragments.push('<tr>'); rowStarted = true; } fragments.push( '<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + entry.color + ';overflow:hidden"></div></div></td>' + '<td class="legendLabel">' + entry.label + '</td>' ); } if (rowStarted) fragments.push('</tr>'); if (fragments.length == 0) return; var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>'; if (options.legend.container != null) $(options.legend.container).html(table); else { var pos = "", p = options.legend.position, m = options.legend.margin; if (m[0] == null) m = [m, m]; if (p.charAt(0) == "n") pos += 'top:' + (m[1] + plotOffset.top) + 'px;'; else if (p.charAt(0) == "s") pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;'; if (p.charAt(1) == "e") pos += 'right:' + (m[0] + plotOffset.right) + 'px;'; else if (p.charAt(1) == "w") pos += 'left:' + (m[0] + plotOffset.left) + 'px;'; var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder); if (options.legend.backgroundOpacity != 0.0) { // put in the transparent background // separately to avoid blended labels and // label boxes var c = options.legend.backgroundColor; if (c == null) { c = options.grid.backgroundColor; if (c && typeof c == "string") c = $.color.parse(c); else c = $.color.extract(legend, 'background-color'); c.a = 1; c = c.toString(); } var div = legend.children(); $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity); } } } // interactive features var highlights = [], redrawTimeout = null; // returns the data item the mouse is over, or null if none is found function findNearbyItem(mouseX, mouseY, seriesFilter) { var maxDistance = options.grid.mouseActiveRadius, smallestDistance = maxDistance * maxDistance + 1, item = null, foundPoint = false, i, j, ps; for (i = series.length - 1; i >= 0; --i) { if (!seriesFilter(series[i])) continue; var s = series[i], axisx = s.xaxis, axisy = s.yaxis, points = s.datapoints.points, mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster my = axisy.c2p(mouseY), maxx = maxDistance / axisx.scale, maxy = maxDistance / axisy.scale; ps = s.datapoints.pointsize; // with inverse transforms, we can't use the maxx/maxy // optimization, sadly if (axisx.options.inverseTransform) maxx = Number.MAX_VALUE; if (axisy.options.inverseTransform) maxy = Number.MAX_VALUE; if (s.lines.show || s.points.show) { for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1]; if (x == null) continue; // For points and lines, the cursor must be within a // certain distance to the data point if (x - mx > maxx || x - mx < -maxx || y - my > maxy || y - my < -maxy) continue; // We have to calculate distances in pixels, not in // data units, because the scales of the axes may be different var dx = Math.abs(axisx.p2c(x) - mouseX), dy = Math.abs(axisy.p2c(y) - mouseY), dist = dx * dx + dy * dy; // we save the sqrt // use <= to ensure last point takes precedence // (last generally means on top of) if (dist < smallestDistance) { smallestDistance = dist; item = [i, j / ps]; } } } if (s.bars.show && !item) { // no other point can be nearby var barLeft, barRight; switch (s.bars.align) { case "left": barLeft = 0; break; case "right": barLeft = -s.bars.barWidth; break; default: barLeft = -s.bars.barWidth / 2; } barRight = barLeft + s.bars.barWidth; for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1], b = points[j + 2]; if (x == null) continue; // for a bar graph, the cursor must be inside the bar if (series[i].bars.horizontal ? (mx <= Math.max(b, x) && mx >= Math.min(b, x) && my >= y + barLeft && my <= y + barRight) : (mx >= x + barLeft && mx <= x + barRight && my >= Math.min(b, y) && my <= Math.max(b, y))) item = [i, j / ps]; } } } if (item) { i = item[0]; j = item[1]; ps = series[i].datapoints.pointsize; return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps), dataIndex: j, series: series[i], seriesIndex: i }; } return null; } function onMouseMove(e) { if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) { return s["hoverable"] != false; }); } function onMouseLeave(e) { if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) { return false; }); } function onClick(e) { triggerClickHoverEvent("plotclick", e, function (s) { return s["clickable"] != false; }); } // trigger click or hover event (they send the same parameters // so we share their code) function triggerClickHoverEvent(eventname, event, seriesFilter) { var offset = eventHolder.offset(), canvasX = event.pageX - offset.left - plotOffset.left, canvasY = event.pageY - offset.top - plotOffset.top, pos = canvasToAxisCoords({ left: canvasX, top: canvasY }); pos.pageX = event.pageX; pos.pageY = event.pageY; var item = findNearbyItem(canvasX, canvasY, seriesFilter); if (item) { // fill in mouse pos for any listeners out there item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10); item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10); } if (options.grid.autoHighlight) { // clear auto-highlights for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.auto == eventname && !(item && h.series == item.series && h.point[0] == item.datapoint[0] && h.point[1] == item.datapoint[1])) unhighlight(h.series, h.point); } if (item) highlight(item.series, item.datapoint, eventname); } placeholder.trigger(eventname, [ pos, item ]); } function triggerRedrawOverlay() { var t = options.interaction.redrawOverlayInterval; if (t == -1) { // skip event queue drawOverlay(); return; } if (!redrawTimeout) redrawTimeout = setTimeout(drawOverlay, t); } function drawOverlay() { redrawTimeout = null; // draw highlights octx.save(); overlay.clear(); octx.translate(plotOffset.left, plotOffset.top); var i, hi; for (i = 0; i < highlights.length; ++i) { hi = highlights[i]; if (hi.series.bars.show) drawBarHighlight(hi.series, hi.point); else drawPointHighlight(hi.series, hi.point); } octx.restore(); executeHooks(hooks.drawOverlay, [octx]); } function highlight(s, point, auto) { if (typeof s == "number") s = series[s]; if (typeof point == "number") { var ps = s.datapoints.pointsize; point = s.datapoints.points.slice(ps * point, ps * (point + 1)); } var i = indexOfHighlight(s, point); if (i == -1) { highlights.push({ series: s, point: point, auto: auto }); triggerRedrawOverlay(); } else if (!auto) highlights[i].auto = false; } function unhighlight(s, point) { if (s == null && point == null) { highlights = []; triggerRedrawOverlay(); return; } if (typeof s == "number") s = series[s]; if (typeof point == "number") { var ps = s.datapoints.pointsize; point = s.datapoints.points.slice(ps * point, ps * (point + 1)); } var i = indexOfHighlight(s, point); if (i != -1) { highlights.splice(i, 1); triggerRedrawOverlay(); } } function indexOfHighlight(s, p) { for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.series == s && h.point[0] == p[0] && h.point[1] == p[1]) return i; } return -1; } function drawPointHighlight(series, point) { var x = point[0], y = point[1], axisx = series.xaxis, axisy = series.yaxis, highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(); if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) return; var pointRadius = series.points.radius + series.points.lineWidth / 2; octx.lineWidth = pointRadius; octx.strokeStyle = highlightColor; var radius = 1.5 * pointRadius; x = axisx.p2c(x); y = axisy.p2c(y); octx.beginPath(); if (series.points.symbol == "circle") octx.arc(x, y, radius, 0, 2 * Math.PI, false); else series.points.symbol(octx, x, y, radius, false); octx.closePath(); octx.stroke(); } function drawBarHighlight(series, point) { var highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(), fillStyle = highlightColor, barLeft; switch (series.bars.align) { case "left": barLeft = 0; break; case "right": barLeft = -series.bars.barWidth; break; default: barLeft = -series.bars.barWidth / 2; } octx.lineWidth = series.bars.lineWidth; octx.strokeStyle = highlightColor; drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth); } function getColorOrGradient(spec, bottom, top, defaultColor) { if (typeof spec == "string") return spec; else { // assume this is a gradient spec; IE currently only // supports a simple vertical gradient properly, so that's // what we support too var gradient = ctx.createLinearGradient(0, top, 0, bottom); for (var i = 0, l = spec.colors.length; i < l; ++i) { var c = spec.colors[i]; if (typeof c != "string") { var co = $.color.parse(defaultColor); if (c.brightness != null) co = co.scale('rgb', c.brightness); if (c.opacity != null) co.a *= c.opacity; c = co.toString(); } gradient.addColorStop(i / (l - 1), c); } return gradient; } } } // Add the plot function to the top level of the jQuery object $.plot = function(placeholder, data, options) { //var t0 = new Date(); var plot = new Plot($(placeholder), data, options, $.plot.plugins); //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime())); return plot; }; $.plot.version = "0.8.2"; $.plot.plugins = []; // Also add the plot function as a chainable property $.fn.plot = function(data, options) { return this.each(function() { $.plot(this, data, options); }); }; // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } })(jQuery);
JavaScript
/* Flot plugin for showing crosshairs when the mouse hovers over the plot. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The plugin supports these options: crosshair: { mode: null or "x" or "y" or "xy" color: color lineWidth: number } Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical crosshair that lets you trace the values on the x axis, "y" enables a horizontal crosshair and "xy" enables them both. "color" is the color of the crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of the drawn lines (default is 1). The plugin also adds four public methods: - setCrosshair( pos ) Set the position of the crosshair. Note that this is cleared if the user moves the mouse. "pos" is in coordinates of the plot and should be on the form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple axes), which is coincidentally the same format as what you get from a "plothover" event. If "pos" is null, the crosshair is cleared. - clearCrosshair() Clear the crosshair. - lockCrosshair(pos) Cause the crosshair to lock to the current location, no longer updating if the user moves the mouse. Optionally supply a position (passed on to setCrosshair()) to move it to. Example usage: var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } }; $("#graph").bind( "plothover", function ( evt, position, item ) { if ( item ) { // Lock the crosshair to the data point being hovered myFlot.lockCrosshair({ x: item.datapoint[ 0 ], y: item.datapoint[ 1 ] }); } else { // Return normal crosshair operation myFlot.unlockCrosshair(); } }); - unlockCrosshair() Free the crosshair to move again after locking it. */ (function ($) { var options = { crosshair: { mode: null, // one of null, "x", "y" or "xy", color: "rgba(170, 0, 0, 0.80)", lineWidth: 1 } }; function init(plot) { // position of crosshair in pixels var crosshair = { x: -1, y: -1, locked: false }; plot.setCrosshair = function setCrosshair(pos) { if (!pos) crosshair.x = -1; else { var o = plot.p2c(pos); crosshair.x = Math.max(0, Math.min(o.left, plot.width())); crosshair.y = Math.max(0, Math.min(o.top, plot.height())); } plot.triggerRedrawOverlay(); }; plot.clearCrosshair = plot.setCrosshair; // passes null for pos plot.lockCrosshair = function lockCrosshair(pos) { if (pos) plot.setCrosshair(pos); crosshair.locked = true; }; plot.unlockCrosshair = function unlockCrosshair() { crosshair.locked = false; }; function onMouseOut(e) { if (crosshair.locked) return; if (crosshair.x != -1) { crosshair.x = -1; plot.triggerRedrawOverlay(); } } function onMouseMove(e) { if (crosshair.locked) return; if (plot.getSelection && plot.getSelection()) { crosshair.x = -1; // hide the crosshair while selecting return; } var offset = plot.offset(); crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width())); crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height())); plot.triggerRedrawOverlay(); } plot.hooks.bindEvents.push(function (plot, eventHolder) { if (!plot.getOptions().crosshair.mode) return; eventHolder.mouseout(onMouseOut); eventHolder.mousemove(onMouseMove); }); plot.hooks.drawOverlay.push(function (plot, ctx) { var c = plot.getOptions().crosshair; if (!c.mode) return; var plotOffset = plot.getPlotOffset(); ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); if (crosshair.x != -1) { var adj = plot.getOptions().crosshair.lineWidth % 2 === 0 ? 0 : 0.5; ctx.strokeStyle = c.color; ctx.lineWidth = c.lineWidth; ctx.lineJoin = "round"; ctx.beginPath(); if (c.mode.indexOf("x") != -1) { var drawX = Math.round(crosshair.x) + adj; ctx.moveTo(drawX, 0); ctx.lineTo(drawX, plot.height()); } if (c.mode.indexOf("y") != -1) { var drawY = Math.round(crosshair.y) + adj; ctx.moveTo(0, drawY); ctx.lineTo(plot.width(), drawY); } ctx.stroke(); } ctx.restore(); }); plot.hooks.shutdown.push(function (plot, eventHolder) { eventHolder.unbind("mouseout", onMouseOut); eventHolder.unbind("mousemove", onMouseMove); }); } $.plot.plugins.push({ init: init, options: options, name: 'crosshair', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for drawing all elements of a plot on the canvas. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. Flot normally produces certain elements, like axis labels and the legend, using HTML elements. This permits greater interactivity and customization, and often looks better, due to cross-browser canvas text inconsistencies and limitations. It can also be desirable to render the plot entirely in canvas, particularly if the goal is to save it as an image, or if Flot is being used in a context where the HTML DOM does not exist, as is the case within Node.js. This plugin switches out Flot's standard drawing operations for canvas-only replacements. Currently the plugin supports only axis labels, but it will eventually allow every element of the plot to be rendered directly to canvas. The plugin supports these options: { canvas: boolean } The "canvas" option controls whether full canvas drawing is enabled, making it possible to toggle on and off. This is useful when a plot uses HTML text in the browser, but needs to redraw with canvas text when exporting as an image. */ (function($) { var options = { canvas: true }; var render, getTextInfo, addText; // Cache the prototype hasOwnProperty for faster access var hasOwnProperty = Object.prototype.hasOwnProperty; function init(plot, classes) { var Canvas = classes.Canvas; // We only want to replace the functions once; the second time around // we would just get our new function back. This whole replacing of // prototype functions is a disaster, and needs to be changed ASAP. if (render == null) { getTextInfo = Canvas.prototype.getTextInfo, addText = Canvas.prototype.addText, render = Canvas.prototype.render; } // Finishes rendering the canvas, including overlaid text Canvas.prototype.render = function() { if (!plot.getOptions().canvas) { return render.call(this); } var context = this.context, cache = this._textCache; // For each text layer, render elements marked as active context.save(); context.textBaseline = "middle"; for (var layerKey in cache) { if (hasOwnProperty.call(cache, layerKey)) { var layerCache = cache[layerKey]; for (var styleKey in layerCache) { if (hasOwnProperty.call(layerCache, styleKey)) { var styleCache = layerCache[styleKey], updateStyles = true; for (var key in styleCache) { if (hasOwnProperty.call(styleCache, key)) { var info = styleCache[key], positions = info.positions, lines = info.lines; // Since every element at this level of the cache have the // same font and fill styles, we can just change them once // using the values from the first element. if (updateStyles) { context.fillStyle = info.font.color; context.font = info.font.definition; updateStyles = false; } for (var i = 0, position; position = positions[i]; i++) { if (position.active) { for (var j = 0, line; line = position.lines[j]; j++) { context.fillText(lines[j].text, line[0], line[1]); } } else { positions.splice(i--, 1); } } if (positions.length == 0) { delete styleCache[key]; } } } } } } } context.restore(); }; // Creates (if necessary) and returns a text info object. // // When the canvas option is set, the object looks like this: // // { // width: Width of the text's bounding box. // height: Height of the text's bounding box. // positions: Array of positions at which this text is drawn. // lines: [{ // height: Height of this line. // widths: Width of this line. // text: Text on this line. // }], // font: { // definition: Canvas font property string. // color: Color of the text. // }, // } // // The positions array contains objects that look like this: // // { // active: Flag indicating whether the text should be visible. // lines: Array of [x, y] coordinates at which to draw the line. // x: X coordinate at which to draw the text. // y: Y coordinate at which to draw the text. // } Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) { if (!plot.getOptions().canvas) { return getTextInfo.call(this, layer, text, font, angle, width); } var textStyle, layerCache, styleCache, info; // Cast the value to a string, in case we were given a number text = "" + text; // If the font is a font-spec object, generate a CSS definition if (typeof font === "object") { textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px " + font.family; } else { textStyle = font; } // Retrieve (or create) the cache for the text's layer and styles layerCache = this._textCache[layer]; if (layerCache == null) { layerCache = this._textCache[layer] = {}; } styleCache = layerCache[textStyle]; if (styleCache == null) { styleCache = layerCache[textStyle] = {}; } info = styleCache[text]; if (info == null) { var context = this.context; // If the font was provided as CSS, create a div with those // classes and examine it to generate a canvas font spec. if (typeof font !== "object") { var element = $("<div>&nbsp;</div>") .css("position", "absolute") .addClass(typeof font === "string" ? font : null) .appendTo(this.getTextLayer(layer)); font = { lineHeight: element.height(), style: element.css("font-style"), variant: element.css("font-variant"), weight: element.css("font-weight"), family: element.css("font-family"), color: element.css("color") }; // Setting line-height to 1, without units, sets it equal // to the font-size, even if the font-size is abstract, // like 'smaller'. This enables us to read the real size // via the element's height, working around browsers that // return the literal 'smaller' value. font.size = element.css("line-height", 1).height(); element.remove(); } textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px " + font.family; // Create a new info object, initializing the dimensions to // zero so we can count them up line-by-line. info = styleCache[text] = { width: 0, height: 0, positions: [], lines: [], font: { definition: textStyle, color: font.color } }; context.save(); context.font = textStyle; // Canvas can't handle multi-line strings; break on various // newlines, including HTML brs, to build a list of lines. // Note that we could split directly on regexps, but IE < 9 is // broken; revisit when we drop IE 7/8 support. var lines = (text + "").replace(/<br ?\/?>|\r\n|\r/g, "\n").split("\n"); for (var i = 0; i < lines.length; ++i) { var lineText = lines[i], measured = context.measureText(lineText); info.width = Math.max(measured.width, info.width); info.height += font.lineHeight; info.lines.push({ text: lineText, width: measured.width, height: font.lineHeight }); } context.restore(); } return info; }; // Adds a text string to the canvas text overlay. Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) { if (!plot.getOptions().canvas) { return addText.call(this, layer, x, y, text, font, angle, width, halign, valign); } var info = this.getTextInfo(layer, text, font, angle, width), positions = info.positions, lines = info.lines; // Text is drawn with baseline 'middle', which we need to account // for by adding half a line's height to the y position. y += info.height / lines.length / 2; // Tweak the initial y-position to match vertical alignment if (valign == "middle") { y = Math.round(y - info.height / 2); } else if (valign == "bottom") { y = Math.round(y - info.height); } else { y = Math.round(y); } // FIXME: LEGACY BROWSER FIX // AFFECTS: Opera < 12.00 // Offset the y coordinate, since Opera is off pretty // consistently compared to the other browsers. if (!!(window.opera && window.opera.version().split(".")[0] < 12)) { y -= 2; } // Determine whether this text already exists at this position. // If so, mark it for inclusion in the next render pass. for (var i = 0, position; position = positions[i]; i++) { if (position.x == x && position.y == y) { position.active = true; return; } } // If the text doesn't exist at this position, create a new entry position = { active: true, lines: [], x: x, y: y }; positions.push(position); // Fill in the x & y positions of each line, adjusting them // individually for horizontal alignment. for (var i = 0, line; line = lines[i]; i++) { if (halign == "center") { position.lines.push([Math.round(x - line.width / 2), y]); } else if (halign == "right") { position.lines.push([Math.round(x - line.width), y]); } else { position.lines.push([Math.round(x), y]); } y += line.height; } }; } $.plot.plugins.push({ init: init, options: options, name: "canvas", version: "1.0" }); })(jQuery);
JavaScript
/* Flot plugin for adding the ability to pan and zoom the plot. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The default behaviour is double click and scrollwheel up/down to zoom in, drag to pan. The plugin defines plot.zoom({ center }), plot.zoomOut() and plot.pan( offset ) so you easily can add custom controls. It also fires "plotpan" and "plotzoom" events, useful for synchronizing plots. The plugin supports these options: zoom: { interactive: false trigger: "dblclick" // or "click" for single click amount: 1.5 // 2 = 200% (zoom in), 0.5 = 50% (zoom out) } pan: { interactive: false cursor: "move" // CSS mouse cursor value used when dragging, e.g. "pointer" frameRate: 20 } xaxis, yaxis, x2axis, y2axis: { zoomRange: null // or [ number, number ] (min range, max range) or false panRange: null // or [ number, number ] (min, max) or false } "interactive" enables the built-in drag/click behaviour. If you enable interactive for pan, then you'll have a basic plot that supports moving around; the same for zoom. "amount" specifies the default amount to zoom in (so 1.5 = 150%) relative to the current viewport. "cursor" is a standard CSS mouse cursor string used for visual feedback to the user when dragging. "frameRate" specifies the maximum number of times per second the plot will update itself while the user is panning around on it (set to null to disable intermediate pans, the plot will then not update until the mouse button is released). "zoomRange" is the interval in which zooming can happen, e.g. with zoomRange: [1, 100] the zoom will never scale the axis so that the difference between min and max is smaller than 1 or larger than 100. You can set either end to null to ignore, e.g. [1, null]. If you set zoomRange to false, zooming on that axis will be disabled. "panRange" confines the panning to stay within a range, e.g. with panRange: [-10, 20] panning stops at -10 in one end and at 20 in the other. Either can be null, e.g. [-10, null]. If you set panRange to false, panning on that axis will be disabled. Example API usage: plot = $.plot(...); // zoom default amount in on the pixel ( 10, 20 ) plot.zoom({ center: { left: 10, top: 20 } }); // zoom out again plot.zoomOut({ center: { left: 10, top: 20 } }); // zoom 200% in on the pixel (10, 20) plot.zoom({ amount: 2, center: { left: 10, top: 20 } }); // pan 100 pixels to the left and 20 down plot.pan({ left: -100, top: 20 }) Here, "center" specifies where the center of the zooming should happen. Note that this is defined in pixel space, not the space of the data points (you can use the p2c helpers on the axes in Flot to help you convert between these). "amount" is the amount to zoom the viewport relative to the current range, so 1 is 100% (i.e. no change), 1.5 is 150% (zoom in), 0.7 is 70% (zoom out). You can set the default in the options. */ // First two dependencies, jquery.event.drag.js and // jquery.mousewheel.js, we put them inline here to save people the // effort of downloading them. /* jquery.event.drag.js ~ v1.5 ~ Copyright (c) 2008, Three Dub Media (http://threedubmedia.com) Licensed under the MIT License ~ http://threedubmedia.googlecode.com/files/MIT-LICENSE.txt */ (function(a){function e(h){var k,j=this,l=h.data||{};if(l.elem)j=h.dragTarget=l.elem,h.dragProxy=d.proxy||j,h.cursorOffsetX=l.pageX-l.left,h.cursorOffsetY=l.pageY-l.top,h.offsetX=h.pageX-h.cursorOffsetX,h.offsetY=h.pageY-h.cursorOffsetY;else if(d.dragging||l.which>0&&h.which!=l.which||a(h.target).is(l.not))return;switch(h.type){case"mousedown":return a.extend(l,a(j).offset(),{elem:j,target:h.target,pageX:h.pageX,pageY:h.pageY}),b.add(document,"mousemove mouseup",e,l),i(j,!1),d.dragging=null,!1;case!d.dragging&&"mousemove":if(g(h.pageX-l.pageX)+g(h.pageY-l.pageY)<l.distance)break;h.target=l.target,k=f(h,"dragstart",j),k!==!1&&(d.dragging=j,d.proxy=h.dragProxy=a(k||j)[0]);case"mousemove":if(d.dragging){if(k=f(h,"drag",j),c.drop&&(c.drop.allowed=k!==!1,c.drop.handler(h)),k!==!1)break;h.type="mouseup"}case"mouseup":b.remove(document,"mousemove mouseup",e),d.dragging&&(c.drop&&c.drop.handler(h),f(h,"dragend",j)),i(j,!0),d.dragging=d.proxy=l.elem=!1}return!0}function f(b,c,d){b.type=c;var e=a.event.dispatch.call(d,b);return e===!1?!1:e||b.result}function g(a){return Math.pow(a,2)}function h(){return d.dragging===!1}function i(a,b){a&&(a.unselectable=b?"off":"on",a.onselectstart=function(){return b},a.style&&(a.style.MozUserSelect=b?"":"none"))}a.fn.drag=function(a,b,c){return b&&this.bind("dragstart",a),c&&this.bind("dragend",c),a?this.bind("drag",b?b:a):this.trigger("drag")};var b=a.event,c=b.special,d=c.drag={not:":input",distance:0,which:1,dragging:!1,setup:function(c){c=a.extend({distance:d.distance,which:d.which,not:d.not},c||{}),c.distance=g(c.distance),b.add(this,"mousedown",e,c),this.attachEvent&&this.attachEvent("ondragstart",h)},teardown:function(){b.remove(this,"mousedown",e),this===d.dragging&&(d.dragging=d.proxy=!1),i(this,!0),this.detachEvent&&this.detachEvent("ondragstart",h)}};c.dragstart=c.dragend={setup:function(){},teardown:function(){}}})(jQuery); /* jquery.mousewheel.min.js * Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.6 * * Requires: 1.2.2+ */ (function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;void 0!==b.axis&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);void 0!==b.wheelDeltaY&&(g=b.wheelDeltaY/120);void 0!==b.wheelDeltaX&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]=d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,!1);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,!1);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery); (function ($) { var options = { xaxis: { zoomRange: null, // or [number, number] (min range, max range) panRange: null // or [number, number] (min, max) }, zoom: { interactive: false, trigger: "dblclick", // or "click" for single click amount: 1.5 // how much to zoom relative to current position, 2 = 200% (zoom in), 0.5 = 50% (zoom out) }, pan: { interactive: false, cursor: "move", frameRate: 20 } }; function init(plot) { function onZoomClick(e, zoomOut) { var c = plot.offset(); c.left = e.pageX - c.left; c.top = e.pageY - c.top; if (zoomOut) plot.zoomOut({ center: c }); else plot.zoom({ center: c }); } function onMouseWheel(e, delta) { e.preventDefault(); onZoomClick(e, delta < 0); return false; } var prevCursor = 'default', prevPageX = 0, prevPageY = 0, panTimeout = null; function onDragStart(e) { if (e.which != 1) // only accept left-click return false; var c = plot.getPlaceholder().css('cursor'); if (c) prevCursor = c; plot.getPlaceholder().css('cursor', plot.getOptions().pan.cursor); prevPageX = e.pageX; prevPageY = e.pageY; } function onDrag(e) { var frameRate = plot.getOptions().pan.frameRate; if (panTimeout || !frameRate) return; panTimeout = setTimeout(function () { plot.pan({ left: prevPageX - e.pageX, top: prevPageY - e.pageY }); prevPageX = e.pageX; prevPageY = e.pageY; panTimeout = null; }, 1 / frameRate * 1000); } function onDragEnd(e) { if (panTimeout) { clearTimeout(panTimeout); panTimeout = null; } plot.getPlaceholder().css('cursor', prevCursor); plot.pan({ left: prevPageX - e.pageX, top: prevPageY - e.pageY }); } function bindEvents(plot, eventHolder) { var o = plot.getOptions(); if (o.zoom.interactive) { eventHolder[o.zoom.trigger](onZoomClick); eventHolder.mousewheel(onMouseWheel); } if (o.pan.interactive) { eventHolder.bind("dragstart", { distance: 10 }, onDragStart); eventHolder.bind("drag", onDrag); eventHolder.bind("dragend", onDragEnd); } } plot.zoomOut = function (args) { if (!args) args = {}; if (!args.amount) args.amount = plot.getOptions().zoom.amount; args.amount = 1 / args.amount; plot.zoom(args); }; plot.zoom = function (args) { if (!args) args = {}; var c = args.center, amount = args.amount || plot.getOptions().zoom.amount, w = plot.width(), h = plot.height(); if (!c) c = { left: w / 2, top: h / 2 }; var xf = c.left / w, yf = c.top / h, minmax = { x: { min: c.left - xf * w / amount, max: c.left + (1 - xf) * w / amount }, y: { min: c.top - yf * h / amount, max: c.top + (1 - yf) * h / amount } }; $.each(plot.getAxes(), function(_, axis) { var opts = axis.options, min = minmax[axis.direction].min, max = minmax[axis.direction].max, zr = opts.zoomRange, pr = opts.panRange; if (zr === false) // no zooming on this axis return; min = axis.c2p(min); max = axis.c2p(max); if (min > max) { // make sure min < max var tmp = min; min = max; max = tmp; } //Check that we are in panRange if (pr) { if (pr[0] != null && min < pr[0]) { min = pr[0]; } if (pr[1] != null && max > pr[1]) { max = pr[1]; } } var range = max - min; if (zr && ((zr[0] != null && range < zr[0]) || (zr[1] != null && range > zr[1]))) return; opts.min = min; opts.max = max; }); plot.setupGrid(); plot.draw(); if (!args.preventEvent) plot.getPlaceholder().trigger("plotzoom", [ plot, args ]); }; plot.pan = function (args) { var delta = { x: +args.left, y: +args.top }; if (isNaN(delta.x)) delta.x = 0; if (isNaN(delta.y)) delta.y = 0; $.each(plot.getAxes(), function (_, axis) { var opts = axis.options, min, max, d = delta[axis.direction]; min = axis.c2p(axis.p2c(axis.min) + d), max = axis.c2p(axis.p2c(axis.max) + d); var pr = opts.panRange; if (pr === false) // no panning on this axis return; if (pr) { // check whether we hit the wall if (pr[0] != null && pr[0] > min) { d = pr[0] - min; min += d; max += d; } if (pr[1] != null && pr[1] < max) { d = pr[1] - max; min += d; max += d; } } opts.min = min; opts.max = max; }); plot.setupGrid(); plot.draw(); if (!args.preventEvent) plot.getPlaceholder().trigger("plotpan", [ plot, args ]); }; function shutdown(plot, eventHolder) { eventHolder.unbind(plot.getOptions().zoom.trigger, onZoomClick); eventHolder.unbind("mousewheel", onMouseWheel); eventHolder.unbind("dragstart", onDragStart); eventHolder.unbind("drag", onDrag); eventHolder.unbind("dragend", onDragEnd); if (panTimeout) clearTimeout(panTimeout); } plot.hooks.bindEvents.push(bindEvents); plot.hooks.shutdown.push(shutdown); } $.plot.plugins.push({ init: init, options: options, name: 'navigate', version: '1.3' }); })(jQuery);
JavaScript
/* Pretty handling of time axes. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. Set axis.mode to "time" to enable. See the section "Time series data" in API.txt for details. */ (function($) { var options = { xaxis: { timezone: null, // "browser" for local to the client or timezone for timezone-js timeformat: null, // format string to use twelveHourClock: false, // 12 or 24 time in time mode monthNames: null // list of names of months } }; // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } // Returns a string with the date d formatted according to fmt. // A subset of the Open Group's strftime format is supported. function formatDate(d, fmt, monthNames, dayNames) { if (typeof d.strftime == "function") { return d.strftime(fmt); } var leftPad = function(n, pad) { n = "" + n; pad = "" + (pad == null ? "0" : pad); return n.length == 1 ? pad + n : n; }; var r = []; var escape = false; var hours = d.getHours(); var isAM = hours < 12; if (monthNames == null) { monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; } if (dayNames == null) { dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; } var hours12; if (hours > 12) { hours12 = hours - 12; } else if (hours == 0) { hours12 = 12; } else { hours12 = hours; } for (var i = 0; i < fmt.length; ++i) { var c = fmt.charAt(i); if (escape) { switch (c) { case 'a': c = "" + dayNames[d.getDay()]; break; case 'b': c = "" + monthNames[d.getMonth()]; break; case 'd': c = leftPad(d.getDate()); break; case 'e': c = leftPad(d.getDate(), " "); break; case 'h': // For back-compat with 0.7; remove in 1.0 case 'H': c = leftPad(hours); break; case 'I': c = leftPad(hours12); break; case 'l': c = leftPad(hours12, " "); break; case 'm': c = leftPad(d.getMonth() + 1); break; case 'M': c = leftPad(d.getMinutes()); break; // quarters not in Open Group's strftime specification case 'q': c = "" + (Math.floor(d.getMonth() / 3) + 1); break; case 'S': c = leftPad(d.getSeconds()); break; case 'y': c = leftPad(d.getFullYear() % 100); break; case 'Y': c = "" + d.getFullYear(); break; case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break; case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break; case 'w': c = "" + d.getDay(); break; } r.push(c); escape = false; } else { if (c == "%") { escape = true; } else { r.push(c); } } } return r.join(""); } // To have a consistent view of time-based data independent of which time // zone the client happens to be in we need a date-like object independent // of time zones. This is done through a wrapper that only calls the UTC // versions of the accessor methods. function makeUtcWrapper(d) { function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) { sourceObj[sourceMethod] = function() { return targetObj[targetMethod].apply(targetObj, arguments); }; }; var utc = { date: d }; // support strftime, if found if (d.strftime != undefined) { addProxyMethod(utc, "strftime", d, "strftime"); } addProxyMethod(utc, "getTime", d, "getTime"); addProxyMethod(utc, "setTime", d, "setTime"); var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"]; for (var p = 0; p < props.length; p++) { addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]); addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]); } return utc; }; // select time zone strategy. This returns a date-like object tied to the // desired timezone function dateGenerator(ts, opts) { if (opts.timezone == "browser") { return new Date(ts); } else if (!opts.timezone || opts.timezone == "utc") { return makeUtcWrapper(new Date(ts)); } else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") { var d = new timezoneJS.Date(); // timezone-js is fickle, so be sure to set the time zone before // setting the time. d.setTimezone(opts.timezone); d.setTime(ts); return d; } else { return makeUtcWrapper(new Date(ts)); } } // map of app. size of time units in milliseconds var timeUnitSize = { "second": 1000, "minute": 60 * 1000, "hour": 60 * 60 * 1000, "day": 24 * 60 * 60 * 1000, "month": 30 * 24 * 60 * 60 * 1000, "quarter": 3 * 30 * 24 * 60 * 60 * 1000, "year": 365.2425 * 24 * 60 * 60 * 1000 }; // the allowed tick sizes, after 1 year we use // an integer algorithm var baseSpec = [ [1, "second"], [2, "second"], [5, "second"], [10, "second"], [30, "second"], [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], [30, "minute"], [1, "hour"], [2, "hour"], [4, "hour"], [8, "hour"], [12, "hour"], [1, "day"], [2, "day"], [3, "day"], [0.25, "month"], [0.5, "month"], [1, "month"], [2, "month"] ]; // we don't know which variant(s) we'll need yet, but generating both is // cheap var specMonths = baseSpec.concat([[3, "month"], [6, "month"], [1, "year"]]); var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"], [1, "year"]]); function init(plot) { plot.hooks.processOptions.push(function (plot, options) { $.each(plot.getAxes(), function(axisName, axis) { var opts = axis.options; if (opts.mode == "time") { axis.tickGenerator = function(axis) { var ticks = []; var d = dateGenerator(axis.min, opts); var minSize = 0; // make quarter use a possibility if quarters are // mentioned in either of these options var spec = (opts.tickSize && opts.tickSize[1] === "quarter") || (opts.minTickSize && opts.minTickSize[1] === "quarter") ? specQuarters : specMonths; if (opts.minTickSize != null) { if (typeof opts.tickSize == "number") { minSize = opts.tickSize; } else { minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]]; } } for (var i = 0; i < spec.length - 1; ++i) { if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]] + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) { break; } } var size = spec[i][0]; var unit = spec[i][1]; // special-case the possibility of several years if (unit == "year") { // if given a minTickSize in years, just use it, // ensuring that it's an integer if (opts.minTickSize != null && opts.minTickSize[1] == "year") { size = Math.floor(opts.minTickSize[0]); } else { var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10)); var norm = (axis.delta / timeUnitSize.year) / magn; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; } // minimum size for years is 1 if (size < 1) { size = 1; } } axis.tickSize = opts.tickSize || [size, unit]; var tickSize = axis.tickSize[0]; unit = axis.tickSize[1]; var step = tickSize * timeUnitSize[unit]; if (unit == "second") { d.setSeconds(floorInBase(d.getSeconds(), tickSize)); } else if (unit == "minute") { d.setMinutes(floorInBase(d.getMinutes(), tickSize)); } else if (unit == "hour") { d.setHours(floorInBase(d.getHours(), tickSize)); } else if (unit == "month") { d.setMonth(floorInBase(d.getMonth(), tickSize)); } else if (unit == "quarter") { d.setMonth(3 * floorInBase(d.getMonth() / 3, tickSize)); } else if (unit == "year") { d.setFullYear(floorInBase(d.getFullYear(), tickSize)); } // reset smaller components d.setMilliseconds(0); if (step >= timeUnitSize.minute) { d.setSeconds(0); } if (step >= timeUnitSize.hour) { d.setMinutes(0); } if (step >= timeUnitSize.day) { d.setHours(0); } if (step >= timeUnitSize.day * 4) { d.setDate(1); } if (step >= timeUnitSize.month * 2) { d.setMonth(floorInBase(d.getMonth(), 3)); } if (step >= timeUnitSize.quarter * 2) { d.setMonth(floorInBase(d.getMonth(), 6)); } if (step >= timeUnitSize.year) { d.setMonth(0); } var carry = 0; var v = Number.NaN; var prev; do { prev = v; v = d.getTime(); ticks.push(v); if (unit == "month" || unit == "quarter") { if (tickSize < 1) { // a bit complicated - we'll divide the // month/quarter up but we need to take // care of fractions so we don't end up in // the middle of a day d.setDate(1); var start = d.getTime(); d.setMonth(d.getMonth() + (unit == "quarter" ? 3 : 1)); var end = d.getTime(); d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize); carry = d.getHours(); d.setHours(0); } else { d.setMonth(d.getMonth() + tickSize * (unit == "quarter" ? 3 : 1)); } } else if (unit == "year") { d.setFullYear(d.getFullYear() + tickSize); } else { d.setTime(v + step); } } while (v < axis.max && v != prev); return ticks; }; axis.tickFormatter = function (v, axis) { var d = dateGenerator(v, axis.options); // first check global format if (opts.timeformat != null) { return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames); } // possibly use quarters if quarters are mentioned in // any of these places var useQuarters = (axis.options.tickSize && axis.options.tickSize[1] == "quarter") || (axis.options.minTickSize && axis.options.minTickSize[1] == "quarter"); var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; var span = axis.max - axis.min; var suffix = (opts.twelveHourClock) ? " %p" : ""; var hourCode = (opts.twelveHourClock) ? "%I" : "%H"; var fmt; if (t < timeUnitSize.minute) { fmt = hourCode + ":%M:%S" + suffix; } else if (t < timeUnitSize.day) { if (span < 2 * timeUnitSize.day) { fmt = hourCode + ":%M" + suffix; } else { fmt = "%b %d " + hourCode + ":%M" + suffix; } } else if (t < timeUnitSize.month) { fmt = "%b %d"; } else if ((useQuarters && t < timeUnitSize.quarter) || (!useQuarters && t < timeUnitSize.year)) { if (span < timeUnitSize.year) { fmt = "%b"; } else { fmt = "%b %Y"; } } else if (useQuarters && t < timeUnitSize.year) { if (span < timeUnitSize.year) { fmt = "Q%q"; } else { fmt = "Q%q %Y"; } } else { fmt = "%Y"; } var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames); return rt; }; } }); }); } $.plot.plugins.push({ init: init, options: options, name: 'time', version: '1.0' }); // Time-axis support used to be in Flot core, which exposed the // formatDate function on the plot object. Various plugins depend // on the function, so we need to re-expose it here. $.plot.formatDate = formatDate; })(jQuery);
JavaScript
// ----- // The `timezoneJS.Date` object gives you full-blown timezone support, independent from the timezone set on the end-user's machine running the browser. It uses the Olson zoneinfo files for its timezone data. // // The constructor function and setter methods use proxy JavaScript Date objects behind the scenes, so you can use strings like '10/22/2006' with the constructor. You also get the same sensible wraparound behavior with numeric parameters (like setting a value of 14 for the month wraps around to the next March). // // The other significant difference from the built-in JavaScript Date is that `timezoneJS.Date` also has named properties that store the values of year, month, date, etc., so it can be directly serialized to JSON and used for data transfer. /* * Copyright 2010 Matthew Eernisse (mde@fleegix.org) * and Open Source Applications Foundation * * 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. * * Credits: Ideas included from incomplete JS implementation of Olson * parser, "XMLDAte" by Philippe Goetz (philippe.goetz@wanadoo.fr) * * Contributions: * Jan Niehusmann * Ricky Romero * Preston Hunt (prestonhunt@gmail.com) * Dov. B Katz (dov.katz@morganstanley.com) * Peter Bergström (pbergstr@mac.com) * Long Ho */ (function () { // Standard initialization stuff to make sure the library is // usable on both client and server (node) side. var root = this; var timezoneJS; if (typeof exports !== 'undefined') { timezoneJS = exports; } else { timezoneJS = root.timezoneJS = {}; } timezoneJS.VERSION = '1.0.0'; // Grab the ajax library from global context. // This can be jQuery, Zepto or fleegix. // You can also specify your own transport mechanism by declaring // `timezoneJS.timezone.transport` to a `function`. More details will follow var $ = root.$ || root.jQuery || root.Zepto , fleegix = root.fleegix // Declare constant list of days and months. Unfortunately this doesn't leave room for i18n due to the Olson data being in English itself , DAYS = timezoneJS.Days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] , MONTHS = timezoneJS.Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] , SHORT_MONTHS = {} , SHORT_DAYS = {} , EXACT_DATE_TIME = {} , TZ_REGEXP = new RegExp('^[a-zA-Z]+/'); //`{ "Jan": 0, "Feb": 1, "Mar": 2, "Apr": 3, "May": 4, "Jun": 5, "Jul": 6, "Aug": 7, "Sep": 8, "Oct": 9, "Nov": 10, "Dec": 11 }` for (var i = 0; i < MONTHS.length; i++) { SHORT_MONTHS[MONTHS[i].substr(0, 3)] = i; } //`{ "Sun": 0, "Mon": 1, "Tue": 2, "Wed": 3, "Thu": 4, "Fri": 5, "Sat": 6 }` for (i = 0; i < DAYS.length; i++) { SHORT_DAYS[DAYS[i].substr(0, 3)] = i; } //Handle array indexOf in IE if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (el) { for (var i = 0; i < this.length; i++ ) { if (el === this[i]) return i; } return -1; } } // Format a number to the length = digits. For ex: // // `_fixWidth(2, 2) = '02'` // // `_fixWidth(1998, 2) = '98'` // // This is used to pad numbers in converting date to string in ISO standard. var _fixWidth = function (number, digits) { if (typeof number !== "number") { throw "not a number: " + number; } var s = number.toString(); if (number.length > digits) { return number.substr(number.length - digits, number.length); } while (s.length < digits) { s = '0' + s; } return s; }; // Abstraction layer for different transport layers, including fleegix/jQuery/Zepto // // Object `opts` include // // - `url`: url to ajax query // // - `async`: true for asynchronous, false otherwise. If false, return value will be response from URL. This is true by default // // - `success`: success callback function // // - `error`: error callback function // Returns response from URL if async is false, otherwise the AJAX request object itself var _transport = function (opts) { if ((!fleegix || typeof fleegix.xhr === 'undefined') && (!$ || typeof $.ajax === 'undefined')) { throw new Error('Please use the Fleegix.js XHR module, jQuery ajax, Zepto ajax, or define your own transport mechanism for downloading zone files.'); } if (!opts) return; if (!opts.url) throw new Error ('URL must be specified'); if (!('async' in opts)) opts.async = true; if (!opts.async) { return fleegix && fleegix.xhr ? fleegix.xhr.doReq({ url: opts.url, async: false }) : $.ajax({ url : opts.url, async : false }).responseText; } return fleegix && fleegix.xhr ? fleegix.xhr.send({ url : opts.url, method : 'get', handleSuccess : opts.success, handleErr : opts.error }) : $.ajax({ url : opts.url, dataType: 'text', method : 'GET', error : opts.error, success : opts.success }); }; // Constructor, which is similar to that of the native Date object itself timezoneJS.Date = function () { var args = Array.prototype.slice.apply(arguments) , dt = null , tz = null , arr = []; //We support several different constructors, including all the ones from `Date` object // with a timezone string at the end. // //- `[tz]`: Returns object with time in `tz` specified. // // - `utcMillis`, `[tz]`: Return object with UTC time = `utcMillis`, in `tz`. // // - `Date`, `[tz]`: Returns object with UTC time = `Date.getTime()`, in `tz`. // // - `year, month, [date,] [hours,] [minutes,] [seconds,] [millis,] [tz]: Same as `Date` object // with tz. // // - `Array`: Can be any combo of the above. // //If 1st argument is an array, we can use it as a list of arguments itself if (Object.prototype.toString.call(args[0]) === '[object Array]') { args = args[0]; } if (typeof args[args.length - 1] === 'string' && TZ_REGEXP.test(args[args.length - 1])) { tz = args.pop(); } switch (args.length) { case 0: dt = new Date(); break; case 1: dt = new Date(args[0]); break; default: for (var i = 0; i < 7; i++) { arr[i] = args[i] || 0; } dt = new Date(arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6]); break; } this._useCache = false; this._tzInfo = {}; this._day = 0; this.year = 0; this.month = 0; this.date = 0; this.hours = 0; this.minutes = 0; this.seconds = 0; this.milliseconds = 0; this.timezone = tz || null; //Tricky part: // For the cases where there are 1/2 arguments: `timezoneJS.Date(millis, [tz])` and `timezoneJS.Date(Date, [tz])`. The // Date `dt` created should be in UTC. Thus the way I detect such cases is to determine if `arr` is not populated & `tz` // is specified. Because if `tz` is not specified, `dt` can be in local time. if (arr.length) { this.setFromDateObjProxy(dt); } else { this.setFromTimeProxy(dt.getTime(), tz); } }; // Implements most of the native Date object timezoneJS.Date.prototype = { getDate: function () { return this.date; }, getDay: function () { return this._day; }, getFullYear: function () { return this.year; }, getMonth: function () { return this.month; }, getYear: function () { return this.year; }, getHours: function () { return this.hours; }, getMilliseconds: function () { return this.milliseconds; }, getMinutes: function () { return this.minutes; }, getSeconds: function () { return this.seconds; }, getUTCDate: function () { return this.getUTCDateProxy().getUTCDate(); }, getUTCDay: function () { return this.getUTCDateProxy().getUTCDay(); }, getUTCFullYear: function () { return this.getUTCDateProxy().getUTCFullYear(); }, getUTCHours: function () { return this.getUTCDateProxy().getUTCHours(); }, getUTCMilliseconds: function () { return this.getUTCDateProxy().getUTCMilliseconds(); }, getUTCMinutes: function () { return this.getUTCDateProxy().getUTCMinutes(); }, getUTCMonth: function () { return this.getUTCDateProxy().getUTCMonth(); }, getUTCSeconds: function () { return this.getUTCDateProxy().getUTCSeconds(); }, // Time adjusted to user-specified timezone getTime: function () { return this._timeProxy + (this.getTimezoneOffset() * 60 * 1000); }, getTimezone: function () { return this.timezone; }, getTimezoneOffset: function () { return this.getTimezoneInfo().tzOffset; }, getTimezoneAbbreviation: function () { return this.getTimezoneInfo().tzAbbr; }, getTimezoneInfo: function () { if (this._useCache) return this._tzInfo; var res; // If timezone is specified, get the correct timezone info based on the Date given if (this.timezone) { res = this.timezone === 'Etc/UTC' || this.timezone === 'Etc/GMT' ? { tzOffset: 0, tzAbbr: 'UTC' } : timezoneJS.timezone.getTzInfo(this._timeProxy, this.timezone); } // If no timezone was specified, use the local browser offset else { res = { tzOffset: this.getLocalOffset(), tzAbbr: null }; } this._tzInfo = res; this._useCache = true; return res }, getUTCDateProxy: function () { var dt = new Date(this._timeProxy); dt.setUTCMinutes(dt.getUTCMinutes() + this.getTimezoneOffset()); return dt; }, setDate: function (n) { this.setAttribute('date', n); }, setFullYear: function (n) { this.setAttribute('year', n); }, setMonth: function (n) { this.setAttribute('month', n); }, setYear: function (n) { this.setUTCAttribute('year', n); }, setHours: function (n) { this.setAttribute('hours', n); }, setMilliseconds: function (n) { this.setAttribute('milliseconds', n); }, setMinutes: function (n) { this.setAttribute('minutes', n); }, setSeconds: function (n) { this.setAttribute('seconds', n); }, setTime: function (n) { if (isNaN(n)) { throw new Error('Units must be a number.'); } this.setFromTimeProxy(n, this.timezone); }, setUTCDate: function (n) { this.setUTCAttribute('date', n); }, setUTCFullYear: function (n) { this.setUTCAttribute('year', n); }, setUTCHours: function (n) { this.setUTCAttribute('hours', n); }, setUTCMilliseconds: function (n) { this.setUTCAttribute('milliseconds', n); }, setUTCMinutes: function (n) { this.setUTCAttribute('minutes', n); }, setUTCMonth: function (n) { this.setUTCAttribute('month', n); }, setUTCSeconds: function (n) { this.setUTCAttribute('seconds', n); }, setFromDateObjProxy: function (dt) { this.year = dt.getFullYear(); this.month = dt.getMonth(); this.date = dt.getDate(); this.hours = dt.getHours(); this.minutes = dt.getMinutes(); this.seconds = dt.getSeconds(); this.milliseconds = dt.getMilliseconds(); this._day = dt.getDay(); this._dateProxy = dt; this._timeProxy = Date.UTC(this.year, this.month, this.date, this.hours, this.minutes, this.seconds, this.milliseconds); this._useCache = false; }, setFromTimeProxy: function (utcMillis, tz) { var dt = new Date(utcMillis); var tzOffset; tzOffset = tz ? timezoneJS.timezone.getTzInfo(dt, tz).tzOffset : dt.getTimezoneOffset(); dt.setTime(utcMillis + (dt.getTimezoneOffset() - tzOffset) * 60000); this.setFromDateObjProxy(dt); }, setAttribute: function (unit, n) { if (isNaN(n)) { throw new Error('Units must be a number.'); } var dt = this._dateProxy; var meth = unit === 'year' ? 'FullYear' : unit.substr(0, 1).toUpperCase() + unit.substr(1); dt['set' + meth](n); this.setFromDateObjProxy(dt); }, setUTCAttribute: function (unit, n) { if (isNaN(n)) { throw new Error('Units must be a number.'); } var meth = unit === 'year' ? 'FullYear' : unit.substr(0, 1).toUpperCase() + unit.substr(1); var dt = this.getUTCDateProxy(); dt['setUTC' + meth](n); dt.setUTCMinutes(dt.getUTCMinutes() - this.getTimezoneOffset()); this.setFromTimeProxy(dt.getTime() + this.getTimezoneOffset() * 60000, this.timezone); }, setTimezone: function (tz) { var previousOffset = this.getTimezoneInfo().tzOffset; this.timezone = tz; this._useCache = false; // Set UTC minutes offsets by the delta of the two timezones this.setUTCMinutes(this.getUTCMinutes() - this.getTimezoneInfo().tzOffset + previousOffset); }, removeTimezone: function () { this.timezone = null; this._useCache = false; }, valueOf: function () { return this.getTime(); }, clone: function () { return this.timezone ? new timezoneJS.Date(this.getTime(), this.timezone) : new timezoneJS.Date(this.getTime()); }, toGMTString: function () { return this.toString('EEE, dd MMM yyyy HH:mm:ss Z', 'Etc/GMT'); }, toLocaleString: function () {}, toLocaleDateString: function () {}, toLocaleTimeString: function () {}, toSource: function () {}, toISOString: function () { return this.toString('yyyy-MM-ddTHH:mm:ss.SSS', 'Etc/UTC') + 'Z'; }, toJSON: function () { return this.toISOString(); }, // Allows different format following ISO8601 format: toString: function (format, tz) { // Default format is the same as toISOString if (!format) format = 'yyyy-MM-dd HH:mm:ss'; var result = format; var tzInfo = tz ? timezoneJS.timezone.getTzInfo(this.getTime(), tz) : this.getTimezoneInfo(); var _this = this; // If timezone is specified, get a clone of the current Date object and modify it if (tz) { _this = this.clone(); _this.setTimezone(tz); } var hours = _this.getHours(); return result // fix the same characters in Month names .replace(/a+/g, function () { return 'k'; }) // `y`: year .replace(/y+/g, function (token) { return _fixWidth(_this.getFullYear(), token.length); }) // `d`: date .replace(/d+/g, function (token) { return _fixWidth(_this.getDate(), token.length); }) // `m`: minute .replace(/m+/g, function (token) { return _fixWidth(_this.getMinutes(), token.length); }) // `s`: second .replace(/s+/g, function (token) { return _fixWidth(_this.getSeconds(), token.length); }) // `S`: millisecond .replace(/S+/g, function (token) { return _fixWidth(_this.getMilliseconds(), token.length); }) // `M`: month. Note: `MM` will be the numeric representation (e.g February is 02) but `MMM` will be text representation (e.g February is Feb) .replace(/M+/g, function (token) { var _month = _this.getMonth(), _len = token.length; if (_len > 3) { return timezoneJS.Months[_month]; } else if (_len > 2) { return timezoneJS.Months[_month].substring(0, _len); } return _fixWidth(_month + 1, _len); }) // `k`: AM/PM .replace(/k+/g, function () { if (hours >= 12) { if (hours > 12) { hours -= 12; } return 'PM'; } return 'AM'; }) // `H`: hour .replace(/H+/g, function (token) { return _fixWidth(hours, token.length); }) // `E`: day .replace(/E+/g, function (token) { return DAYS[_this.getDay()].substring(0, token.length); }) // `Z`: timezone abbreviation .replace(/Z+/gi, function () { return tzInfo.tzAbbr; }); }, toUTCString: function () { return this.toGMTString(); }, civilToJulianDayNumber: function (y, m, d) { var a; // Adjust for zero-based JS-style array m++; if (m > 12) { a = parseInt(m/12, 10); m = m % 12; y += a; } if (m <= 2) { y -= 1; m += 12; } a = Math.floor(y / 100); var b = 2 - a + Math.floor(a / 4) , jDt = Math.floor(365.25 * (y + 4716)) + Math.floor(30.6001 * (m + 1)) + d + b - 1524; return jDt; }, getLocalOffset: function () { return this._dateProxy.getTimezoneOffset(); } }; timezoneJS.timezone = new function () { var _this = this , regionMap = {'Etc':'etcetera','EST':'northamerica','MST':'northamerica','HST':'northamerica','EST5EDT':'northamerica','CST6CDT':'northamerica','MST7MDT':'northamerica','PST8PDT':'northamerica','America':'northamerica','Pacific':'australasia','Atlantic':'europe','Africa':'africa','Indian':'africa','Antarctica':'antarctica','Asia':'asia','Australia':'australasia','Europe':'europe','WET':'europe','CET':'europe','MET':'europe','EET':'europe'} , regionExceptions = {'Pacific/Honolulu':'northamerica','Atlantic/Bermuda':'northamerica','Atlantic/Cape_Verde':'africa','Atlantic/St_Helena':'africa','Indian/Kerguelen':'antarctica','Indian/Chagos':'asia','Indian/Maldives':'asia','Indian/Christmas':'australasia','Indian/Cocos':'australasia','America/Danmarkshavn':'europe','America/Scoresbysund':'europe','America/Godthab':'europe','America/Thule':'europe','Asia/Yekaterinburg':'europe','Asia/Omsk':'europe','Asia/Novosibirsk':'europe','Asia/Krasnoyarsk':'europe','Asia/Irkutsk':'europe','Asia/Yakutsk':'europe','Asia/Vladivostok':'europe','Asia/Sakhalin':'europe','Asia/Magadan':'europe','Asia/Kamchatka':'europe','Asia/Anadyr':'europe','Africa/Ceuta':'europe','America/Argentina/Buenos_Aires':'southamerica','America/Argentina/Cordoba':'southamerica','America/Argentina/Tucuman':'southamerica','America/Argentina/La_Rioja':'southamerica','America/Argentina/San_Juan':'southamerica','America/Argentina/Jujuy':'southamerica','America/Argentina/Catamarca':'southamerica','America/Argentina/Mendoza':'southamerica','America/Argentina/Rio_Gallegos':'southamerica','America/Argentina/Ushuaia':'southamerica','America/Aruba':'southamerica','America/La_Paz':'southamerica','America/Noronha':'southamerica','America/Belem':'southamerica','America/Fortaleza':'southamerica','America/Recife':'southamerica','America/Araguaina':'southamerica','America/Maceio':'southamerica','America/Bahia':'southamerica','America/Sao_Paulo':'southamerica','America/Campo_Grande':'southamerica','America/Cuiaba':'southamerica','America/Porto_Velho':'southamerica','America/Boa_Vista':'southamerica','America/Manaus':'southamerica','America/Eirunepe':'southamerica','America/Rio_Branco':'southamerica','America/Santiago':'southamerica','Pacific/Easter':'southamerica','America/Bogota':'southamerica','America/Curacao':'southamerica','America/Guayaquil':'southamerica','Pacific/Galapagos':'southamerica','Atlantic/Stanley':'southamerica','America/Cayenne':'southamerica','America/Guyana':'southamerica','America/Asuncion':'southamerica','America/Lima':'southamerica','Atlantic/South_Georgia':'southamerica','America/Paramaribo':'southamerica','America/Port_of_Spain':'southamerica','America/Montevideo':'southamerica','America/Caracas':'southamerica'}; function invalidTZError(t) { throw new Error('Timezone "' + t + '" is either incorrect, or not loaded in the timezone registry.'); } function builtInLoadZoneFile(fileName, opts) { var url = _this.zoneFileBasePath + '/' + fileName; return !opts || !opts.async ? _this.parseZones(_this.transport({ url : url, async : false })) : _this.transport({ async: true, url : url, success : function (str) { if (_this.parseZones(str) && typeof opts.callback === 'function') { opts.callback(); } return true; }, error : function () { throw new Error('Error retrieving "' + url + '" zoneinfo files'); } }); } function getRegionForTimezone(tz) { var exc = regionExceptions[tz] , reg , ret; if (exc) return exc; reg = tz.split('/')[0]; ret = regionMap[reg]; // If there's nothing listed in the main regions for this TZ, check the 'backward' links if (ret) return ret; var link = _this.zones[tz]; if (typeof link === 'string') { return getRegionForTimezone(link); } // Backward-compat file hasn't loaded yet, try looking in there if (!_this.loadedZones.backward) { // This is for obvious legacy zones (e.g., Iceland) that don't even have a prefix like "America/" that look like normal zones _this.loadZoneFile('backward'); return getRegionForTimezone(tz); } invalidTZError(tz); } function parseTimeString(str) { var pat = /(\d+)(?::0*(\d*))?(?::0*(\d*))?([wsugz])?$/; var hms = str.match(pat); hms[1] = parseInt(hms[1], 10); hms[2] = hms[2] ? parseInt(hms[2], 10) : 0; hms[3] = hms[3] ? parseInt(hms[3], 10) : 0; return hms; } function processZone(z) { if (!z[3]) { return; } var yea = parseInt(z[3], 10); var mon = 11; var dat = 31; if (z[4]) { mon = SHORT_MONTHS[z[4].substr(0, 3)]; dat = parseInt(z[5], 10) || 1; } var string = z[6] ? z[6] : '00:00:00' , t = parseTimeString(string); return [yea, mon, dat, t[1], t[2], t[3]]; } function getZone(dt, tz) { var utcMillis = typeof dt === 'number' ? dt : new Date(dt).getTime(); var t = tz; var zoneList = _this.zones[t]; // Follow links to get to an actual zone while (typeof zoneList === "string") { t = zoneList; zoneList = _this.zones[t]; } if (!zoneList) { // Backward-compat file hasn't loaded yet, try looking in there if (!_this.loadedZones.backward) { //This is for backward entries like "America/Fort_Wayne" that // getRegionForTimezone *thinks* it has a region file and zone // for (e.g., America => 'northamerica'), but in reality it's a // legacy zone we need the backward file for. _this.loadZoneFile('backward'); return getZone(dt, tz); } invalidTZError(t); } if (zoneList.length === 0) { throw new Error('No Zone found for "' + tz + '" on ' + dt); } //Do backwards lookup since most use cases deal with newer dates. for (var i = zoneList.length - 1; i >= 0; i--) { var z = zoneList[i]; if (z[3] && utcMillis > z[3]) break; } return zoneList[i+1]; } function getBasicOffset(time) { var off = parseTimeString(time) , adj = time.indexOf('-') === 0 ? -1 : 1; off = adj * (((off[1] * 60 + off[2]) * 60 + off[3]) * 1000); return off/60/1000; } //if isUTC is true, date is given in UTC, otherwise it's given // in local time (ie. date.getUTC*() returns local time components) function getRule(dt, zone, isUTC) { var date = typeof dt === 'number' ? new Date(dt) : dt; var ruleset = zone[1]; var basicOffset = zone[0]; //Convert a date to UTC. Depending on the 'type' parameter, the date // parameter may be: // // - `u`, `g`, `z`: already UTC (no adjustment). // // - `s`: standard time (adjust for time zone offset but not for DST) // // - `w`: wall clock time (adjust for both time zone and DST offset). // // DST adjustment is done using the rule given as third argument. var convertDateToUTC = function (date, type, rule) { var offset = 0; if (type === 'u' || type === 'g' || type === 'z') { // UTC offset = 0; } else if (type === 's') { // Standard Time offset = basicOffset; } else if (type === 'w' || !type) { // Wall Clock Time offset = getAdjustedOffset(basicOffset, rule); } else { throw("unknown type " + type); } offset *= 60 * 1000; // to millis return new Date(date.getTime() + offset); }; //Step 1: Find applicable rules for this year. // //Step 2: Sort the rules by effective date. // //Step 3: Check requested date to see if a rule has yet taken effect this year. If not, // //Step 4: Get the rules for the previous year. If there isn't an applicable rule for last year, then // there probably is no current time offset since they seem to explicitly turn off the offset // when someone stops observing DST. // // FIXME if this is not the case and we'll walk all the way back (ugh). // //Step 5: Sort the rules by effective date. //Step 6: Apply the most recent rule before the current time. var convertRuleToExactDateAndTime = function (yearAndRule, prevRule) { var year = yearAndRule[0] , rule = yearAndRule[1]; // Assume that the rule applies to the year of the given date. var hms = rule[5]; var effectiveDate; if (!EXACT_DATE_TIME[year]) EXACT_DATE_TIME[year] = {}; // Result for given parameters is already stored if (EXACT_DATE_TIME[year][rule]) effectiveDate = EXACT_DATE_TIME[year][rule]; else { //If we have a specific date, use that! if (!isNaN(rule[4])) { effectiveDate = new Date(Date.UTC(year, SHORT_MONTHS[rule[3]], rule[4], hms[1], hms[2], hms[3], 0)); } //Let's hunt for the date. else { var targetDay , operator; //Example: `lastThu` if (rule[4].substr(0, 4) === "last") { // Start at the last day of the month and work backward. effectiveDate = new Date(Date.UTC(year, SHORT_MONTHS[rule[3]] + 1, 1, hms[1] - 24, hms[2], hms[3], 0)); targetDay = SHORT_DAYS[rule[4].substr(4, 3)]; operator = "<="; } //Example: `Sun>=15` else { //Start at the specified date. effectiveDate = new Date(Date.UTC(year, SHORT_MONTHS[rule[3]], rule[4].substr(5), hms[1], hms[2], hms[3], 0)); targetDay = SHORT_DAYS[rule[4].substr(0, 3)]; operator = rule[4].substr(3, 2); } var ourDay = effectiveDate.getUTCDay(); //Go forwards. if (operator === ">=") { effectiveDate.setUTCDate(effectiveDate.getUTCDate() + (targetDay - ourDay + ((targetDay < ourDay) ? 7 : 0))); } //Go backwards. Looking for the last of a certain day, or operator is "<=" (less likely). else { effectiveDate.setUTCDate(effectiveDate.getUTCDate() + (targetDay - ourDay - ((targetDay > ourDay) ? 7 : 0))); } } EXACT_DATE_TIME[year][rule] = effectiveDate; } //If previous rule is given, correct for the fact that the starting time of the current // rule may be specified in local time. if (prevRule) { effectiveDate = convertDateToUTC(effectiveDate, hms[4], prevRule); } return effectiveDate; }; var findApplicableRules = function (year, ruleset) { var applicableRules = []; for (var i = 0; ruleset && i < ruleset.length; i++) { //Exclude future rules. if (ruleset[i][0] <= year && ( // Date is in a set range. ruleset[i][1] >= year || // Date is in an "only" year. (ruleset[i][0] === year && ruleset[i][1] === "only") || //We're in a range from the start year to infinity. ruleset[i][1] === "max" ) ) { //It's completely okay to have any number of matches here. // Normally we should only see two, but that doesn't preclude other numbers of matches. // These matches are applicable to this year. applicableRules.push([year, ruleset[i]]); } } return applicableRules; }; var compareDates = function (a, b, prev) { var year, rule; if (a.constructor !== Date) { year = a[0]; rule = a[1]; a = (!prev && EXACT_DATE_TIME[year] && EXACT_DATE_TIME[year][rule]) ? EXACT_DATE_TIME[year][rule] : convertRuleToExactDateAndTime(a, prev); } else if (prev) { a = convertDateToUTC(a, isUTC ? 'u' : 'w', prev); } if (b.constructor !== Date) { year = b[0]; rule = b[1]; b = (!prev && EXACT_DATE_TIME[year] && EXACT_DATE_TIME[year][rule]) ? EXACT_DATE_TIME[year][rule] : convertRuleToExactDateAndTime(b, prev); } else if (prev) { b = convertDateToUTC(b, isUTC ? 'u' : 'w', prev); } a = Number(a); b = Number(b); return a - b; }; var year = date.getUTCFullYear(); var applicableRules; applicableRules = findApplicableRules(year, _this.rules[ruleset]); applicableRules.push(date); //While sorting, the time zone in which the rule starting time is specified // is ignored. This is ok as long as the timespan between two DST changes is // larger than the DST offset, which is probably always true. // As the given date may indeed be close to a DST change, it may get sorted // to a wrong position (off by one), which is corrected below. applicableRules.sort(compareDates); //If there are not enough past DST rules... if (applicableRules.indexOf(date) < 2) { applicableRules = applicableRules.concat(findApplicableRules(year-1, _this.rules[ruleset])); applicableRules.sort(compareDates); } var pinpoint = applicableRules.indexOf(date); if (pinpoint > 1 && compareDates(date, applicableRules[pinpoint-1], applicableRules[pinpoint-2][1]) < 0) { //The previous rule does not really apply, take the one before that. return applicableRules[pinpoint - 2][1]; } else if (pinpoint > 0 && pinpoint < applicableRules.length - 1 && compareDates(date, applicableRules[pinpoint+1], applicableRules[pinpoint-1][1]) > 0) { //The next rule does already apply, take that one. return applicableRules[pinpoint + 1][1]; } else if (pinpoint === 0) { //No applicable rule found in this and in previous year. return null; } return applicableRules[pinpoint - 1][1]; } function getAdjustedOffset(off, rule) { return -Math.ceil(rule[6] - off); } function getAbbreviation(zone, rule) { var res; var base = zone[2]; if (base.indexOf('%s') > -1) { var repl; if (rule) { repl = rule[7] === '-' ? '' : rule[7]; } //FIXME: Right now just falling back to Standard -- // apparently ought to use the last valid rule, // although in practice that always ought to be Standard else { repl = 'S'; } res = base.replace('%s', repl); } else if (base.indexOf('/') > -1) { //Chose one of two alternative strings. res = base.split("/", 2)[rule[6] ? 1 : 0]; } else { res = base; } return res; } this.zoneFileBasePath; this.zoneFiles = ['africa', 'antarctica', 'asia', 'australasia', 'backward', 'etcetera', 'europe', 'northamerica', 'pacificnew', 'southamerica']; this.loadingSchemes = { PRELOAD_ALL: 'preloadAll', LAZY_LOAD: 'lazyLoad', MANUAL_LOAD: 'manualLoad' }; this.loadingScheme = this.loadingSchemes.LAZY_LOAD; this.loadedZones = {}; this.zones = {}; this.rules = {}; this.init = function (o) { var opts = { async: true } , def = this.defaultZoneFile = this.loadingScheme === this.loadingSchemes.PRELOAD_ALL ? this.zoneFiles : 'northamerica' , done = 0 , callbackFn; //Override default with any passed-in opts for (var p in o) { opts[p] = o[p]; } if (typeof def === 'string') { return this.loadZoneFile(def, opts); } //Wraps callback function in another one that makes // sure all files have been loaded. callbackFn = opts.callback; opts.callback = function () { done++; (done === def.length) && typeof callbackFn === 'function' && callbackFn(); }; for (var i = 0; i < def.length; i++) { this.loadZoneFile(def[i], opts); } }; //Get the zone files via XHR -- if the sync flag // is set to true, it's being called by the lazy-loading // mechanism, so the result needs to be returned inline. this.loadZoneFile = function (fileName, opts) { if (typeof this.zoneFileBasePath === 'undefined') { throw new Error('Please define a base path to your zone file directory -- timezoneJS.timezone.zoneFileBasePath.'); } //Ignore already loaded zones. if (this.loadedZones[fileName]) { return; } this.loadedZones[fileName] = true; return builtInLoadZoneFile(fileName, opts); }; this.loadZoneJSONData = function (url, sync) { var processData = function (data) { data = eval('('+ data +')'); for (var z in data.zones) { _this.zones[z] = data.zones[z]; } for (var r in data.rules) { _this.rules[r] = data.rules[r]; } }; return sync ? processData(_this.transport({ url : url, async : false })) : _this.transport({ url : url, success : processData }); }; this.loadZoneDataFromObject = function (data) { if (!data) { return; } for (var z in data.zones) { _this.zones[z] = data.zones[z]; } for (var r in data.rules) { _this.rules[r] = data.rules[r]; } }; this.getAllZones = function () { var arr = []; for (var z in this.zones) { arr.push(z); } return arr.sort(); }; this.parseZones = function (str) { var lines = str.split('\n') , arr = [] , chunk = '' , l , zone = null , rule = null; for (var i = 0; i < lines.length; i++) { l = lines[i]; if (l.match(/^\s/)) { l = "Zone " + zone + l; } l = l.split("#")[0]; if (l.length > 3) { arr = l.split(/\s+/); chunk = arr.shift(); //Ignore Leap. switch (chunk) { case 'Zone': zone = arr.shift(); if (!_this.zones[zone]) { _this.zones[zone] = []; } if (arr.length < 3) break; //Process zone right here and replace 3rd element with the processed array. arr.splice(3, arr.length, processZone(arr)); if (arr[3]) arr[3] = Date.UTC.apply(null, arr[3]); arr[0] = -getBasicOffset(arr[0]); _this.zones[zone].push(arr); break; case 'Rule': rule = arr.shift(); if (!_this.rules[rule]) { _this.rules[rule] = []; } //Parse int FROM year and TO year arr[0] = parseInt(arr[0], 10); arr[1] = parseInt(arr[1], 10) || arr[1]; //Parse time string AT arr[5] = parseTimeString(arr[5]); //Parse offset SAVE arr[6] = getBasicOffset(arr[6]); _this.rules[rule].push(arr); break; case 'Link': //No zones for these should already exist. if (_this.zones[arr[1]]) { throw new Error('Error with Link ' + arr[1] + '. Cannot create link of a preexisted zone.'); } //Create the link. _this.zones[arr[1]] = arr[0]; break; } } } return true; }; //Expose transport mechanism and allow overwrite. this.transport = _transport; this.getTzInfo = function (dt, tz, isUTC) { //Lazy-load any zones not yet loaded. if (this.loadingScheme === this.loadingSchemes.LAZY_LOAD) { //Get the correct region for the zone. var zoneFile = getRegionForTimezone(tz); if (!zoneFile) { throw new Error('Not a valid timezone ID.'); } if (!this.loadedZones[zoneFile]) { //Get the file and parse it -- use synchronous XHR. this.loadZoneFile(zoneFile); } } var z = getZone(dt, tz); var off = z[0]; //See if the offset needs adjustment. var rule = getRule(dt, z, isUTC); if (rule) { off = getAdjustedOffset(off, rule); } var abbr = getAbbreviation(z, rule); return { tzOffset: off, tzAbbr: abbr }; }; }; }).call(this);
JavaScript
/* Flot plugin that adds some extra symbols for plotting points. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The symbols are accessed as strings through the standard symbol options: series: { points: { symbol: "square" // or "diamond", "triangle", "cross" } } */ (function ($) { function processRawData(plot, series, datapoints) { // we normalize the area of each symbol so it is approximately the // same as a circle of the given radius var handlers = { square: function (ctx, x, y, radius, shadow) { // pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2 var size = radius * Math.sqrt(Math.PI) / 2; ctx.rect(x - size, y - size, size + size, size + size); }, diamond: function (ctx, x, y, radius, shadow) { // pi * r^2 = 2s^2 => s = r * sqrt(pi/2) var size = radius * Math.sqrt(Math.PI / 2); ctx.moveTo(x - size, y); ctx.lineTo(x, y - size); ctx.lineTo(x + size, y); ctx.lineTo(x, y + size); ctx.lineTo(x - size, y); }, triangle: function (ctx, x, y, radius, shadow) { // pi * r^2 = 1/2 * s^2 * sin (pi / 3) => s = r * sqrt(2 * pi / sin(pi / 3)) var size = radius * Math.sqrt(2 * Math.PI / Math.sin(Math.PI / 3)); var height = size * Math.sin(Math.PI / 3); ctx.moveTo(x - size/2, y + height/2); ctx.lineTo(x + size/2, y + height/2); if (!shadow) { ctx.lineTo(x, y - height/2); ctx.lineTo(x - size/2, y + height/2); } }, cross: function (ctx, x, y, radius, shadow) { // pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2 var size = radius * Math.sqrt(Math.PI) / 2; ctx.moveTo(x - size, y - size); ctx.lineTo(x + size, y + size); ctx.moveTo(x - size, y + size); ctx.lineTo(x + size, y - size); } }; var s = series.points.symbol; if (handlers[s]) series.points.symbol = handlers[s]; } function init(plot) { plot.hooks.processDatapoints.push(processRawData); } $.plot.plugins.push({ init: init, name: 'symbols', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for plotting textual data or categories. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. Consider a dataset like [["February", 34], ["March", 20], ...]. This plugin allows you to plot such a dataset directly. To enable it, you must specify mode: "categories" on the axis with the textual labels, e.g. $.plot("#placeholder", data, { xaxis: { mode: "categories" } }); By default, the labels are ordered as they are met in the data series. If you need a different ordering, you can specify "categories" on the axis options and list the categories there: xaxis: { mode: "categories", categories: ["February", "March", "April"] } If you need to customize the distances between the categories, you can specify "categories" as an object mapping labels to values xaxis: { mode: "categories", categories: { "February": 1, "March": 3, "April": 4 } } If you don't specify all categories, the remaining categories will be numbered from the max value plus 1 (with a spacing of 1 between each). Internally, the plugin works by transforming the input data through an auto- generated mapping where the first category becomes 0, the second 1, etc. Hence, a point like ["February", 34] becomes [0, 34] internally in Flot (this is visible in hover and click events that return numbers rather than the category labels). The plugin also overrides the tick generator to spit out the categories as ticks instead of the values. If you need to map a value back to its label, the mapping is always accessible as "categories" on the axis object, e.g. plot.getAxes().xaxis.categories. */ (function ($) { var options = { xaxis: { categories: null }, yaxis: { categories: null } }; function processRawData(plot, series, data, datapoints) { // if categories are enabled, we need to disable // auto-transformation to numbers so the strings are intact // for later processing var xCategories = series.xaxis.options.mode == "categories", yCategories = series.yaxis.options.mode == "categories"; if (!(xCategories || yCategories)) return; var format = datapoints.format; if (!format) { // FIXME: auto-detection should really not be defined here var s = series; format = []; format.push({ x: true, number: true, required: true }); format.push({ y: true, number: true, required: true }); if (s.bars.show || (s.lines.show && s.lines.fill)) { var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero)); format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale }); if (s.bars.horizontal) { delete format[format.length - 1].y; format[format.length - 1].x = true; } } datapoints.format = format; } for (var m = 0; m < format.length; ++m) { if (format[m].x && xCategories) format[m].number = false; if (format[m].y && yCategories) format[m].number = false; } } function getNextIndex(categories) { var index = -1; for (var v in categories) if (categories[v] > index) index = categories[v]; return index + 1; } function categoriesTickGenerator(axis) { var res = []; for (var label in axis.categories) { var v = axis.categories[label]; if (v >= axis.min && v <= axis.max) res.push([v, label]); } res.sort(function (a, b) { return a[0] - b[0]; }); return res; } function setupCategoriesForAxis(series, axis, datapoints) { if (series[axis].options.mode != "categories") return; if (!series[axis].categories) { // parse options var c = {}, o = series[axis].options.categories || {}; if ($.isArray(o)) { for (var i = 0; i < o.length; ++i) c[o[i]] = i; } else { for (var v in o) c[v] = o[v]; } series[axis].categories = c; } // fix ticks if (!series[axis].options.ticks) series[axis].options.ticks = categoriesTickGenerator; transformPointsOnAxis(datapoints, axis, series[axis].categories); } function transformPointsOnAxis(datapoints, axis, categories) { // go through the points, transforming them var points = datapoints.points, ps = datapoints.pointsize, format = datapoints.format, formatColumn = axis.charAt(0), index = getNextIndex(categories); for (var i = 0; i < points.length; i += ps) { if (points[i] == null) continue; for (var m = 0; m < ps; ++m) { var val = points[i + m]; if (val == null || !format[m][formatColumn]) continue; if (!(val in categories)) { categories[val] = index; ++index; } points[i + m] = categories[val]; } } } function processDatapoints(plot, series, datapoints) { setupCategoriesForAxis(series, "xaxis", datapoints); setupCategoriesForAxis(series, "yaxis", datapoints); } function init(plot) { plot.hooks.processRawData.push(processRawData); plot.hooks.processDatapoints.push(processDatapoints); } $.plot.plugins.push({ init: init, options: options, name: 'categories', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for automatically redrawing plots as the placeholder resizes. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. It works by listening for changes on the placeholder div (through the jQuery resize event plugin) - if the size changes, it will redraw the plot. There are no options. If you need to disable the plugin for some plots, you can just fix the size of their placeholders. */ /* Inline dependency: * jQuery resize event - v1.1 - 3/14/2010 * http://benalman.com/projects/jquery-resize-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function($,t,n){function p(){for(var n=r.length-1;n>=0;n--){var o=$(r[n]);if(o[0]==t||o.is(":visible")){var h=o.width(),d=o.height(),v=o.data(a);!v||h===v.w&&d===v.h?i[f]=i[l]:(i[f]=i[c],o.trigger(u,[v.w=h,v.h=d]))}else v=o.data(a),v.w=0,v.h=0}s!==null&&(s=t.requestAnimationFrame(p))}var r=[],i=$.resize=$.extend($.resize,{}),s,o="setTimeout",u="resize",a=u+"-special-event",f="delay",l="pendingDelay",c="activeDelay",h="throttleWindow";i[l]=250,i[c]=20,i[f]=i[l],i[h]=!0,$.event.special[u]={setup:function(){if(!i[h]&&this[o])return!1;var t=$(this);r.push(this),t.data(a,{w:t.width(),h:t.height()}),r.length===1&&(s=n,p())},teardown:function(){if(!i[h]&&this[o])return!1;var t=$(this);for(var n=r.length-1;n>=0;n--)if(r[n]==this){r.splice(n,1);break}t.removeData(a),r.length||(cancelAnimationFrame(s),s=null)},add:function(t){function s(t,i,s){var o=$(this),u=o.data(a);u.w=i!==n?i:o.width(),u.h=s!==n?s:o.height(),r.apply(this,arguments)}if(!i[h]&&this[o])return!1;var r;if($.isFunction(t))return r=t,s;r=t.handler,t.handler=s}},t.requestAnimationFrame||(t.requestAnimationFrame=function(){return t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||t.oRequestAnimationFrame||t.msRequestAnimationFrame||function(e,n){return t.setTimeout(e,i[f])}}()),t.cancelAnimationFrame||(t.cancelAnimationFrame=function(){return t.webkitCancelRequestAnimationFrame||t.mozCancelRequestAnimationFrame||t.oCancelRequestAnimationFrame||t.msCancelRequestAnimationFrame||clearTimeout}())})(jQuery,this); (function ($) { var options = { }; // no options function init(plot) { function onResize() { var placeholder = plot.getPlaceholder(); // somebody might have hidden us and we can't plot // when we don't have the dimensions if (placeholder.width() == 0 || placeholder.height() == 0) return; plot.resize(); plot.setupGrid(); plot.draw(); } function bindEvents(plot, eventHolder) { plot.getPlaceholder().resize(onResize); } function shutdown(plot, eventHolder) { plot.getPlaceholder().unbind("resize", onResize); } plot.hooks.bindEvents.push(bindEvents); plot.hooks.shutdown.push(shutdown); } $.plot.plugins.push({ init: init, options: options, name: 'resize', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for thresholding data. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The plugin supports these options: series: { threshold: { below: number color: colorspec } } It can also be applied to a single series, like this: $.plot( $("#placeholder"), [{ data: [ ... ], threshold: { ... } }]) An array can be passed for multiple thresholding, like this: threshold: [{ below: number1 color: color1 },{ below: number2 color: color2 }] These multiple threshold objects can be passed in any order since they are sorted by the processing function. The data points below "below" are drawn with the specified color. This makes it easy to mark points below 0, e.g. for budget data. Internally, the plugin works by splitting the data into two series, above and below the threshold. The extra series below the threshold will have its label cleared and the special "originSeries" attribute set to the original series. You may need to check for this in hover events. */ (function ($) { var options = { series: { threshold: null } // or { below: number, color: color spec} }; function init(plot) { function thresholdData(plot, s, datapoints, below, color) { var ps = datapoints.pointsize, i, x, y, p, prevp, thresholded = $.extend({}, s); // note: shallow copy thresholded.datapoints = { points: [], pointsize: ps, format: datapoints.format }; thresholded.label = null; thresholded.color = color; thresholded.threshold = null; thresholded.originSeries = s; thresholded.data = []; var origpoints = datapoints.points, addCrossingPoints = s.lines.show; var threspoints = []; var newpoints = []; var m; for (i = 0; i < origpoints.length; i += ps) { x = origpoints[i]; y = origpoints[i + 1]; prevp = p; if (y < below) p = threspoints; else p = newpoints; if (addCrossingPoints && prevp != p && x != null && i > 0 && origpoints[i - ps] != null) { var interx = x + (below - y) * (x - origpoints[i - ps]) / (y - origpoints[i - ps + 1]); prevp.push(interx); prevp.push(below); for (m = 2; m < ps; ++m) prevp.push(origpoints[i + m]); p.push(null); // start new segment p.push(null); for (m = 2; m < ps; ++m) p.push(origpoints[i + m]); p.push(interx); p.push(below); for (m = 2; m < ps; ++m) p.push(origpoints[i + m]); } p.push(x); p.push(y); for (m = 2; m < ps; ++m) p.push(origpoints[i + m]); } datapoints.points = newpoints; thresholded.datapoints.points = threspoints; if (thresholded.datapoints.points.length > 0) { var origIndex = $.inArray(s, plot.getData()); // Insert newly-generated series right after original one (to prevent it from becoming top-most) plot.getData().splice(origIndex + 1, 0, thresholded); } // FIXME: there are probably some edge cases left in bars } function processThresholds(plot, s, datapoints) { if (!s.threshold) return; if (s.threshold instanceof Array) { s.threshold.sort(function(a, b) { return a.below - b.below; }); $(s.threshold).each(function(i, th) { thresholdData(plot, s, datapoints, th.below, th.color); }); } else { thresholdData(plot, s, datapoints, s.threshold.below, s.threshold.color); } } plot.hooks.processDatapoints.push(processThresholds); } $.plot.plugins.push({ init: init, options: options, name: 'threshold', version: '1.2' }); })(jQuery);
JavaScript
/* Flot plugin for selecting regions of a plot. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The plugin supports these options: selection: { mode: null or "x" or "y" or "xy", color: color, shape: "round" or "miter" or "bevel", minSize: number of pixels } Selection support is enabled by setting the mode to one of "x", "y" or "xy". In "x" mode, the user will only be able to specify the x range, similarly for "y" mode. For "xy", the selection becomes a rectangle where both ranges can be specified. "color" is color of the selection (if you need to change the color later on, you can get to it with plot.getOptions().selection.color). "shape" is the shape of the corners of the selection. "minSize" is the minimum size a selection can be in pixels. This value can be customized to determine the smallest size a selection can be and still have the selection rectangle be displayed. When customizing this value, the fact that it refers to pixels, not axis units must be taken into account. Thus, for example, if there is a bar graph in time mode with BarWidth set to 1 minute, setting "minSize" to 1 will not make the minimum selection size 1 minute, but rather 1 pixel. Note also that setting "minSize" to 0 will prevent "plotunselected" events from being fired when the user clicks the mouse without dragging. When selection support is enabled, a "plotselected" event will be emitted on the DOM element you passed into the plot function. The event handler gets a parameter with the ranges selected on the axes, like this: placeholder.bind( "plotselected", function( event, ranges ) { alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to) // similar for yaxis - with multiple axes, the extra ones are in // x2axis, x3axis, ... }); The "plotselected" event is only fired when the user has finished making the selection. A "plotselecting" event is fired during the process with the same parameters as the "plotselected" event, in case you want to know what's happening while it's happening, A "plotunselected" event with no arguments is emitted when the user clicks the mouse to remove the selection. As stated above, setting "minSize" to 0 will destroy this behavior. The plugin allso adds the following methods to the plot object: - setSelection( ranges, preventEvent ) Set the selection rectangle. The passed in ranges is on the same form as returned in the "plotselected" event. If the selection mode is "x", you should put in either an xaxis range, if the mode is "y" you need to put in an yaxis range and both xaxis and yaxis if the selection mode is "xy", like this: setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } }); setSelection will trigger the "plotselected" event when called. If you don't want that to happen, e.g. if you're inside a "plotselected" handler, pass true as the second parameter. If you are using multiple axes, you can specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of xaxis, the plugin picks the first one it sees. - clearSelection( preventEvent ) Clear the selection rectangle. Pass in true to avoid getting a "plotunselected" event. - getSelection() Returns the current selection in the same format as the "plotselected" event. If there's currently no selection, the function returns null. */ (function ($) { function init(plot) { var selection = { first: { x: -1, y: -1}, second: { x: -1, y: -1}, show: false, active: false }; // FIXME: The drag handling implemented here should be // abstracted out, there's some similar code from a library in // the navigation plugin, this should be massaged a bit to fit // the Flot cases here better and reused. Doing this would // make this plugin much slimmer. var savedhandlers = {}; var mouseUpHandler = null; function onMouseMove(e) { if (selection.active) { updateSelection(e); plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]); } } function onMouseDown(e) { if (e.which != 1) // only accept left-click return; // cancel out any text selections document.body.focus(); // prevent text selection and drag in old-school browsers if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) { savedhandlers.onselectstart = document.onselectstart; document.onselectstart = function () { return false; }; } if (document.ondrag !== undefined && savedhandlers.ondrag == null) { savedhandlers.ondrag = document.ondrag; document.ondrag = function () { return false; }; } setSelectionPos(selection.first, e); selection.active = true; // this is a bit silly, but we have to use a closure to be // able to whack the same handler again mouseUpHandler = function (e) { onMouseUp(e); }; $(document).one("mouseup", mouseUpHandler); } function onMouseUp(e) { mouseUpHandler = null; // revert drag stuff for old-school browsers if (document.onselectstart !== undefined) document.onselectstart = savedhandlers.onselectstart; if (document.ondrag !== undefined) document.ondrag = savedhandlers.ondrag; // no more dragging selection.active = false; updateSelection(e); if (selectionIsSane()) triggerSelectedEvent(); else { // this counts as a clear plot.getPlaceholder().trigger("plotunselected", [ ]); plot.getPlaceholder().trigger("plotselecting", [ null ]); } return false; } function getSelection() { if (!selectionIsSane()) return null; if (!selection.show) return null; var r = {}, c1 = selection.first, c2 = selection.second; $.each(plot.getAxes(), function (name, axis) { if (axis.used) { var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]); r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) }; } }); return r; } function triggerSelectedEvent() { var r = getSelection(); plot.getPlaceholder().trigger("plotselected", [ r ]); // backwards-compat stuff, to be removed in future if (r.xaxis && r.yaxis) plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]); } function clamp(min, value, max) { return value < min ? min: (value > max ? max: value); } function setSelectionPos(pos, e) { var o = plot.getOptions(); var offset = plot.getPlaceholder().offset(); var plotOffset = plot.getPlotOffset(); pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width()); pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height()); if (o.selection.mode == "y") pos.x = pos == selection.first ? 0 : plot.width(); if (o.selection.mode == "x") pos.y = pos == selection.first ? 0 : plot.height(); } function updateSelection(pos) { if (pos.pageX == null) return; setSelectionPos(selection.second, pos); if (selectionIsSane()) { selection.show = true; plot.triggerRedrawOverlay(); } else clearSelection(true); } function clearSelection(preventEvent) { if (selection.show) { selection.show = false; plot.triggerRedrawOverlay(); if (!preventEvent) plot.getPlaceholder().trigger("plotunselected", [ ]); } } // function taken from markings support in Flot function extractRange(ranges, coord) { var axis, from, to, key, axes = plot.getAxes(); for (var k in axes) { axis = axes[k]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; } function setSelection(ranges, preventEvent) { var axis, range, o = plot.getOptions(); if (o.selection.mode == "y") { selection.first.x = 0; selection.second.x = plot.width(); } else { range = extractRange(ranges, "x"); selection.first.x = range.axis.p2c(range.from); selection.second.x = range.axis.p2c(range.to); } if (o.selection.mode == "x") { selection.first.y = 0; selection.second.y = plot.height(); } else { range = extractRange(ranges, "y"); selection.first.y = range.axis.p2c(range.from); selection.second.y = range.axis.p2c(range.to); } selection.show = true; plot.triggerRedrawOverlay(); if (!preventEvent && selectionIsSane()) triggerSelectedEvent(); } function selectionIsSane() { var minSize = plot.getOptions().selection.minSize; return Math.abs(selection.second.x - selection.first.x) >= minSize && Math.abs(selection.second.y - selection.first.y) >= minSize; } plot.clearSelection = clearSelection; plot.setSelection = setSelection; plot.getSelection = getSelection; plot.hooks.bindEvents.push(function(plot, eventHolder) { var o = plot.getOptions(); if (o.selection.mode != null) { eventHolder.mousemove(onMouseMove); eventHolder.mousedown(onMouseDown); } }); plot.hooks.drawOverlay.push(function (plot, ctx) { // draw selection if (selection.show && selectionIsSane()) { var plotOffset = plot.getPlotOffset(); var o = plot.getOptions(); ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); var c = $.color.parse(o.selection.color); ctx.strokeStyle = c.scale('a', 0.8).toString(); ctx.lineWidth = 1; ctx.lineJoin = o.selection.shape; ctx.fillStyle = c.scale('a', 0.4).toString(); var x = Math.min(selection.first.x, selection.second.x) + 0.5, y = Math.min(selection.first.y, selection.second.y) + 0.5, w = Math.abs(selection.second.x - selection.first.x) - 1, h = Math.abs(selection.second.y - selection.first.y) - 1; ctx.fillRect(x, y, w, h); ctx.strokeRect(x, y, w, h); ctx.restore(); } }); plot.hooks.shutdown.push(function (plot, eventHolder) { eventHolder.unbind("mousemove", onMouseMove); eventHolder.unbind("mousedown", onMouseDown); if (mouseUpHandler) $(document).unbind("mouseup", mouseUpHandler); }); } $.plot.plugins.push({ init: init, options: { selection: { mode: null, // one of null, "x", "y" or "xy" color: "#e8cfac", shape: "round", // one of "round", "miter", or "bevel" minSize: 5 // minimum number of pixels } }, name: 'selection', version: '1.1' }); })(jQuery);
JavaScript
/* Plugin for jQuery for working with colors. * * Version 1.1. * * Inspiration from jQuery color animation plugin by John Resig. * * Released under the MIT license by Ole Laursen, October 2009. * * Examples: * * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString() * var c = $.color.extract($("#mydiv"), 'background-color'); * console.log(c.r, c.g, c.b, c.a); * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)" * * Note that .scale() and .add() return the same modified object * instead of making a new one. * * V. 1.1: Fix error handling so e.g. parsing an empty string does * produce a color rather than just crashing. */ (function($) { $.color = {}; // construct color object with some convenient chainable helpers $.color.make = function (r, g, b, a) { var o = {}; o.r = r || 0; o.g = g || 0; o.b = b || 0; o.a = a != null ? a : 1; o.add = function (c, d) { for (var i = 0; i < c.length; ++i) o[c.charAt(i)] += d; return o.normalize(); }; o.scale = function (c, f) { for (var i = 0; i < c.length; ++i) o[c.charAt(i)] *= f; return o.normalize(); }; o.toString = function () { if (o.a >= 1.0) { return "rgb("+[o.r, o.g, o.b].join(",")+")"; } else { return "rgba("+[o.r, o.g, o.b, o.a].join(",")+")"; } }; o.normalize = function () { function clamp(min, value, max) { return value < min ? min: (value > max ? max: value); } o.r = clamp(0, parseInt(o.r), 255); o.g = clamp(0, parseInt(o.g), 255); o.b = clamp(0, parseInt(o.b), 255); o.a = clamp(0, o.a, 1); return o; }; o.clone = function () { return $.color.make(o.r, o.b, o.g, o.a); }; return o.normalize(); } // extract CSS color property from element, going up in the DOM // if it's "transparent" $.color.extract = function (elem, css) { var c; do { c = elem.css(css).toLowerCase(); // keep going until we find an element that has color, or // we hit the body or root (have no parent) if (c != '' && c != 'transparent') break; elem = elem.parent(); } while (elem.length && !$.nodeName(elem.get(0), "body")); // catch Safari's way of signalling transparent if (c == "rgba(0, 0, 0, 0)") c = "transparent"; return $.color.parse(c); } // parse CSS color string (like "rgb(10, 32, 43)" or "#fff"), // returns color object, if parsing failed, you get black (0, 0, // 0) out $.color.parse = function (str) { var res, m = $.color.make; // Look for rgb(num,num,num) if (res = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str)) return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10)); // Look for rgba(num,num,num,num) if (res = /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(str)) return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10), parseFloat(res[4])); // Look for rgb(num%,num%,num%) if (res = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str)) return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55); // Look for rgba(num%,num%,num%,num) if (res = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55, parseFloat(res[4])); // Look for #a0b1c2 if (res = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str)) return m(parseInt(res[1], 16), parseInt(res[2], 16), parseInt(res[3], 16)); // Look for #fff if (res = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str)) return m(parseInt(res[1]+res[1], 16), parseInt(res[2]+res[2], 16), parseInt(res[3]+res[3], 16)); // Otherwise, we're most likely dealing with a named color var name = $.trim(str).toLowerCase(); if (name == "transparent") return m(255, 255, 255, 0); else { // default to black res = lookupColors[name] || [0, 0, 0]; return m(res[0], res[1], res[2]); } } var lookupColors = { aqua:[0,255,255], azure:[240,255,255], beige:[245,245,220], black:[0,0,0], blue:[0,0,255], brown:[165,42,42], cyan:[0,255,255], darkblue:[0,0,139], darkcyan:[0,139,139], darkgrey:[169,169,169], darkgreen:[0,100,0], darkkhaki:[189,183,107], darkmagenta:[139,0,139], darkolivegreen:[85,107,47], darkorange:[255,140,0], darkorchid:[153,50,204], darkred:[139,0,0], darksalmon:[233,150,122], darkviolet:[148,0,211], fuchsia:[255,0,255], gold:[255,215,0], green:[0,128,0], indigo:[75,0,130], khaki:[240,230,140], lightblue:[173,216,230], lightcyan:[224,255,255], lightgreen:[144,238,144], lightgrey:[211,211,211], lightpink:[255,182,193], lightyellow:[255,255,224], lime:[0,255,0], magenta:[255,0,255], maroon:[128,0,0], navy:[0,0,128], olive:[128,128,0], orange:[255,165,0], pink:[255,192,203], purple:[128,0,128], violet:[128,0,128], red:[255,0,0], silver:[192,192,192], white:[255,255,255], yellow:[255,255,0] }; })(jQuery);
JavaScript
// Copyright 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Known Issues: // // * Patterns only support repeat. // * Radial gradient are not implemented. The VML version of these look very // different from the canvas one. // * Clipping paths are not implemented. // * Coordsize. The width and height attribute have higher priority than the // width and height style values which isn't correct. // * Painting mode isn't implemented. // * Canvas width/height should is using content-box by default. IE in // Quirks mode will draw the canvas using border-box. Either change your // doctype to HTML5 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) // or use Box Sizing Behavior from WebFX // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) // * Non uniform scaling does not correctly scale strokes. // * Filling very large shapes (above 5000 points) is buggy. // * Optimize. There is always room for speed improvements. // Only add this code if we do not already have a canvas implementation if (!document.createElement('canvas').getContext) { (function() { // alias some functions to make (compiled) code shorter var m = Math; var mr = m.round; var ms = m.sin; var mc = m.cos; var abs = m.abs; var sqrt = m.sqrt; // this is used for sub pixel precision var Z = 10; var Z2 = Z / 2; var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; /** * This funtion is assigned to the <canvas> elements as element.getContext(). * @this {HTMLElement} * @return {CanvasRenderingContext2D_} */ function getContext() { return this.context_ || (this.context_ = new CanvasRenderingContext2D_(this)); } var slice = Array.prototype.slice; /** * Binds a function to an object. The returned function will always use the * passed in {@code obj} as {@code this}. * * Example: * * g = bind(f, obj, a, b) * g(c, d) // will do f.call(obj, a, b, c, d) * * @param {Function} f The function to bind the object to * @param {Object} obj The object that should act as this when the function * is called * @param {*} var_args Rest arguments that will be used as the initial * arguments when the function is called * @return {Function} A new function that has bound this */ function bind(f, obj, var_args) { var a = slice.call(arguments, 2); return function() { return f.apply(obj, a.concat(slice.call(arguments))); }; } function encodeHtmlAttribute(s) { return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); } function addNamespace(doc, prefix, urn) { if (!doc.namespaces[prefix]) { doc.namespaces.add(prefix, urn, '#default#VML'); } } function addNamespacesAndStylesheet(doc) { addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); // Setup default CSS. Only add one style sheet per document if (!doc.styleSheets['ex_canvas_']) { var ss = doc.createStyleSheet(); ss.owningElement.id = 'ex_canvas_'; ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + // default size is 300x150 in Gecko and Opera 'text-align:left;width:300px;height:150px}'; } } // Add namespaces and stylesheet at startup. addNamespacesAndStylesheet(document); var G_vmlCanvasManager_ = { init: function(opt_doc) { var doc = opt_doc || document; // Create a dummy element so that IE will allow canvas elements to be // recognized. doc.createElement('canvas'); doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); }, init_: function(doc) { // find all canvas elements var els = doc.getElementsByTagName('canvas'); for (var i = 0; i < els.length; i++) { this.initElement(els[i]); } }, /** * Public initializes a canvas element so that it can be used as canvas * element from now on. This is called automatically before the page is * loaded but if you are creating elements using createElement you need to * make sure this is called on the element. * @param {HTMLElement} el The canvas element to initialize. * @return {HTMLElement} the element that was created. */ initElement: function(el) { if (!el.getContext) { el.getContext = getContext; // Add namespaces and stylesheet to document of the element. addNamespacesAndStylesheet(el.ownerDocument); // Remove fallback content. There is no way to hide text nodes so we // just remove all childNodes. We could hide all elements and remove // text nodes but who really cares about the fallback content. el.innerHTML = ''; // do not use inline function because that will leak memory el.attachEvent('onpropertychange', onPropertyChange); el.attachEvent('onresize', onResize); var attrs = el.attributes; if (attrs.width && attrs.width.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setWidth_(attrs.width.nodeValue); el.style.width = attrs.width.nodeValue + 'px'; } else { el.width = el.clientWidth; } if (attrs.height && attrs.height.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setHeight_(attrs.height.nodeValue); el.style.height = attrs.height.nodeValue + 'px'; } else { el.height = el.clientHeight; } //el.getContext().setCoordsize_() } return el; } }; function onPropertyChange(e) { var el = e.srcElement; switch (e.propertyName) { case 'width': el.getContext().clearRect(); el.style.width = el.attributes.width.nodeValue + 'px'; // In IE8 this does not trigger onresize. el.firstChild.style.width = el.clientWidth + 'px'; break; case 'height': el.getContext().clearRect(); el.style.height = el.attributes.height.nodeValue + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; break; } } function onResize(e) { var el = e.srcElement; if (el.firstChild) { el.firstChild.style.width = el.clientWidth + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; } } G_vmlCanvasManager_.init(); // precompute "00" to "FF" var decToHex = []; for (var i = 0; i < 16; i++) { for (var j = 0; j < 16; j++) { decToHex[i * 16 + j] = i.toString(16) + j.toString(16); } } function createMatrixIdentity() { return [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; } function matrixMultiply(m1, m2) { var result = createMatrixIdentity(); for (var x = 0; x < 3; x++) { for (var y = 0; y < 3; y++) { var sum = 0; for (var z = 0; z < 3; z++) { sum += m1[x][z] * m2[z][y]; } result[x][y] = sum; } } return result; } function copyState(o1, o2) { o2.fillStyle = o1.fillStyle; o2.lineCap = o1.lineCap; o2.lineJoin = o1.lineJoin; o2.lineWidth = o1.lineWidth; o2.miterLimit = o1.miterLimit; o2.shadowBlur = o1.shadowBlur; o2.shadowColor = o1.shadowColor; o2.shadowOffsetX = o1.shadowOffsetX; o2.shadowOffsetY = o1.shadowOffsetY; o2.strokeStyle = o1.strokeStyle; o2.globalAlpha = o1.globalAlpha; o2.font = o1.font; o2.textAlign = o1.textAlign; o2.textBaseline = o1.textBaseline; o2.arcScaleX_ = o1.arcScaleX_; o2.arcScaleY_ = o1.arcScaleY_; o2.lineScale_ = o1.lineScale_; } var colorData = { aliceblue: '#F0F8FF', antiquewhite: '#FAEBD7', aquamarine: '#7FFFD4', azure: '#F0FFFF', beige: '#F5F5DC', bisque: '#FFE4C4', black: '#000000', blanchedalmond: '#FFEBCD', blueviolet: '#8A2BE2', brown: '#A52A2A', burlywood: '#DEB887', cadetblue: '#5F9EA0', chartreuse: '#7FFF00', chocolate: '#D2691E', coral: '#FF7F50', cornflowerblue: '#6495ED', cornsilk: '#FFF8DC', crimson: '#DC143C', cyan: '#00FFFF', darkblue: '#00008B', darkcyan: '#008B8B', darkgoldenrod: '#B8860B', darkgray: '#A9A9A9', darkgreen: '#006400', darkgrey: '#A9A9A9', darkkhaki: '#BDB76B', darkmagenta: '#8B008B', darkolivegreen: '#556B2F', darkorange: '#FF8C00', darkorchid: '#9932CC', darkred: '#8B0000', darksalmon: '#E9967A', darkseagreen: '#8FBC8F', darkslateblue: '#483D8B', darkslategray: '#2F4F4F', darkslategrey: '#2F4F4F', darkturquoise: '#00CED1', darkviolet: '#9400D3', deeppink: '#FF1493', deepskyblue: '#00BFFF', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1E90FF', firebrick: '#B22222', floralwhite: '#FFFAF0', forestgreen: '#228B22', gainsboro: '#DCDCDC', ghostwhite: '#F8F8FF', gold: '#FFD700', goldenrod: '#DAA520', grey: '#808080', greenyellow: '#ADFF2F', honeydew: '#F0FFF0', hotpink: '#FF69B4', indianred: '#CD5C5C', indigo: '#4B0082', ivory: '#FFFFF0', khaki: '#F0E68C', lavender: '#E6E6FA', lavenderblush: '#FFF0F5', lawngreen: '#7CFC00', lemonchiffon: '#FFFACD', lightblue: '#ADD8E6', lightcoral: '#F08080', lightcyan: '#E0FFFF', lightgoldenrodyellow: '#FAFAD2', lightgreen: '#90EE90', lightgrey: '#D3D3D3', lightpink: '#FFB6C1', lightsalmon: '#FFA07A', lightseagreen: '#20B2AA', lightskyblue: '#87CEFA', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#B0C4DE', lightyellow: '#FFFFE0', limegreen: '#32CD32', linen: '#FAF0E6', magenta: '#FF00FF', mediumaquamarine: '#66CDAA', mediumblue: '#0000CD', mediumorchid: '#BA55D3', mediumpurple: '#9370DB', mediumseagreen: '#3CB371', mediumslateblue: '#7B68EE', mediumspringgreen: '#00FA9A', mediumturquoise: '#48D1CC', mediumvioletred: '#C71585', midnightblue: '#191970', mintcream: '#F5FFFA', mistyrose: '#FFE4E1', moccasin: '#FFE4B5', navajowhite: '#FFDEAD', oldlace: '#FDF5E6', olivedrab: '#6B8E23', orange: '#FFA500', orangered: '#FF4500', orchid: '#DA70D6', palegoldenrod: '#EEE8AA', palegreen: '#98FB98', paleturquoise: '#AFEEEE', palevioletred: '#DB7093', papayawhip: '#FFEFD5', peachpuff: '#FFDAB9', peru: '#CD853F', pink: '#FFC0CB', plum: '#DDA0DD', powderblue: '#B0E0E6', rosybrown: '#BC8F8F', royalblue: '#4169E1', saddlebrown: '#8B4513', salmon: '#FA8072', sandybrown: '#F4A460', seagreen: '#2E8B57', seashell: '#FFF5EE', sienna: '#A0522D', skyblue: '#87CEEB', slateblue: '#6A5ACD', slategray: '#708090', slategrey: '#708090', snow: '#FFFAFA', springgreen: '#00FF7F', steelblue: '#4682B4', tan: '#D2B48C', thistle: '#D8BFD8', tomato: '#FF6347', turquoise: '#40E0D0', violet: '#EE82EE', wheat: '#F5DEB3', whitesmoke: '#F5F5F5', yellowgreen: '#9ACD32' }; function getRgbHslContent(styleString) { var start = styleString.indexOf('(', 3); var end = styleString.indexOf(')', start + 1); var parts = styleString.substring(start + 1, end).split(','); // add alpha if needed if (parts.length != 4 || styleString.charAt(3) != 'a') { parts[3] = 1; } return parts; } function percent(s) { return parseFloat(s) / 100; } function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); } function hslToRgb(parts){ var r, g, b, h, s, l; h = parseFloat(parts[0]) / 360 % 360; if (h < 0) h++; s = clamp(percent(parts[1]), 0, 1); l = clamp(percent(parts[2]), 0, 1); if (s == 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return '#' + decToHex[Math.floor(r * 255)] + decToHex[Math.floor(g * 255)] + decToHex[Math.floor(b * 255)]; } function hueToRgb(m1, m2, h) { if (h < 0) h++; if (h > 1) h--; if (6 * h < 1) return m1 + (m2 - m1) * 6 * h; else if (2 * h < 1) return m2; else if (3 * h < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6; else return m1; } var processStyleCache = {}; function processStyle(styleString) { if (styleString in processStyleCache) { return processStyleCache[styleString]; } var str, alpha = 1; styleString = String(styleString); if (styleString.charAt(0) == '#') { str = styleString; } else if (/^rgb/.test(styleString)) { var parts = getRgbHslContent(styleString); var str = '#', n; for (var i = 0; i < 3; i++) { if (parts[i].indexOf('%') != -1) { n = Math.floor(percent(parts[i]) * 255); } else { n = +parts[i]; } str += decToHex[clamp(n, 0, 255)]; } alpha = +parts[3]; } else if (/^hsl/.test(styleString)) { var parts = getRgbHslContent(styleString); str = hslToRgb(parts); alpha = parts[3]; } else { str = colorData[styleString] || styleString; } return processStyleCache[styleString] = {color: str, alpha: alpha}; } var DEFAULT_STYLE = { style: 'normal', variant: 'normal', weight: 'normal', size: 10, family: 'sans-serif' }; // Internal text style cache var fontStyleCache = {}; function processFontStyle(styleString) { if (fontStyleCache[styleString]) { return fontStyleCache[styleString]; } var el = document.createElement('div'); var style = el.style; try { style.font = styleString; } catch (ex) { // Ignore failures to set to invalid font. } return fontStyleCache[styleString] = { style: style.fontStyle || DEFAULT_STYLE.style, variant: style.fontVariant || DEFAULT_STYLE.variant, weight: style.fontWeight || DEFAULT_STYLE.weight, size: style.fontSize || DEFAULT_STYLE.size, family: style.fontFamily || DEFAULT_STYLE.family }; } function getComputedStyle(style, element) { var computedStyle = {}; for (var p in style) { computedStyle[p] = style[p]; } // Compute the size var canvasFontSize = parseFloat(element.currentStyle.fontSize), fontSize = parseFloat(style.size); if (typeof style.size == 'number') { computedStyle.size = style.size; } else if (style.size.indexOf('px') != -1) { computedStyle.size = fontSize; } else if (style.size.indexOf('em') != -1) { computedStyle.size = canvasFontSize * fontSize; } else if(style.size.indexOf('%') != -1) { computedStyle.size = (canvasFontSize / 100) * fontSize; } else if (style.size.indexOf('pt') != -1) { computedStyle.size = fontSize / .75; } else { computedStyle.size = canvasFontSize; } // Different scaling between normal text and VML text. This was found using // trial and error to get the same size as non VML text. computedStyle.size *= 0.981; return computedStyle; } function buildStyle(style) { return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + style.size + 'px ' + style.family; } var lineCapMap = { 'butt': 'flat', 'round': 'round' }; function processLineCap(lineCap) { return lineCapMap[lineCap] || 'square'; } /** * This class implements CanvasRenderingContext2D interface as described by * the WHATWG. * @param {HTMLElement} canvasElement The element that the 2D context should * be associated with */ function CanvasRenderingContext2D_(canvasElement) { this.m_ = createMatrixIdentity(); this.mStack_ = []; this.aStack_ = []; this.currentPath_ = []; // Canvas context properties this.strokeStyle = '#000'; this.fillStyle = '#000'; this.lineWidth = 1; this.lineJoin = 'miter'; this.lineCap = 'butt'; this.miterLimit = Z * 1; this.globalAlpha = 1; this.font = '10px sans-serif'; this.textAlign = 'left'; this.textBaseline = 'alphabetic'; this.canvas = canvasElement; var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; var el = canvasElement.ownerDocument.createElement('div'); el.style.cssText = cssText; canvasElement.appendChild(el); var overlayEl = el.cloneNode(false); // Use a non transparent background. overlayEl.style.backgroundColor = 'red'; overlayEl.style.filter = 'alpha(opacity=0)'; canvasElement.appendChild(overlayEl); this.element_ = el; this.arcScaleX_ = 1; this.arcScaleY_ = 1; this.lineScale_ = 1; } var contextPrototype = CanvasRenderingContext2D_.prototype; contextPrototype.clearRect = function() { if (this.textMeasureEl_) { this.textMeasureEl_.removeNode(true); this.textMeasureEl_ = null; } this.element_.innerHTML = ''; }; contextPrototype.beginPath = function() { // TODO: Branch current matrix so that save/restore has no effect // as per safari docs. this.currentPath_ = []; }; contextPrototype.moveTo = function(aX, aY) { var p = getCoords(this, aX, aY); this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.lineTo = function(aX, aY) { var p = getCoords(this, aX, aY); this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { var p = getCoords(this, aX, aY); var cp1 = getCoords(this, aCP1x, aCP1y); var cp2 = getCoords(this, aCP2x, aCP2y); bezierCurveTo(this, cp1, cp2, p); }; // Helper function that takes the already fixed cordinates. function bezierCurveTo(self, cp1, cp2, p) { self.currentPath_.push({ type: 'bezierCurveTo', cp1x: cp1.x, cp1y: cp1.y, cp2x: cp2.x, cp2y: cp2.y, x: p.x, y: p.y }); self.currentX_ = p.x; self.currentY_ = p.y; } contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { // the following is lifted almost directly from // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes var cp = getCoords(this, aCPx, aCPy); var p = getCoords(this, aX, aY); var cp1 = { x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) }; var cp2 = { x: cp1.x + (p.x - this.currentX_) / 3.0, y: cp1.y + (p.y - this.currentY_) / 3.0 }; bezierCurveTo(this, cp1, cp2, p); }; contextPrototype.arc = function(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { aRadius *= Z; var arcType = aClockwise ? 'at' : 'wa'; var xStart = aX + mc(aStartAngle) * aRadius - Z2; var yStart = aY + ms(aStartAngle) * aRadius - Z2; var xEnd = aX + mc(aEndAngle) * aRadius - Z2; var yEnd = aY + ms(aEndAngle) * aRadius - Z2; // IE won't render arches drawn counter clockwise if xStart == xEnd. if (xStart == xEnd && !aClockwise) { xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something // that can be represented in binary } var p = getCoords(this, aX, aY); var pStart = getCoords(this, xStart, yStart); var pEnd = getCoords(this, xEnd, yEnd); this.currentPath_.push({type: arcType, x: p.x, y: p.y, radius: aRadius, xStart: pStart.x, yStart: pStart.y, xEnd: pEnd.x, yEnd: pEnd.y}); }; contextPrototype.rect = function(aX, aY, aWidth, aHeight) { this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); }; contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.stroke(); this.currentPath_ = oldPath; }; contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.fill(); this.currentPath_ = oldPath; }; contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { var gradient = new CanvasGradient_('gradient'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.x1_ = aX1; gradient.y1_ = aY1; return gradient; }; contextPrototype.createRadialGradient = function(aX0, aY0, aR0, aX1, aY1, aR1) { var gradient = new CanvasGradient_('gradientradial'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.r0_ = aR0; gradient.x1_ = aX1; gradient.y1_ = aY1; gradient.r1_ = aR1; return gradient; }; contextPrototype.drawImage = function(image, var_args) { var dx, dy, dw, dh, sx, sy, sw, sh; // to find the original width we overide the width and height var oldRuntimeWidth = image.runtimeStyle.width; var oldRuntimeHeight = image.runtimeStyle.height; image.runtimeStyle.width = 'auto'; image.runtimeStyle.height = 'auto'; // get the original size var w = image.width; var h = image.height; // and remove overides image.runtimeStyle.width = oldRuntimeWidth; image.runtimeStyle.height = oldRuntimeHeight; if (arguments.length == 3) { dx = arguments[1]; dy = arguments[2]; sx = sy = 0; sw = dw = w; sh = dh = h; } else if (arguments.length == 5) { dx = arguments[1]; dy = arguments[2]; dw = arguments[3]; dh = arguments[4]; sx = sy = 0; sw = w; sh = h; } else if (arguments.length == 9) { sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else { throw Error('Invalid number of arguments'); } var d = getCoords(this, dx, dy); var w2 = sw / 2; var h2 = sh / 2; var vmlStr = []; var W = 10; var H = 10; // For some reason that I've now forgotten, using divs didn't work vmlStr.push(' <g_vml_:group', ' coordsize="', Z * W, ',', Z * H, '"', ' coordorigin="0,0"' , ' style="width:', W, 'px;height:', H, 'px;position:absolute;'); // If filters are necessary (rotation exists), create them // filters are bog-slow, so only create them if abbsolutely necessary // The following check doesn't account for skews (which don't exist // in the canvas spec (yet) anyway. if (this.m_[0][0] != 1 || this.m_[0][1] || this.m_[1][1] != 1 || this.m_[1][0]) { var filter = []; // Note the 12/21 reversal filter.push('M11=', this.m_[0][0], ',', 'M12=', this.m_[1][0], ',', 'M21=', this.m_[0][1], ',', 'M22=', this.m_[1][1], ',', 'Dx=', mr(d.x / Z), ',', 'Dy=', mr(d.y / Z), ''); // Bounding box calculation (need to minimize displayed area so that // filters don't waste time on unused pixels. var max = d; var c2 = getCoords(this, dx + dw, dy); var c3 = getCoords(this, dx, dy + dh); var c4 = getCoords(this, dx + dw, dy + dh); max.x = m.max(max.x, c2.x, c3.x, c4.x); max.y = m.max(max.y, c2.y, c3.y, c4.y); vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z), 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(', filter.join(''), ", sizingmethod='clip');"); } else { vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;'); } vmlStr.push(' ">' , '<g_vml_:image src="', image.src, '"', ' style="width:', Z * dw, 'px;', ' height:', Z * dh, 'px"', ' cropleft="', sx / w, '"', ' croptop="', sy / h, '"', ' cropright="', (w - sx - sw) / w, '"', ' cropbottom="', (h - sy - sh) / h, '"', ' />', '</g_vml_:group>'); this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); }; contextPrototype.stroke = function(aFill) { var W = 10; var H = 10; // Divide the shape into chunks if it's too long because IE has a limit // somewhere for how long a VML shape can be. This simple division does // not work with fills, only strokes, unfortunately. var chunkSize = 5000; var min = {x: null, y: null}; var max = {x: null, y: null}; for (var j = 0; j < this.currentPath_.length; j += chunkSize) { var lineStr = []; var lineOpen = false; lineStr.push('<g_vml_:shape', ' filled="', !!aFill, '"', ' style="position:absolute;width:', W, 'px;height:', H, 'px;"', ' coordorigin="0,0"', ' coordsize="', Z * W, ',', Z * H, '"', ' stroked="', !aFill, '"', ' path="'); var newSeq = false; for (var i = j; i < Math.min(j + chunkSize, this.currentPath_.length); i++) { if (i % chunkSize == 0 && i > 0) { // move into position for next chunk lineStr.push(' m ', mr(this.currentPath_[i-1].x), ',', mr(this.currentPath_[i-1].y)); } var p = this.currentPath_[i]; var c; switch (p.type) { case 'moveTo': c = p; lineStr.push(' m ', mr(p.x), ',', mr(p.y)); break; case 'lineTo': lineStr.push(' l ', mr(p.x), ',', mr(p.y)); break; case 'close': lineStr.push(' x '); p = null; break; case 'bezierCurveTo': lineStr.push(' c ', mr(p.cp1x), ',', mr(p.cp1y), ',', mr(p.cp2x), ',', mr(p.cp2y), ',', mr(p.x), ',', mr(p.y)); break; case 'at': case 'wa': lineStr.push(' ', p.type, ' ', mr(p.x - this.arcScaleX_ * p.radius), ',', mr(p.y - this.arcScaleY_ * p.radius), ' ', mr(p.x + this.arcScaleX_ * p.radius), ',', mr(p.y + this.arcScaleY_ * p.radius), ' ', mr(p.xStart), ',', mr(p.yStart), ' ', mr(p.xEnd), ',', mr(p.yEnd)); break; } // TODO: Following is broken for curves due to // move to proper paths. // Figure out dimensions so we can do gradient fills // properly if (p) { if (min.x == null || p.x < min.x) { min.x = p.x; } if (max.x == null || p.x > max.x) { max.x = p.x; } if (min.y == null || p.y < min.y) { min.y = p.y; } if (max.y == null || p.y > max.y) { max.y = p.y; } } } lineStr.push(' ">'); if (!aFill) { appendStroke(this, lineStr); } else { appendFill(this, lineStr, min, max); } lineStr.push('</g_vml_:shape>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); } }; function appendStroke(ctx, lineStr) { var a = processStyle(ctx.strokeStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; var lineWidth = ctx.lineScale_ * ctx.lineWidth; // VML cannot correctly render a line if the width is less than 1px. // In that case, we dilute the color to make the line look thinner. if (lineWidth < 1) { opacity *= lineWidth; } lineStr.push( '<g_vml_:stroke', ' opacity="', opacity, '"', ' joinstyle="', ctx.lineJoin, '"', ' miterlimit="', ctx.miterLimit, '"', ' endcap="', processLineCap(ctx.lineCap), '"', ' weight="', lineWidth, 'px"', ' color="', color, '" />' ); } function appendFill(ctx, lineStr, min, max) { var fillStyle = ctx.fillStyle; var arcScaleX = ctx.arcScaleX_; var arcScaleY = ctx.arcScaleY_; var width = max.x - min.x; var height = max.y - min.y; if (fillStyle instanceof CanvasGradient_) { // TODO: Gradients transformed with the transformation matrix. var angle = 0; var focus = {x: 0, y: 0}; // additional offset var shift = 0; // scale factor for offset var expansion = 1; if (fillStyle.type_ == 'gradient') { var x0 = fillStyle.x0_ / arcScaleX; var y0 = fillStyle.y0_ / arcScaleY; var x1 = fillStyle.x1_ / arcScaleX; var y1 = fillStyle.y1_ / arcScaleY; var p0 = getCoords(ctx, x0, y0); var p1 = getCoords(ctx, x1, y1); var dx = p1.x - p0.x; var dy = p1.y - p0.y; angle = Math.atan2(dx, dy) * 180 / Math.PI; // The angle should be a non-negative number. if (angle < 0) { angle += 360; } // Very small angles produce an unexpected result because they are // converted to a scientific notation string. if (angle < 1e-6) { angle = 0; } } else { var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); focus = { x: (p0.x - min.x) / width, y: (p0.y - min.y) / height }; width /= arcScaleX * Z; height /= arcScaleY * Z; var dimension = m.max(width, height); shift = 2 * fillStyle.r0_ / dimension; expansion = 2 * fillStyle.r1_ / dimension - shift; } // We need to sort the color stops in ascending order by offset, // otherwise IE won't interpret it correctly. var stops = fillStyle.colors_; stops.sort(function(cs1, cs2) { return cs1.offset - cs2.offset; }); var length = stops.length; var color1 = stops[0].color; var color2 = stops[length - 1].color; var opacity1 = stops[0].alpha * ctx.globalAlpha; var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; var colors = []; for (var i = 0; i < length; i++) { var stop = stops[i]; colors.push(stop.offset * expansion + shift + ' ' + stop.color); } // When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"', ' method="none" focus="100%"', ' color="', color1, '"', ' color2="', color2, '"', ' colors="', colors.join(','), '"', ' opacity="', opacity2, '"', ' g_o_:opacity2="', opacity1, '"', ' angle="', angle, '"', ' focusposition="', focus.x, ',', focus.y, '" />'); } else if (fillStyle instanceof CanvasPattern_) { if (width && height) { var deltaLeft = -min.x; var deltaTop = -min.y; lineStr.push('<g_vml_:fill', ' position="', deltaLeft / width * arcScaleX * arcScaleX, ',', deltaTop / height * arcScaleY * arcScaleY, '"', ' type="tile"', // TODO: Figure out the correct size to fit the scale. //' size="', w, 'px ', h, 'px"', ' src="', fillStyle.src_, '" />'); } } else { var a = processStyle(ctx.fillStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />'); } } contextPrototype.fill = function() { this.stroke(true); }; contextPrototype.closePath = function() { this.currentPath_.push({type: 'close'}); }; function getCoords(ctx, aX, aY) { var m = ctx.m_; return { x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 }; }; contextPrototype.save = function() { var o = {}; copyState(this, o); this.aStack_.push(o); this.mStack_.push(this.m_); this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); }; contextPrototype.restore = function() { if (this.aStack_.length) { copyState(this.aStack_.pop(), this); this.m_ = this.mStack_.pop(); } }; function matrixIsFinite(m) { return isFinite(m[0][0]) && isFinite(m[0][1]) && isFinite(m[1][0]) && isFinite(m[1][1]) && isFinite(m[2][0]) && isFinite(m[2][1]); } function setM(ctx, m, updateLineScale) { if (!matrixIsFinite(m)) { return; } ctx.m_ = m; if (updateLineScale) { // Get the line scale. // Determinant of this.m_ means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; ctx.lineScale_ = sqrt(abs(det)); } } contextPrototype.translate = function(aX, aY) { var m1 = [ [1, 0, 0], [0, 1, 0], [aX, aY, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.rotate = function(aRot) { var c = mc(aRot); var s = ms(aRot); var m1 = [ [c, s, 0], [-s, c, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.scale = function(aX, aY) { this.arcScaleX_ *= aX; this.arcScaleY_ *= aY; var m1 = [ [aX, 0, 0], [0, aY, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { var m1 = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { var m = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, m, true); }; /** * The text drawing function. * The maxWidth argument isn't taken in account, since no browser supports * it yet. */ contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { var m = this.m_, delta = 1000, left = 0, right = delta, offset = {x: 0, y: 0}, lineStr = []; var fontStyle = getComputedStyle(processFontStyle(this.font), this.element_); var fontStyleString = buildStyle(fontStyle); var elementStyle = this.element_.currentStyle; var textAlign = this.textAlign.toLowerCase(); switch (textAlign) { case 'left': case 'center': case 'right': break; case 'end': textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; break; case 'start': textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; break; default: textAlign = 'left'; } // 1.75 is an arbitrary number, as there is no info about the text baseline switch (this.textBaseline) { case 'hanging': case 'top': offset.y = fontStyle.size / 1.75; break; case 'middle': break; default: case null: case 'alphabetic': case 'ideographic': case 'bottom': offset.y = -fontStyle.size / 2.25; break; } switch(textAlign) { case 'right': left = delta; right = 0.05; break; case 'center': left = right = delta / 2; break; } var d = getCoords(this, x + offset.x, y + offset.y); lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ', ' coordsize="100 100" coordorigin="0 0"', ' filled="', !stroke, '" stroked="', !!stroke, '" style="position:absolute;width:1px;height:1px;">'); if (stroke) { appendStroke(this, lineStr); } else { // TODO: Fix the min and max params. appendFill(this, lineStr, {x: -left, y: 0}, {x: right, y: fontStyle.size}); } var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ', ' offset="', skewOffset, '" origin="', left ,' 0" />', '<g_vml_:path textpathok="true" />', '<g_vml_:textpath on="true" string="', encodeHtmlAttribute(text), '" style="v-text-align:', textAlign, ';font:', encodeHtmlAttribute(fontStyleString), '" /></g_vml_:line>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; contextPrototype.fillText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, false); }; contextPrototype.strokeText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, true); }; contextPrototype.measureText = function(text) { if (!this.textMeasureEl_) { var s = '<span style="position:absolute;' + 'top:-20000px;left:0;padding:0;margin:0;border:none;' + 'white-space:pre;"></span>'; this.element_.insertAdjacentHTML('beforeEnd', s); this.textMeasureEl_ = this.element_.lastChild; } var doc = this.element_.ownerDocument; this.textMeasureEl_.innerHTML = ''; this.textMeasureEl_.style.font = this.font; // Don't use innerHTML or innerText because they allow markup/whitespace. this.textMeasureEl_.appendChild(doc.createTextNode(text)); return {width: this.textMeasureEl_.offsetWidth}; }; /******** STUBS ********/ contextPrototype.clip = function() { // TODO: Implement }; contextPrototype.arcTo = function() { // TODO: Implement }; contextPrototype.createPattern = function(image, repetition) { return new CanvasPattern_(image, repetition); }; // Gradient / Pattern Stubs function CanvasGradient_(aType) { this.type_ = aType; this.x0_ = 0; this.y0_ = 0; this.r0_ = 0; this.x1_ = 0; this.y1_ = 0; this.r1_ = 0; this.colors_ = []; } CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { aColor = processStyle(aColor); this.colors_.push({offset: aOffset, color: aColor.color, alpha: aColor.alpha}); }; function CanvasPattern_(image, repetition) { assertImageIsValid(image); switch (repetition) { case 'repeat': case null: case '': this.repetition_ = 'repeat'; break case 'repeat-x': case 'repeat-y': case 'no-repeat': this.repetition_ = repetition; break; default: throwException('SYNTAX_ERR'); } this.src_ = image.src; this.width_ = image.width; this.height_ = image.height; } function throwException(s) { throw new DOMException_(s); } function assertImageIsValid(img) { if (!img || img.nodeType != 1 || img.tagName != 'IMG') { throwException('TYPE_MISMATCH_ERR'); } if (img.readyState != 'complete') { throwException('INVALID_STATE_ERR'); } } function DOMException_(s) { this.code = this[s]; this.message = s +': DOM Exception ' + this.code; } var p = DOMException_.prototype = new Error; p.INDEX_SIZE_ERR = 1; p.DOMSTRING_SIZE_ERR = 2; p.HIERARCHY_REQUEST_ERR = 3; p.WRONG_DOCUMENT_ERR = 4; p.INVALID_CHARACTER_ERR = 5; p.NO_DATA_ALLOWED_ERR = 6; p.NO_MODIFICATION_ALLOWED_ERR = 7; p.NOT_FOUND_ERR = 8; p.NOT_SUPPORTED_ERR = 9; p.INUSE_ATTRIBUTE_ERR = 10; p.INVALID_STATE_ERR = 11; p.SYNTAX_ERR = 12; p.INVALID_MODIFICATION_ERR = 13; p.NAMESPACE_ERR = 14; p.INVALID_ACCESS_ERR = 15; p.VALIDATION_ERR = 16; p.TYPE_MISMATCH_ERR = 17; // set up externs G_vmlCanvasManager = G_vmlCanvasManager_; CanvasRenderingContext2D = CanvasRenderingContext2D_; CanvasGradient = CanvasGradient_; CanvasPattern = CanvasPattern_; DOMException = DOMException_; })(); } // if
JavaScript
/* Flot plugin for computing bottoms for filled line and bar charts. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The case: you've got two series that you want to fill the area between. In Flot terms, you need to use one as the fill bottom of the other. You can specify the bottom of each data point as the third coordinate manually, or you can use this plugin to compute it for you. In order to name the other series, you need to give it an id, like this: var dataset = [ { data: [ ... ], id: "foo" } , // use default bottom { data: [ ... ], fillBetween: "foo" }, // use first dataset as bottom ]; $.plot($("#placeholder"), dataset, { lines: { show: true, fill: true }}); As a convenience, if the id given is a number that doesn't appear as an id in the series, it is interpreted as the index in the array instead (so fillBetween: 0 can also mean the first series). Internally, the plugin modifies the datapoints in each series. For line series, extra data points might be inserted through interpolation. Note that at points where the bottom line is not defined (due to a null point or start/end of line), the current line will show a gap too. The algorithm comes from the jquery.flot.stack.js plugin, possibly some code could be shared. */ (function ( $ ) { var options = { series: { fillBetween: null // or number } }; function init( plot ) { function findBottomSeries( s, allseries ) { var i; for ( i = 0; i < allseries.length; ++i ) { if ( allseries[ i ].id === s.fillBetween ) { return allseries[ i ]; } } if ( typeof s.fillBetween === "number" ) { if ( s.fillBetween < 0 || s.fillBetween >= allseries.length ) { return null; } return allseries[ s.fillBetween ]; } return null; } function computeFillBottoms( plot, s, datapoints ) { if ( s.fillBetween == null ) { return; } var other = findBottomSeries( s, plot.getData() ); if ( !other ) { return; } var ps = datapoints.pointsize, points = datapoints.points, otherps = other.datapoints.pointsize, otherpoints = other.datapoints.points, newpoints = [], px, py, intery, qx, qy, bottom, withlines = s.lines.show, withbottom = ps > 2 && datapoints.format[2].y, withsteps = withlines && s.lines.steps, fromgap = true, i = 0, j = 0, l, m; while ( true ) { if ( i >= points.length ) { break; } l = newpoints.length; if ( points[ i ] == null ) { // copy gaps for ( m = 0; m < ps; ++m ) { newpoints.push( points[ i + m ] ); } i += ps; } else if ( j >= otherpoints.length ) { // for lines, we can't use the rest of the points if ( !withlines ) { for ( m = 0; m < ps; ++m ) { newpoints.push( points[ i + m ] ); } } i += ps; } else if ( otherpoints[ j ] == null ) { // oops, got a gap for ( m = 0; m < ps; ++m ) { newpoints.push( null ); } fromgap = true; j += otherps; } else { // cases where we actually got two points px = points[ i ]; py = points[ i + 1 ]; qx = otherpoints[ j ]; qy = otherpoints[ j + 1 ]; bottom = 0; if ( px === qx ) { for ( m = 0; m < ps; ++m ) { newpoints.push( points[ i + m ] ); } //newpoints[ l + 1 ] += qy; bottom = qy; i += ps; j += otherps; } else if ( px > qx ) { // we got past point below, might need to // insert interpolated extra point if ( withlines && i > 0 && points[ i - ps ] != null ) { intery = py + ( points[ i - ps + 1 ] - py ) * ( qx - px ) / ( points[ i - ps ] - px ); newpoints.push( qx ); newpoints.push( intery ); for ( m = 2; m < ps; ++m ) { newpoints.push( points[ i + m ] ); } bottom = qy; } j += otherps; } else { // px < qx // if we come from a gap, we just skip this point if ( fromgap && withlines ) { i += ps; continue; } for ( m = 0; m < ps; ++m ) { newpoints.push( points[ i + m ] ); } // we might be able to interpolate a point below, // this can give us a better y if ( withlines && j > 0 && otherpoints[ j - otherps ] != null ) { bottom = qy + ( otherpoints[ j - otherps + 1 ] - qy ) * ( px - qx ) / ( otherpoints[ j - otherps ] - qx ); } //newpoints[l + 1] += bottom; i += ps; } fromgap = false; if ( l !== newpoints.length && withbottom ) { newpoints[ l + 2 ] = bottom; } } // maintain the line steps invariant if ( withsteps && l !== newpoints.length && l > 0 && newpoints[ l ] !== null && newpoints[ l ] !== newpoints[ l - ps ] && newpoints[ l + 1 ] !== newpoints[ l - ps + 1 ] ) { for (m = 0; m < ps; ++m) { newpoints[ l + ps + m ] = newpoints[ l + m ]; } newpoints[ l + 1 ] = newpoints[ l - ps + 1 ]; } } datapoints.points = newpoints; } plot.hooks.processDatapoints.push( computeFillBottoms ); } $.plot.plugins.push({ init: init, options: options, name: "fillbetween", version: "1.0" }); })(jQuery);
JavaScript
/* Flot plugin for rendering pie charts. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The plugin assumes that each series has a single data value, and that each value is a positive integer or zero. Negative numbers don't make sense for a pie chart, and have unpredictable results. The values do NOT need to be passed in as percentages; the plugin will calculate the total and per-slice percentages internally. * Created by Brian Medendorp * Updated with contributions from btburnett3, Anthony Aragues and Xavi Ivars The plugin supports these options: series: { pie: { show: true/false radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto' innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show) offset: { top: integer value to move the pie up or down left: integer value to move the pie left or right, or 'auto' }, stroke: { color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF') width: integer pixel width of the stroke }, label: { show: true/false, or 'auto' formatter: a user-defined function that modifies the text/style of the label text radius: 0-1 for percentage of fullsize, or a specified pixel length background: { color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000') opacity: 0-1 }, threshold: 0-1 for the percentage value at which to hide labels (if they're too small) }, combine: { threshold: 0-1 for the percentage value at which to combine slices (if they're too small) color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined label: any text value of what the combined slice should be labeled } highlight: { opacity: 0-1 } } } More detail and specific examples can be found in the included HTML file. */ (function($) { // Maximum redraw attempts when fitting labels within the plot var REDRAW_ATTEMPTS = 10; // Factor by which to shrink the pie when fitting labels within the plot var REDRAW_SHRINK = 0.95; function init(plot) { var canvas = null, target = null, options = null, maxRadius = null, centerLeft = null, centerTop = null, processed = false, ctx = null; // interactive variables var highlights = []; // add hook to determine if pie plugin in enabled, and then perform necessary operations plot.hooks.processOptions.push(function(plot, options) { if (options.series.pie.show) { options.grid.show = false; // set labels.show if (options.series.pie.label.show == "auto") { if (options.legend.show) { options.series.pie.label.show = false; } else { options.series.pie.label.show = true; } } // set radius if (options.series.pie.radius == "auto") { if (options.series.pie.label.show) { options.series.pie.radius = 3/4; } else { options.series.pie.radius = 1; } } // ensure sane tilt if (options.series.pie.tilt > 1) { options.series.pie.tilt = 1; } else if (options.series.pie.tilt < 0) { options.series.pie.tilt = 0; } } }); plot.hooks.bindEvents.push(function(plot, eventHolder) { var options = plot.getOptions(); if (options.series.pie.show) { if (options.grid.hoverable) { eventHolder.unbind("mousemove").mousemove(onMouseMove); } if (options.grid.clickable) { eventHolder.unbind("click").click(onClick); } } }); plot.hooks.processDatapoints.push(function(plot, series, data, datapoints) { var options = plot.getOptions(); if (options.series.pie.show) { processDatapoints(plot, series, data, datapoints); } }); plot.hooks.drawOverlay.push(function(plot, octx) { var options = plot.getOptions(); if (options.series.pie.show) { drawOverlay(plot, octx); } }); plot.hooks.draw.push(function(plot, newCtx) { var options = plot.getOptions(); if (options.series.pie.show) { draw(plot, newCtx); } }); function processDatapoints(plot, series, datapoints) { if (!processed) { processed = true; canvas = plot.getCanvas(); target = $(canvas).parent(); options = plot.getOptions(); plot.setData(combine(plot.getData())); } } function combine(data) { var total = 0, combined = 0, numCombined = 0, color = options.series.pie.combine.color, newdata = []; // Fix up the raw data from Flot, ensuring the data is numeric for (var i = 0; i < data.length; ++i) { var value = data[i].data; // If the data is an array, we'll assume that it's a standard // Flot x-y pair, and are concerned only with the second value. // Note how we use the original array, rather than creating a // new one; this is more efficient and preserves any extra data // that the user may have stored in higher indexes. if ($.isArray(value) && value.length == 1) { value = value[0]; } if ($.isArray(value)) { // Equivalent to $.isNumeric() but compatible with jQuery < 1.7 if (!isNaN(parseFloat(value[1])) && isFinite(value[1])) { value[1] = +value[1]; } else { value[1] = 0; } } else if (!isNaN(parseFloat(value)) && isFinite(value)) { value = [1, +value]; } else { value = [1, 0]; } data[i].data = [value]; } // Sum up all the slices, so we can calculate percentages for each for (var i = 0; i < data.length; ++i) { total += data[i].data[0][1]; } // Count the number of slices with percentages below the combine // threshold; if it turns out to be just one, we won't combine. for (var i = 0; i < data.length; ++i) { var value = data[i].data[0][1]; if (value / total <= options.series.pie.combine.threshold) { combined += value; numCombined++; if (!color) { color = data[i].color; } } } for (var i = 0; i < data.length; ++i) { var value = data[i].data[0][1]; if (numCombined < 2 || value / total > options.series.pie.combine.threshold) { newdata.push({ data: [[1, value]], color: data[i].color, label: data[i].label, angle: value * Math.PI * 2 / total, percent: value / (total / 100) }); } } if (numCombined > 1) { newdata.push({ data: [[1, combined]], color: color, label: options.series.pie.combine.label, angle: combined * Math.PI * 2 / total, percent: combined / (total / 100) }); } return newdata; } function draw(plot, newCtx) { if (!target) { return; // if no series were passed } var canvasWidth = plot.getPlaceholder().width(), canvasHeight = plot.getPlaceholder().height(), legendWidth = target.children().filter(".legend").children().width() || 0; ctx = newCtx; // WARNING: HACK! REWRITE THIS CODE AS SOON AS POSSIBLE! // When combining smaller slices into an 'other' slice, we need to // add a new series. Since Flot gives plugins no way to modify the // list of series, the pie plugin uses a hack where the first call // to processDatapoints results in a call to setData with the new // list of series, then subsequent processDatapoints do nothing. // The plugin-global 'processed' flag is used to control this hack; // it starts out false, and is set to true after the first call to // processDatapoints. // Unfortunately this turns future setData calls into no-ops; they // call processDatapoints, the flag is true, and nothing happens. // To fix this we'll set the flag back to false here in draw, when // all series have been processed, so the next sequence of calls to // processDatapoints once again starts out with a slice-combine. // This is really a hack; in 0.9 we need to give plugins a proper // way to modify series before any processing begins. processed = false; // calculate maximum radius and center point maxRadius = Math.min(canvasWidth, canvasHeight / options.series.pie.tilt) / 2; centerTop = canvasHeight / 2 + options.series.pie.offset.top; centerLeft = canvasWidth / 2; if (options.series.pie.offset.left == "auto") { if (options.legend.position.match("w")) { centerLeft += legendWidth / 2; } else { centerLeft -= legendWidth / 2; } if (centerLeft < maxRadius) { centerLeft = maxRadius; } else if (centerLeft > canvasWidth - maxRadius) { centerLeft = canvasWidth - maxRadius; } } else { centerLeft += options.series.pie.offset.left; } var slices = plot.getData(), attempts = 0; // Keep shrinking the pie's radius until drawPie returns true, // indicating that all the labels fit, or we try too many times. do { if (attempts > 0) { maxRadius *= REDRAW_SHRINK; } attempts += 1; clear(); if (options.series.pie.tilt <= 0.8) { drawShadow(); } } while (!drawPie() && attempts < REDRAW_ATTEMPTS) if (attempts >= REDRAW_ATTEMPTS) { clear(); target.prepend("<div class='error'>Could not draw pie with labels contained inside canvas</div>"); } if (plot.setSeries && plot.insertLegend) { plot.setSeries(slices); plot.insertLegend(); } // we're actually done at this point, just defining internal functions at this point function clear() { ctx.clearRect(0, 0, canvasWidth, canvasHeight); target.children().filter(".pieLabel, .pieLabelBackground").remove(); } function drawShadow() { var shadowLeft = options.series.pie.shadow.left; var shadowTop = options.series.pie.shadow.top; var edge = 10; var alpha = options.series.pie.shadow.alpha; var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; if (radius >= canvasWidth / 2 - shadowLeft || radius * options.series.pie.tilt >= canvasHeight / 2 - shadowTop || radius <= edge) { return; // shadow would be outside canvas, so don't draw it } ctx.save(); ctx.translate(shadowLeft,shadowTop); ctx.globalAlpha = alpha; ctx.fillStyle = "#000"; // center and rotate to starting position ctx.translate(centerLeft,centerTop); ctx.scale(1, options.series.pie.tilt); //radius -= edge; for (var i = 1; i <= edge; i++) { ctx.beginPath(); ctx.arc(0, 0, radius, 0, Math.PI * 2, false); ctx.fill(); radius -= i; } ctx.restore(); } function drawPie() { var startAngle = Math.PI * options.series.pie.startAngle; var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; // center and rotate to starting position ctx.save(); ctx.translate(centerLeft,centerTop); ctx.scale(1, options.series.pie.tilt); //ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera // draw slices ctx.save(); var currentAngle = startAngle; for (var i = 0; i < slices.length; ++i) { slices[i].startAngle = currentAngle; drawSlice(slices[i].angle, slices[i].color, true); } ctx.restore(); // draw slice outlines if (options.series.pie.stroke.width > 0) { ctx.save(); ctx.lineWidth = options.series.pie.stroke.width; currentAngle = startAngle; for (var i = 0; i < slices.length; ++i) { drawSlice(slices[i].angle, options.series.pie.stroke.color, false); } ctx.restore(); } // draw donut hole drawDonutHole(ctx); ctx.restore(); // Draw the labels, returning true if they fit within the plot if (options.series.pie.label.show) { return drawLabels(); } else return true; function drawSlice(angle, color, fill) { if (angle <= 0 || isNaN(angle)) { return; } if (fill) { ctx.fillStyle = color; } else { ctx.strokeStyle = color; ctx.lineJoin = "round"; } ctx.beginPath(); if (Math.abs(angle - Math.PI * 2) > 0.000000001) { ctx.moveTo(0, 0); // Center of the pie } //ctx.arc(0, 0, radius, 0, angle, false); // This doesn't work properly in Opera ctx.arc(0, 0, radius,currentAngle, currentAngle + angle / 2, false); ctx.arc(0, 0, radius,currentAngle + angle / 2, currentAngle + angle, false); ctx.closePath(); //ctx.rotate(angle); // This doesn't work properly in Opera currentAngle += angle; if (fill) { ctx.fill(); } else { ctx.stroke(); } } function drawLabels() { var currentAngle = startAngle; var radius = options.series.pie.label.radius > 1 ? options.series.pie.label.radius : maxRadius * options.series.pie.label.radius; for (var i = 0; i < slices.length; ++i) { if (slices[i].percent >= options.series.pie.label.threshold * 100) { if (!drawLabel(slices[i], currentAngle, i)) { return false; } } currentAngle += slices[i].angle; } return true; function drawLabel(slice, startAngle, index) { if (slice.data[0][1] == 0) { return true; } // format label text var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter; if (lf) { text = lf(slice.label, slice); } else { text = slice.label; } if (plf) { text = plf(text, slice); } var halfAngle = ((startAngle + slice.angle) + startAngle) / 2; var x = centerLeft + Math.round(Math.cos(halfAngle) * radius); var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt; var html = "<span class='pieLabel' id='pieLabel" + index + "' style='position:absolute;top:" + y + "px;left:" + x + "px;'>" + text + "</span>"; target.append(html); var label = target.children("#pieLabel" + index); var labelTop = (y - label.height() / 2); var labelLeft = (x - label.width() / 2); label.css("top", labelTop); label.css("left", labelLeft); // check to make sure that the label is not outside the canvas if (0 - labelTop > 0 || 0 - labelLeft > 0 || canvasHeight - (labelTop + label.height()) < 0 || canvasWidth - (labelLeft + label.width()) < 0) { return false; } if (options.series.pie.label.background.opacity != 0) { // put in the transparent background separately to avoid blended labels and label boxes var c = options.series.pie.label.background.color; if (c == null) { c = slice.color; } var pos = "top:" + labelTop + "px;left:" + labelLeft + "px;"; $("<div class='pieLabelBackground' style='position:absolute;width:" + label.width() + "px;height:" + label.height() + "px;" + pos + "background-color:" + c + ";'></div>") .css("opacity", options.series.pie.label.background.opacity) .insertBefore(label); } return true; } // end individual label function } // end drawLabels function } // end drawPie function } // end draw function // Placed here because it needs to be accessed from multiple locations function drawDonutHole(layer) { if (options.series.pie.innerRadius > 0) { // subtract the center layer.save(); var innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius; layer.globalCompositeOperation = "destination-out"; // this does not work with excanvas, but it will fall back to using the stroke color layer.beginPath(); layer.fillStyle = options.series.pie.stroke.color; layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false); layer.fill(); layer.closePath(); layer.restore(); // add inner stroke layer.save(); layer.beginPath(); layer.strokeStyle = options.series.pie.stroke.color; layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false); layer.stroke(); layer.closePath(); layer.restore(); // TODO: add extra shadow inside hole (with a mask) if the pie is tilted. } } //-- Additional Interactive related functions -- function isPointInPoly(poly, pt) { for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) ((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1])) && (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0]) && (c = !c); return c; } function findNearbySlice(mouseX, mouseY) { var slices = plot.getData(), options = plot.getOptions(), radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius, x, y; for (var i = 0; i < slices.length; ++i) { var s = slices[i]; if (s.pie.show) { ctx.save(); ctx.beginPath(); ctx.moveTo(0, 0); // Center of the pie //ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here. ctx.arc(0, 0, radius, s.startAngle, s.startAngle + s.angle / 2, false); ctx.arc(0, 0, radius, s.startAngle + s.angle / 2, s.startAngle + s.angle, false); ctx.closePath(); x = mouseX - centerLeft; y = mouseY - centerTop; if (ctx.isPointInPath) { if (ctx.isPointInPath(mouseX - centerLeft, mouseY - centerTop)) { ctx.restore(); return { datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i }; } } else { // excanvas for IE doesn;t support isPointInPath, this is a workaround. var p1X = radius * Math.cos(s.startAngle), p1Y = radius * Math.sin(s.startAngle), p2X = radius * Math.cos(s.startAngle + s.angle / 4), p2Y = radius * Math.sin(s.startAngle + s.angle / 4), p3X = radius * Math.cos(s.startAngle + s.angle / 2), p3Y = radius * Math.sin(s.startAngle + s.angle / 2), p4X = radius * Math.cos(s.startAngle + s.angle / 1.5), p4Y = radius * Math.sin(s.startAngle + s.angle / 1.5), p5X = radius * Math.cos(s.startAngle + s.angle), p5Y = radius * Math.sin(s.startAngle + s.angle), arrPoly = [[0, 0], [p1X, p1Y], [p2X, p2Y], [p3X, p3Y], [p4X, p4Y], [p5X, p5Y]], arrPoint = [x, y]; // TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt? if (isPointInPoly(arrPoly, arrPoint)) { ctx.restore(); return { datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i }; } } ctx.restore(); } } return null; } function onMouseMove(e) { triggerClickHoverEvent("plothover", e); } function onClick(e) { triggerClickHoverEvent("plotclick", e); } // trigger click or hover event (they send the same parameters so we share their code) function triggerClickHoverEvent(eventname, e) { var offset = plot.offset(); var canvasX = parseInt(e.pageX - offset.left); var canvasY = parseInt(e.pageY - offset.top); var item = findNearbySlice(canvasX, canvasY); if (options.grid.autoHighlight) { // clear auto-highlights for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.auto == eventname && !(item && h.series == item.series)) { unhighlight(h.series); } } } // highlight the slice if (item) { highlight(item.series, eventname); } // trigger any hover bind events var pos = { pageX: e.pageX, pageY: e.pageY }; target.trigger(eventname, [pos, item]); } function highlight(s, auto) { //if (typeof s == "number") { // s = series[s]; //} var i = indexOfHighlight(s); if (i == -1) { highlights.push({ series: s, auto: auto }); plot.triggerRedrawOverlay(); } else if (!auto) { highlights[i].auto = false; } } function unhighlight(s) { if (s == null) { highlights = []; plot.triggerRedrawOverlay(); } //if (typeof s == "number") { // s = series[s]; //} var i = indexOfHighlight(s); if (i != -1) { highlights.splice(i, 1); plot.triggerRedrawOverlay(); } } function indexOfHighlight(s) { for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.series == s) return i; } return -1; } function drawOverlay(plot, octx) { var options = plot.getOptions(); var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; octx.save(); octx.translate(centerLeft, centerTop); octx.scale(1, options.series.pie.tilt); for (var i = 0; i < highlights.length; ++i) { drawHighlight(highlights[i].series); } drawDonutHole(octx); octx.restore(); function drawHighlight(series) { if (series.angle <= 0 || isNaN(series.angle)) { return; } //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString(); octx.fillStyle = "rgba(255, 255, 255, " + options.series.pie.highlight.opacity + ")"; // this is temporary until we have access to parseColor octx.beginPath(); if (Math.abs(series.angle - Math.PI * 2) > 0.000000001) { octx.moveTo(0, 0); // Center of the pie } octx.arc(0, 0, radius, series.startAngle, series.startAngle + series.angle / 2, false); octx.arc(0, 0, radius, series.startAngle + series.angle / 2, series.startAngle + series.angle, false); octx.closePath(); octx.fill(); } } } // end init (plugin body) // define pie specific options and their default values var options = { series: { pie: { show: false, radius: "auto", // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value) innerRadius: 0, /* for donut */ startAngle: 3/2, tilt: 1, shadow: { left: 5, // shadow left offset top: 15, // shadow top offset alpha: 0.02 // shadow alpha }, offset: { top: 0, left: "auto" }, stroke: { color: "#fff", width: 1 }, label: { show: "auto", formatter: function(label, slice) { return "<div style='font-size:x-small;text-align:center;padding:2px;color:" + slice.color + ";'>" + label + "<br/>" + Math.round(slice.percent) + "%</div>"; }, // formatter function radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value) background: { color: null, opacity: 0 }, threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow) }, combine: { threshold: -1, // percentage at which to combine little slices into one larger slice color: null, // color to give the new slice (auto-generated if null) label: "Other" // label to give the new slice }, highlight: { //color: "#fff", // will add this functionality once parseColor is available opacity: 0.5 } } } }; $.plot.plugins.push({ init: init, options: options, name: "pie", version: "1.1" }); })(jQuery);
JavaScript
/* Flot plugin for plotting images. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The data syntax is [ [ image, x1, y1, x2, y2 ], ... ] where (x1, y1) and (x2, y2) are where you intend the two opposite corners of the image to end up in the plot. Image must be a fully loaded Javascript image (you can make one with new Image()). If the image is not complete, it's skipped when plotting. There are two helpers included for retrieving images. The easiest work the way that you put in URLs instead of images in the data, like this: [ "myimage.png", 0, 0, 10, 10 ] Then call $.plot.image.loadData( data, options, callback ) where data and options are the same as you pass in to $.plot. This loads the images, replaces the URLs in the data with the corresponding images and calls "callback" when all images are loaded (or failed loading). In the callback, you can then call $.plot with the data set. See the included example. A more low-level helper, $.plot.image.load(urls, callback) is also included. Given a list of URLs, it calls callback with an object mapping from URL to Image object when all images are loaded or have failed loading. The plugin supports these options: series: { images: { show: boolean anchor: "corner" or "center" alpha: [ 0, 1 ] } } They can be specified for a specific series: $.plot( $("#placeholder"), [{ data: [ ... ], images: { ... } ]) Note that because the data format is different from usual data points, you can't use images with anything else in a specific data series. Setting "anchor" to "center" causes the pixels in the image to be anchored at the corner pixel centers inside of at the pixel corners, effectively letting half a pixel stick out to each side in the plot. A possible future direction could be support for tiling for large images (like Google Maps). */ (function ($) { var options = { series: { images: { show: false, alpha: 1, anchor: "corner" // or "center" } } }; $.plot.image = {}; $.plot.image.loadDataImages = function (series, options, callback) { var urls = [], points = []; var defaultShow = options.series.images.show; $.each(series, function (i, s) { if (!(defaultShow || s.images.show)) return; if (s.data) s = s.data; $.each(s, function (i, p) { if (typeof p[0] == "string") { urls.push(p[0]); points.push(p); } }); }); $.plot.image.load(urls, function (loadedImages) { $.each(points, function (i, p) { var url = p[0]; if (loadedImages[url]) p[0] = loadedImages[url]; }); callback(); }); } $.plot.image.load = function (urls, callback) { var missing = urls.length, loaded = {}; if (missing == 0) callback({}); $.each(urls, function (i, url) { var handler = function () { --missing; loaded[url] = this; if (missing == 0) callback(loaded); }; $('<img />').load(handler).error(handler).attr('src', url); }); }; function drawSeries(plot, ctx, series) { var plotOffset = plot.getPlotOffset(); if (!series.images || !series.images.show) return; var points = series.datapoints.points, ps = series.datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { var img = points[i], x1 = points[i + 1], y1 = points[i + 2], x2 = points[i + 3], y2 = points[i + 4], xaxis = series.xaxis, yaxis = series.yaxis, tmp; // actually we should check img.complete, but it // appears to be a somewhat unreliable indicator in // IE6 (false even after load event) if (!img || img.width <= 0 || img.height <= 0) continue; if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } // if the anchor is at the center of the pixel, expand the // image by 1/2 pixel in each direction if (series.images.anchor == "center") { tmp = 0.5 * (x2-x1) / (img.width - 1); x1 -= tmp; x2 += tmp; tmp = 0.5 * (y2-y1) / (img.height - 1); y1 -= tmp; y2 += tmp; } // clip if (x1 == x2 || y1 == y2 || x1 >= xaxis.max || x2 <= xaxis.min || y1 >= yaxis.max || y2 <= yaxis.min) continue; var sx1 = 0, sy1 = 0, sx2 = img.width, sy2 = img.height; if (x1 < xaxis.min) { sx1 += (sx2 - sx1) * (xaxis.min - x1) / (x2 - x1); x1 = xaxis.min; } if (x2 > xaxis.max) { sx2 += (sx2 - sx1) * (xaxis.max - x2) / (x2 - x1); x2 = xaxis.max; } if (y1 < yaxis.min) { sy2 += (sy1 - sy2) * (yaxis.min - y1) / (y2 - y1); y1 = yaxis.min; } if (y2 > yaxis.max) { sy1 += (sy1 - sy2) * (yaxis.max - y2) / (y2 - y1); y2 = yaxis.max; } x1 = xaxis.p2c(x1); x2 = xaxis.p2c(x2); y1 = yaxis.p2c(y1); y2 = yaxis.p2c(y2); // the transformation may have swapped us if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } tmp = ctx.globalAlpha; ctx.globalAlpha *= series.images.alpha; ctx.drawImage(img, sx1, sy1, sx2 - sx1, sy2 - sy1, x1 + plotOffset.left, y1 + plotOffset.top, x2 - x1, y2 - y1); ctx.globalAlpha = tmp; } } function processRawData(plot, series, data, datapoints) { if (!series.images.show) return; // format is Image, x1, y1, x2, y2 (opposite corners) datapoints.format = [ { required: true }, { x: true, number: true, required: true }, { y: true, number: true, required: true }, { x: true, number: true, required: true }, { y: true, number: true, required: true } ]; } function init(plot) { plot.hooks.processRawData.push(processRawData); plot.hooks.drawSeries.push(drawSeries); } $.plot.plugins.push({ init: init, options: options, name: 'image', version: '1.1' }); })(jQuery);
JavaScript
../src/pwstrength.js
JavaScript
/*jslint vars: false, browser: true, nomen: true, regexp: true */ /*global jQuery */ /* * jQuery Password Strength plugin for Twitter Bootstrap * * Copyright (c) 2008-2013 Tane Piper * Copyright (c) 2013 Alejandro Blanco * Modified By Keenthemes for Bootstrap 3.0 compatibility * * Dual licensed under the MIT and GPL licenses. * */ (function ($) { "use strict"; var options = { errors: [], // Options minChar: 8, errorMessages: { password_to_short: "The Password is too short", same_as_username: "Your password cannot be the same as your username" }, scores: [17, 26, 40, 50], verdicts: ["Weak", "Normal", "Medium", "Strong", "Very Strong"], showVerdictInline: true, // show password verdict inside the progress bar showVerdicts: true, raisePower: 1.4, usernameField: "#username", onLoad: undefined, onKeyUp: undefined, viewports: { progress: undefined, verdict: undefined, errors: undefined }, // Rules stuff ruleScores: { wordNotEmail: -100, wordLength: -100, wordSimilarToUsername: -100, wordLowercase: 1, wordUppercase: 3, wordOneNumber: 3, wordThreeNumbers: 5, wordOneSpecialChar: 3, wordTwoSpecialChar: 5, wordUpperLowerCombo: 2, wordLetterNumberCombo: 2, wordLetterNumberCharCombo: 2 }, rules: { wordNotEmail: true, wordLength: true, wordSimilarToUsername: true, wordLowercase: true, wordUppercase: true, wordOneNumber: true, wordThreeNumbers: true, wordOneSpecialChar: true, wordTwoSpecialChar: true, wordUpperLowerCombo: true, wordLetterNumberCombo: true, wordLetterNumberCharCombo: true }, validationRules: { wordNotEmail: function (options, word, score) { return word.match(/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i) && score; }, wordLength: function (options, word, score) { var wordlen = word.length, lenScore = Math.pow(wordlen, options.raisePower); if (wordlen < options.minChar) { lenScore = (lenScore + score); options.errors.push(options.errorMessages.password_to_short); } return lenScore; }, wordSimilarToUsername: function (options, word, score) { var username = $(options.usernameField).val(); if (username && word.toLowerCase().match(username.toLowerCase())) { options.errors.push(options.errorMessages.same_as_username); return score; } return true; }, wordLowercase: function (options, word, score) { return word.match(/[a-z]/) && score; }, wordUppercase: function (options, word, score) { return word.match(/[A-Z]/) && score; }, wordOneNumber : function (options, word, score) { return word.match(/\d+/) && score; }, wordThreeNumbers : function (options, word, score) { return word.match(/(.*[0-9].*[0-9].*[0-9])/) && score; }, wordOneSpecialChar : function (options, word, score) { return word.match(/.[!,@,#,$,%,\^,&,*,?,_,~]/) && score; }, wordTwoSpecialChar : function (options, word, score) { return word.match(/(.*[!,@,#,$,%,\^,&,*,?,_,~].*[!,@,#,$,%,\^,&,*,?,_,~])/) && score; }, wordUpperLowerCombo : function (options, word, score) { return word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) && score; }, wordLetterNumberCombo : function (options, word, score) { return word.match(/([a-zA-Z])/) && word.match(/([0-9])/) && score; }, wordLetterNumberCharCombo : function (options, word, score) { return word.match(/([a-zA-Z0-9].*[!,@,#,$,%,\^,&,*,?,_,~])|([!,@,#,$,%,\^,&,*,?,_,~].*[a-zA-Z0-9])/) && score; } } }, setProgressBar = function ($el, score) { var options = $el.data("pwstrength"), progressbar = options.progressbar, $verdict; if (options.showVerdictInline) { $verdict = progressbar.find(".progress-bar"); } else { if (options.showVerdicts) { if (options.viewports.verdict) { $verdict = $(options.viewports.verdict).find(".progress-bar"); } else { $verdict = $el.parent().find(".password-verdict"); if ($verdict.length === 0) { $verdict = $('<span class="password-verdict"></span>'); $verdict.insertAfter($el); } } } } if (score < options.scores[0]) { progressbar.find(".progress-bar").css("width", "5%").addClass("progress-bar-danger").removeClass("progress-bar-warning").removeClass("progress-bar-success"); if (options.showVerdicts) { $verdict.text(options.verdicts[0]); } } else if (score >= options.scores[0] && score < options.scores[1]) { progressbar.find(".progress-bar").css("width", "25%").addClass("progress-bar-danger").removeClass("progress-bar-warning").removeClass("progress-bar-success"); if (options.showVerdicts) { $verdict.text(options.verdicts[1]); } } else if (score >= options.scores[1] && score < options.scores[2]) { progressbar.find(".progress-bar").css("width", "50%").addClass("progress-bar-warning").removeClass("progress-bar-danger").removeClass("progress-bar-success"); if (options.showVerdicts) { $verdict.text(options.verdicts[2]); } } else if (score >= options.scores[2] && score < options.scores[3]) { progressbar.find(".progress-bar").css("width", "75%").addClass("progress-bar-warning").removeClass("progress-bar-danger").removeClass("progress-bar-success"); if (options.showVerdicts) { $verdict.text(options.verdicts[3]); } } else if (score >= options.scores[3]) { progressbar.find(".progress-bar").css("width", "100%").addClass("progress-bar-success").removeClass("progress-bar-warning").removeClass("progress-bar-danger"); progressbar.find(".bar").css("width", "100%"); if (options.showVerdicts) { $verdict.text(options.verdicts[4]); } } }, calculateScore = function ($el) { var self = this, word = $el.val(), totalScore = 0, options = $el.data("pwstrength"); $.each(options.rules, function (rule, active) { if (active === true) { var score = options.ruleScores[rule], result = options.validationRules[rule](options, word, score); if (result) { totalScore += result; } } }); setProgressBar($el, totalScore); return totalScore; }, progressWidget = function () { return '<div class="progress"><div class="progress-bar"></div></div>'; }, methods = { init: function (settings) { var self = this, allOptions = $.extend(options, settings); return this.each(function (idx, el) { var $el = $(el), progressbar, verdict; $el.data("pwstrength", allOptions); $el.on("keyup", function (event) { var options = $el.data("pwstrength"); options.errors = []; calculateScore.call(self, $el); if ($.isFunction(options.onKeyUp)) { options.onKeyUp(event); } }); progressbar = $(progressWidget()); if (allOptions.viewports.progress) { $(allOptions.viewports.progress).append(progressbar); } else { progressbar.insertAfter($el); } progressbar.find(".progress-bar").css("width", "0%"); $el.data("pwstrength").progressbar = progressbar; if (!options.showVerdictInline && allOptions.showVerdicts) { verdict = $('<span class="password-verdict">' + allOptions.verdicts[0] + '</span>'); if (allOptions.viewports.verdict) { $(allOptions.viewports.verdict).append(verdict); } else { verdict.insertAfter($el); } } if ($.isFunction(allOptions.onLoad)) { allOptions.onLoad(); } }); }, destroy: function () { this.each(function (idx, el) { var $el = $(el); $el.parent().find("span.password-verdict").remove(); $el.parent().find("div.progress").remove(); $el.parent().find("ul.error-list").remove(); $el.removeData("pwstrength"); }); }, forceUpdate: function () { var self = this; this.each(function (idx, el) { var $el = $(el), options = $el.data("pwstrength"); options.errors = []; calculateScore.call(self, $el); }); }, outputErrorList: function () { this.each(function (idx, el) { var output = '<ul class="error-list">', $el = $(el), errors = $el.data("pwstrength").errors, viewports = $el.data("pwstrength").viewports, verdict; $el.parent().find("ul.error-list").remove(); if (errors.length > 0) { $.each(errors, function (i, item) { output += '<li>' + item + '</li>'; }); output += '</ul>'; if (viewports.errors) { $(viewports.errors).html(output); } else { output = $(output); verdict = $el.parent().find("span.password-verdict"); if (verdict.length > 0) { el = verdict; } output.insertAfter(el); } } }); }, addRule: function (name, method, score, active) { this.each(function (idx, el) { var options = $(el).data("pwstrength"); options.rules[name] = active; options.ruleScores[name] = score; options.validationRules[name] = method; }); }, changeScore: function (rule, score) { this.each(function (idx, el) { $(el).data("pwstrength").ruleScores[rule] = score; }); }, ruleActive: function (rule, active) { this.each(function (idx, el) { $(el).data("pwstrength").rules[rule] = active; }); } }; $.fn.pwstrength = function (method) { var result; if (methods[method]) { result = methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === "object" || !method) { result = methods.init.apply(this, arguments); } else { $.error("Method " + method + " does not exist on jQuery.pwstrength"); } return result; }; }(jQuery));
JavaScript
/* jQuery Tags Input Plugin 1.3.3 Copyright (c) 2011 XOXCO, Inc Documentation for this plugin lives here: http://xoxco.com/clickable/jquery-tags-input Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php ben@xoxco.com */ (function($) { var delimiter = new Array(); var tags_callbacks = new Array(); $.fn.doAutosize = function(o){ var minWidth = $(this).data('minwidth'), maxWidth = $(this).data('maxwidth'), val = '', input = $(this), testSubject = $('#'+$(this).data('tester_id')); if (val === (val = input.val())) {return;} // Enter new content into testSubject var escaped = val.replace(/&/g, '&amp;').replace(/\s/g,' ').replace(/</g, '&lt;').replace(/>/g, '&gt;'); testSubject.html(escaped); // Calculate new width + whether to change var testerWidth = testSubject.width(), newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth, currentWidth = input.width(), isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth) || (newWidth > minWidth && newWidth < maxWidth); // Animate width if (isValidWidthChange) { input.width(newWidth); } }; $.fn.resetAutosize = function(options){ // alert(JSON.stringify(options)); var minWidth = $(this).data('minwidth') || options.minInputWidth || $(this).width(), maxWidth = $(this).data('maxwidth') || options.maxInputWidth || ($(this).closest('.tagsinput').width() - options.inputPadding), val = '', input = $(this), testSubject = $('<tester/>').css({ position: 'absolute', top: -9999, left: -9999, width: 'auto', fontSize: input.css('fontSize'), fontFamily: input.css('fontFamily'), fontWeight: input.css('fontWeight'), letterSpacing: input.css('letterSpacing'), whiteSpace: 'nowrap' }), testerId = $(this).attr('id')+'_autosize_tester'; if(! $('#'+testerId).length > 0){ testSubject.attr('id', testerId); testSubject.appendTo('body'); } input.data('minwidth', minWidth); input.data('maxwidth', maxWidth); input.data('tester_id', testerId); input.css('width', minWidth); }; $.fn.addTag = function(value,options) { options = jQuery.extend({focus:false,callback:true},options); this.each(function() { var id = $(this).attr('id'); var tagslist = $(this).val().split(delimiter[id]); if (tagslist[0] == '') { tagslist = new Array(); } value = jQuery.trim(value); if (options.unique) { var skipTag = $(this).tagExist(value); if(skipTag == true) { //Marks fake input as not_valid to let styling it $('#'+id+'_tag').addClass('not_valid'); } } else { var skipTag = false; } if (value !='' && skipTag != true) { $('<span>').addClass('tag').append( $('<span>').text(value).append('&nbsp;&nbsp;'), $('<a>', { href : '#', title : 'Removing tag', text : 'x' }).click(function () { return $('#' + id).removeTag(escape(value)); }) ).insertBefore('#' + id + '_addTag'); tagslist.push(value); $('#'+id+'_tag').val(''); if (options.focus) { $('#'+id+'_tag').focus(); } else { $('#'+id+'_tag').blur(); } $.fn.tagsInput.updateTagsField(this,tagslist); if (options.callback && tags_callbacks[id] && tags_callbacks[id]['onAddTag']) { var f = tags_callbacks[id]['onAddTag']; f.call(this, value); } if(tags_callbacks[id] && tags_callbacks[id]['onChange']) { var i = tagslist.length; var f = tags_callbacks[id]['onChange']; f.call(this, $(this), tagslist[i-1]); } } }); return false; }; $.fn.removeTag = function(value) { value = unescape(value); this.each(function() { var id = $(this).attr('id'); var old = $(this).val().split(delimiter[id]); $('#'+id+'_tagsinput .tag').remove(); str = ''; for (i=0; i< old.length; i++) { if (old[i]!=value) { str = str + delimiter[id] +old[i]; } } $.fn.tagsInput.importTags(this,str); if (tags_callbacks[id] && tags_callbacks[id]['onRemoveTag']) { var f = tags_callbacks[id]['onRemoveTag']; f.call(this, value); } }); return false; }; $.fn.tagExist = function(val) { var id = $(this).attr('id'); var tagslist = $(this).val().split(delimiter[id]); return (jQuery.inArray(val, tagslist) >= 0); //true when tag exists, false when not }; // clear all existing tags and import new ones from a string $.fn.importTags = function(str) { id = $(this).attr('id'); $('#'+id+'_tagsinput .tag').remove(); $.fn.tagsInput.importTags(this,str); } $.fn.tagsInput = function(options) { var settings = jQuery.extend({ interactive:true, defaultText:'add a tag', minChars:0, width:'300px', height:'100px', autocomplete: {selectFirst: false }, 'hide':true, 'delimiter':',', 'unique':true, removeWithBackspace:true, placeholderColor:'#666666', autosize: true, comfortZone: 20, inputPadding: 6*2 },options); this.each(function() { if (settings.hide) { $(this).hide(); } var id = $(this).attr('id'); if (!id || delimiter[$(this).attr('id')]) { id = $(this).attr('id', 'tags' + new Date().getTime()).attr('id'); } var data = jQuery.extend({ pid:id, real_input: '#'+id, holder: '#'+id+'_tagsinput', input_wrapper: '#'+id+'_addTag', fake_input: '#'+id+'_tag' },settings); delimiter[id] = data.delimiter; if (settings.onAddTag || settings.onRemoveTag || settings.onChange) { tags_callbacks[id] = new Array(); tags_callbacks[id]['onAddTag'] = settings.onAddTag; tags_callbacks[id]['onRemoveTag'] = settings.onRemoveTag; tags_callbacks[id]['onChange'] = settings.onChange; } var markup = '<div id="'+id+'_tagsinput" class="tagsinput"><div id="'+id+'_addTag">'; if (settings.interactive) { markup = markup + '<input id="'+id+'_tag" value="" data-default="'+settings.defaultText+'" />'; } markup = markup + '</div><div class="tags_clear"></div></div>'; $(markup).insertAfter(this); $(data.holder).css('width',settings.width); $(data.holder).css('min-height',settings.height); $(data.holder).css('height','100%'); if ($(data.real_input).val()!='') { $.fn.tagsInput.importTags($(data.real_input),$(data.real_input).val()); } if (settings.interactive) { $(data.fake_input).val($(data.fake_input).attr('data-default')); $(data.fake_input).css('color',settings.placeholderColor); $(data.fake_input).resetAutosize(settings); $(data.holder).bind('click',data,function(event) { $(event.data.fake_input).focus(); }); $(data.fake_input).bind('focus',data,function(event) { if ($(event.data.fake_input).val()==$(event.data.fake_input).attr('data-default')) { $(event.data.fake_input).val(''); } $(event.data.fake_input).css('color','#000000'); }); if (settings.autocomplete_url != undefined) { autocomplete_options = {source: settings.autocomplete_url}; for (attrname in settings.autocomplete) { autocomplete_options[attrname] = settings.autocomplete[attrname]; } if (jQuery.Autocompleter !== undefined) { $(data.fake_input).autocomplete(settings.autocomplete_url, settings.autocomplete); $(data.fake_input).bind('result',data,function(event,data,formatted) { if (data) { $('#'+id).addTag(data[0] + "",{focus:true,unique:(settings.unique)}); } }); } else if (jQuery.ui.autocomplete !== undefined) { $(data.fake_input).autocomplete(autocomplete_options); $(data.fake_input).bind('autocompleteselect',data,function(event,ui) { $(event.data.real_input).addTag(ui.item.value,{focus:true,unique:(settings.unique)}); return false; }); } } else { // if a user tabs out of the field, create a new tag // this is only available if autocomplete is not used. $(data.fake_input).bind('blur',data,function(event) { var d = $(this).attr('data-default'); if ($(event.data.fake_input).val()!='' && $(event.data.fake_input).val()!=d) { if( (event.data.minChars <= $(event.data.fake_input).val().length) && (!event.data.maxChars || (event.data.maxChars >= $(event.data.fake_input).val().length)) ) $(event.data.real_input).addTag($(event.data.fake_input).val(),{focus:true,unique:(settings.unique)}); } else { $(event.data.fake_input).val($(event.data.fake_input).attr('data-default')); $(event.data.fake_input).css('color',settings.placeholderColor); } return false; }); } // if user types a comma, create a new tag $(data.fake_input).bind('keypress',data,function(event) { if (event.which==event.data.delimiter.charCodeAt(0) || event.which==13 ) { event.preventDefault(); if( (event.data.minChars <= $(event.data.fake_input).val().length) && (!event.data.maxChars || (event.data.maxChars >= $(event.data.fake_input).val().length)) ) $(event.data.real_input).addTag($(event.data.fake_input).val(),{focus:true,unique:(settings.unique)}); $(event.data.fake_input).resetAutosize(settings); return false; } else if (event.data.autosize) { $(event.data.fake_input).doAutosize(settings); } }); //Delete last tag on backspace data.removeWithBackspace && $(data.fake_input).bind('keydown', function(event) { if(event.keyCode == 8 && $(this).val() == '') { event.preventDefault(); var last_tag = $(this).closest('.tagsinput').find('.tag:last').text(); var id = $(this).attr('id').replace(/_tag$/, ''); last_tag = last_tag.replace(/[\s]+x$/, ''); $('#' + id).removeTag(escape(last_tag)); $(this).trigger('focus'); } }); $(data.fake_input).blur(); //Removes the not_valid class when user changes the value of the fake input if(data.unique) { $(data.fake_input).keydown(function(event){ if(event.keyCode == 8 || String.fromCharCode(event.which).match(/\w+|[áéíóúÁÉÍÓÚñÑ,/]+/)) { $(this).removeClass('not_valid'); } }); } } // if settings.interactive }); return this; }; $.fn.tagsInput.updateTagsField = function(obj,tagslist) { var id = $(obj).attr('id'); $(obj).val(tagslist.join(delimiter[id])); }; $.fn.tagsInput.importTags = function(obj,val) { $(obj).val(''); var id = $(obj).attr('id'); var tags = val.split(delimiter[id]); for (i=0; i<tags.length; i++) { $(obj).addTag(tags[i],{focus:false,callback:false}); } if(tags_callbacks[id] && tags_callbacks[id]['onChange']) { var f = tags_callbacks[id]['onChange']; f.call(obj, obj, tags[i]); } }; })(jQuery);
JavaScript
/** Core script to handle the entire theme and core functions **/ var App = function () { // IE mode var isRTL = false; var isIE8 = false; var isIE9 = false; var isIE10 = false; var sidebarWidth = 225; var sidebarCollapsedWidth = 35; var responsiveHandlers = []; // theme layout color set var layoutColorCodes = { 'blue': '#4b8df8', 'red': '#e02222', 'green': '#35aa47', 'purple': '#852b99', 'grey': '#555555', 'light-grey': '#fafafa', 'yellow': '#ffb848' }; // To get the correct viewport width based on http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/ var _getViewPort = function () { var e = window, a = 'inner'; if (!('innerWidth' in window)) { a = 'client'; e = document.documentElement || document.body; } return { width: e[a + 'Width'], height: e[a + 'Height'] } } // initializes main settings var handleInit = function () { if ($('body').css('direction') === 'rtl') { isRTL = true; } isIE8 = !! navigator.userAgent.match(/MSIE 8.0/); isIE9 = !! navigator.userAgent.match(/MSIE 9.0/); isIE10 = !! navigator.userAgent.match(/MSIE 10.0/); if (isIE10) { jQuery('html').addClass('ie10'); // detect IE10 version } if (isIE10 || isIE9 || isIE8) { jQuery('html').addClass('ie'); // detect IE10 version } /* Virtual keyboards: Also, note that if you're using inputs in your modal – iOS has a rendering bug which doesn't update the position of fixed elements when the virtual keyboard is triggered */ var deviceAgent = navigator.userAgent.toLowerCase(); if (deviceAgent.match(/(iphone|ipod|ipad)/)) { $(document).on('focus', 'input, textarea', function () { $('.page-header').hide(); $('.page-footer').hide(); }); $(document).on('blur', 'input, textarea', function () { $('.page-header').show(); $('.page-footer').show(); }); } } var handleSidebarState = function () { // remove sidebar toggler if window width smaller than 992(for tablet and phone mode) var viewport = _getViewPort(); if (viewport.width < 992) { $('body').removeClass("page-sidebar-closed"); } } // runs callback functions set by App.addResponsiveHandler(). var runResponsiveHandlers = function () { // reinitialize other subscribed elements for (var i = 0; i < responsiveHandlers.length; i++) { var each = responsiveHandlers[i]; each.call(); } } // reinitialize the laypot on window resize var handleResponsive = function () { handleSidebarState(); handleSidebarAndContentHeight(); handleFixedSidebar(); runResponsiveHandlers(); } // initialize the layout on page load var handleResponsiveOnInit = function () { handleSidebarState(); handleSidebarAndContentHeight(); } // handle the layout reinitialization on window resize var handleResponsiveOnResize = function () { var resize; if (isIE8) { var currheight; $(window).resize(function () { if (currheight == document.documentElement.clientHeight) { return; //quite event since only body resized not window. } if (resize) { clearTimeout(resize); } resize = setTimeout(function () { handleResponsive(); }, 50); // wait 50ms until window resize finishes. currheight = document.documentElement.clientHeight; // store last body client height }); } else { $(window).resize(function () { if (resize) { clearTimeout(resize); } resize = setTimeout(function () { handleResponsive(); }, 50); // wait 50ms until window resize finishes. }); } } //* BEGIN:CORE HANDLERS *// // this function handles responsive layout on screen size resize or mobile device rotate. // Set proper height for sidebar and content. The content and sidebar height must be synced always. var handleSidebarAndContentHeight = function () { var content = $('.page-content'); var sidebar = $('.page-sidebar'); var body = $('body'); var height; if (body.hasClass("page-footer-fixed") === true && body.hasClass("page-sidebar-fixed") === false) { var available_height = $(window).height() - $('.footer').outerHeight() - $('.header').outerHeight(); if (content.height() < available_height) { content.attr('style', 'min-height:' + available_height + 'px !important'); } } else { if (body.hasClass('page-sidebar-fixed')) { height = _calculateFixedSidebarViewportHeight(); } else { height = sidebar.height() + 20; var headerHeight = $('.header').outerHeight(); var footerHeight = $('.footer').outerHeight(); if ($(window).width() > 1024 && (height + headerHeight + footerHeight) < $(window).height()) { height = $(window).height() - headerHeight - footerHeight; } } if (height >= content.height()) { content.attr('style', 'min-height:' + height + 'px !important'); } } } // Handle sidebar menu var handleSidebarMenu = function () { jQuery('.page-sidebar').on('click', 'li > a', function (e) { if ($(this).next().hasClass('sub-menu') == false) { if ($('.btn-navbar').hasClass('collapsed') == false) { $('.btn-navbar').click(); } return; } if ($(this).next().hasClass('sub-menu always-open')) { return; } var parent = $(this).parent().parent(); var the = $(this); var menu = $('.page-sidebar-menu'); var sub = jQuery(this).next(); var autoScroll = menu.data("auto-scroll") ? menu.data("auto-scroll") : true; var slideSpeed = menu.data("slide-speed") ? parseInt(menu.data("slide-speed")) : 200; parent.children('li.open').children('a').children('.arrow').removeClass('open'); parent.children('li.open').children('.sub-menu:not(.always-open)').slideUp(200); parent.children('li.open').removeClass('open'); var slideOffeset = -200; if (sub.is(":visible")) { jQuery('.arrow', jQuery(this)).removeClass("open"); jQuery(this).parent().removeClass("open"); sub.slideUp(slideSpeed, function () { if (autoScroll == true && $('body').hasClass('page-sidebar-closed') == false) { if ($('body').hasClass('page-sidebar-fixed')) { menu.slimScroll({'scrollTo': (the.position()).top}); } else { App.scrollTo(the, slideOffeset); } } handleSidebarAndContentHeight(); }); } else { jQuery('.arrow', jQuery(this)).addClass("open"); jQuery(this).parent().addClass("open"); sub.slideDown(slideSpeed, function () { if (autoScroll == true && $('body').hasClass('page-sidebar-closed') == false) { if ($('body').hasClass('page-sidebar-fixed')) { menu.slimScroll({'scrollTo': (the.position()).top}); } else { App.scrollTo(the, slideOffeset); } } handleSidebarAndContentHeight(); }); } e.preventDefault(); }); // handle ajax links within sidebar menu jQuery('.page-sidebar').on('click', ' li > a.ajaxify', function (e) { e.preventDefault(); App.scrollTop(); var url = $(this).attr("href"); var menuContainer = jQuery('.page-sidebar ul'); var pageContent = $('.page-content'); var pageContentBody = $('.page-content .page-content-body'); menuContainer.children('li.active').removeClass('active'); menuContainer.children('arrow.open').removeClass('open'); $(this).parents('li').each(function () { $(this).addClass('active'); $(this).children('a > span.arrow').addClass('open'); }); $(this).parents('li').addClass('active'); App.startPageLoading(); if ($(window).width() <= 991 && $('.page-sidebar').hasClass("in")) { $('.navbar-toggle').click(); } $.ajax({ type: "GET", cache: false, url: url, dataType: "html", success: function (res) { App.stopPageLoading(); pageContentBody.html(res); App.fixContentHeight(); // fix content height App.initAjax(); // initialize core stuff }, error: function (xhr, ajaxOptions, thrownError) { pageContentBody.html('<h4>Could not load the requested content.</h4>'); App.stopPageLoading(); } }); }); // handle ajax link within main content jQuery('.page-content').on('click', '.ajaxify', function (e) { e.preventDefault(); App.scrollTop(); var url = $(this).attr("href"); var pageContent = $('.page-content'); var pageContentBody = $('.page-content .page-content-body'); App.startPageLoading(); if ($(window).width() <= 991 && $('.page-sidebar').hasClass("in")) { $('.navbar-toggle').click(); } $.ajax({ type: "GET", cache: false, url: url, dataType: "html", success: function (res) { App.stopPageLoading(); pageContentBody.html(res); App.fixContentHeight(); // fix content height App.initAjax(); // initialize core stuff }, error: function (xhr, ajaxOptions, thrownError) { pageContentBody.html('<h4>Could not load the requested content.</h4>'); App.stopPageLoading(); } }); }); } // Helper function to calculate sidebar height for fixed sidebar layout. var _calculateFixedSidebarViewportHeight = function () { var sidebarHeight = $(window).height() - $('.header').height() + 1; if ($('body').hasClass("page-footer-fixed")) { sidebarHeight = sidebarHeight - $('.footer').outerHeight(); } return sidebarHeight; } // Handles fixed sidebar var handleFixedSidebar = function () { var menu = $('.page-sidebar-menu'); if (menu.parent('.slimScrollDiv').size() === 1) { // destroy existing instance before updating the height menu.slimScroll({ destroy: true }); menu.removeAttr('style'); $('.page-sidebar').removeAttr('style'); } if ($('.page-sidebar-fixed').size() === 0) { handleSidebarAndContentHeight(); return; } var viewport = _getViewPort(); if (viewport.width >= 992) { var sidebarHeight = _calculateFixedSidebarViewportHeight(); menu.slimScroll({ size: '7px', color: '#a1b2bd', opacity: .3, position: isRTL ? 'left' : 'right', height: sidebarHeight, allowPageScroll: false, disableFadeOut: false }); handleSidebarAndContentHeight(); } } // Handles the sidebar menu hover effect for fixed sidebar. var handleFixedSidebarHoverable = function () { if ($('body').hasClass('page-sidebar-fixed') === false) { return; } $('.page-sidebar').off('mouseenter').on('mouseenter', function () { var body = $('body'); if ((body.hasClass('page-sidebar-closed') === false || body.hasClass('page-sidebar-fixed') === false) || $(this).hasClass('page-sidebar-hovering')) { return; } body.removeClass('page-sidebar-closed').addClass('page-sidebar-hover-on'); if (body.hasClass("page-sidebar-reversed")) { $(this).width(sidebarWidth); } else { $(this).addClass('page-sidebar-hovering'); $(this).animate({ width: sidebarWidth }, 400, '', function () { $(this).removeClass('page-sidebar-hovering'); }); } }); $('.page-sidebar').off('mouseleave').on('mouseleave', function () { var body = $('body'); if ((body.hasClass('page-sidebar-hover-on') === false || body.hasClass('page-sidebar-fixed') === false) || $(this).hasClass('page-sidebar-hovering')) { return; } if (body.hasClass("page-sidebar-reversed")) { $('body').addClass('page-sidebar-closed').removeClass('page-sidebar-hover-on'); $(this).width(sidebarCollapsedWidth); } else { $(this).addClass('page-sidebar-hovering'); $(this).animate({ width: sidebarCollapsedWidth }, 400, '', function () { $('body').addClass('page-sidebar-closed').removeClass('page-sidebar-hover-on'); $(this).removeClass('page-sidebar-hovering'); }); } }); } // Handles sidebar toggler to close/hide the sidebar. var handleSidebarToggler = function () { var viewport = _getViewPort(); if ($.cookie && $.cookie('sidebar_closed') === '1' && viewport.width >= 992) { $('body').addClass('page-sidebar-closed'); } // handle sidebar show/hide $('.page-sidebar, .header').on('click', '.sidebar-toggler', function (e) { var body = $('body'); var sidebar = $('.page-sidebar'); if ((body.hasClass("page-sidebar-hover-on") && body.hasClass('page-sidebar-fixed')) || sidebar.hasClass('page-sidebar-hovering')) { body.removeClass('page-sidebar-hover-on'); sidebar.css('width', '').hide().show(); handleSidebarAndContentHeight(); //fix content & sidebar height if ($.cookie) { $.cookie('sidebar_closed', '0'); } e.stopPropagation(); runResponsiveHandlers(); return; } $(".sidebar-search", sidebar).removeClass("open"); if (body.hasClass("page-sidebar-closed")) { body.removeClass("page-sidebar-closed"); if (body.hasClass('page-sidebar-fixed')) { sidebar.css('width', ''); } if ($.cookie) { $.cookie('sidebar_closed', '0'); } } else { body.addClass("page-sidebar-closed"); if ($.cookie) { $.cookie('sidebar_closed', '1'); } } handleSidebarAndContentHeight(); //fix content & sidebar height runResponsiveHandlers(); }); // handle the search bar close $('.page-sidebar').on('click', '.sidebar-search .remove', function (e) { e.preventDefault(); $('.sidebar-search').removeClass("open"); }); // handle the search query submit on enter press $('.page-sidebar .sidebar-search').on('keypress', 'input.form-control', function (e) { if (e.which == 13) { $('.sidebar-search').submit(); return false; //<---- Add this line } }); // handle the search submit(for sidebar search and responsive mode of the header search) $('.sidebar-search .submit').on('click', function (e) { e.preventDefault(); if ($('body').hasClass("page-sidebar-closed")) { if ($('.sidebar-search').hasClass('open') == false) { if ($('.page-sidebar-fixed').size() === 1) { $('.page-sidebar .sidebar-toggler').click(); //trigger sidebar toggle button } $('.sidebar-search').addClass("open"); } else { $('.sidebar-search').submit(); } } else { $('.sidebar-search').submit(); } }); // header search box: // handle the search query submit on enter press $('.header .search-form').on('keypress', 'input.form-control', function (e) { if (e.which == 13) { $('.sidebar-search').submit(); return false; //<---- Add this line } }); //handle header search button click $('.header .search-form .submit').on('click', function (e) { e.preventDefault(); $('.header .search-form').submit(); }); } // Handles the horizontal menu var handleHorizontalMenu = function () { //handle hor menu search form toggler click $('.header').on('click', '.hor-menu .hor-menu-search-form-toggler', function (e) { if ($(this).hasClass('off')) { $(this).removeClass('off'); $('.header .hor-menu .search-form').hide(); } else { $(this).addClass('off'); $('.header .hor-menu .search-form').show(); } e.preventDefault(); }); //handle tab click $('.header').on('click', '.hor-menu a[data-toggle="tab"]', function (e) { e.preventDefault(); var nav = $(".hor-menu .nav"); var active_link = nav.find('li.current'); $('li.active', active_link).removeClass("active"); $('.selected', active_link).remove(); var new_link = $(this).parents('li').last(); new_link.addClass("current"); new_link.find("a:first").append('<span class="selected"></span>'); }); //handle hor menu search button click $('.header').on('click', '.hor-menu .search-form .btn', function (e) { $('.form-search').submit(); e.preventDefault(); }); //handle hor menu search form on enter press $('.header').on('keypress', '.hor-menu .search-form input', function (e) { if (e.which == 13) { $('.form-search').submit(); return false; } }); } // Handles the go to top button at the footer var handleGoTop = function () { /* set variables locally for increased performance */ jQuery('.footer').on('click', '.go-top', function (e) { App.scrollTo(); e.preventDefault(); }); } // Handles portlet tools & actions var handlePortletTools = function () { jQuery('body').on('click', '.portlet > .portlet-title > .tools > a.remove', function (e) { e.preventDefault(); jQuery(this).closest(".portlet").remove(); }); jQuery('body').on('click', '.portlet > .portlet-title > .tools > a.reload', function (e) { e.preventDefault(); var el = jQuery(this).closest(".portlet").children(".portlet-body"); var url = jQuery(this).attr("data-url"); var error = $(this).attr("data-error-display"); if (url) { App.blockUI({target: el, iconOnly: true}); $.ajax({ type: "GET", cache: false, url: url, dataType: "html", success: function(res) { App.unblockUI(el); el.html(res); }, error: function(xhr, ajaxOptions, thrownError) { App.unblockUI(el); var msg = 'Error on reloading the content. Please check your connection and try again.'; if (error == "toastr" && toastr) { toastr.error(msg); } else if (error == "notific8" && $.notific8) { $.notific8('zindex', 11500); $.notific8(msg, {theme: 'ruby', life: 3000}); } else { alert(msg); } } }); } else { // for demo purpose App.blockUI({target: el, iconOnly: true}); window.setTimeout(function () { App.unblockUI(el); }, 1000); } }); // load ajax data on page init $('.portlet .portlet-title a.reload[data-load="true"]').click(); jQuery('body').on('click', '.portlet > .portlet-title > .tools > .collapse, .portlet .portlet-title > .tools > .expand', function (e) { e.preventDefault(); var el = jQuery(this).closest(".portlet").children(".portlet-body"); if (jQuery(this).hasClass("collapse")) { jQuery(this).removeClass("collapse").addClass("expand"); el.slideUp(200); } else { jQuery(this).removeClass("expand").addClass("collapse"); el.slideDown(200); } }); } // Handles custom checkboxes & radios using jQuery Uniform plugin var handleUniform = function () { if (!jQuery().uniform) { return; } var test = $("input[type=checkbox]:not(.toggle, .make-switch), input[type=radio]:not(.toggle, .star, .make-switch)"); if (test.size() > 0) { test.each(function () { if ($(this).parents(".checker").size() == 0) { $(this).show(); $(this).uniform(); } }); } } var handleBootstrapSwitch = function () { if (!jQuery().bootstrapSwitch) { return; } $('.make-switch').bootstrapSwitch(); } // Handles Bootstrap Accordions. var handleAccordions = function () { jQuery('body').on('shown.bs.collapse', '.accordion.scrollable', function (e) { App.scrollTo($(e.target)); }); } // Handles Bootstrap Tabs. var handleTabs = function () { // fix content height on tab click $('body').on('shown.bs.tab', '.nav.nav-tabs', function () { handleSidebarAndContentHeight(); }); //activate tab if tab id provided in the URL if (location.hash) { var tabid = location.hash.substr(1); $('a[href="#' + tabid + '"]').parents('.tab-pane:hidden').each(function(){ var tabid = $(this).attr("id"); $('a[href="#' + tabid + '"]').click(); }); $('a[href="#' + tabid + '"]').click(); } } // Handles Bootstrap Modals. var handleModals = function () { // fix stackable modal issue: when 2 or more modals opened, closing one of modal will remove .modal-open class. $('body').on('hide.bs.modal', function () { if ($('.modal:visible').size() > 1 && $('html').hasClass('modal-open') == false) { $('html').addClass('modal-open'); } else if ($('.modal:visible').size() <= 1) { $('html').removeClass('modal-open'); } }); $('body').on('show.bs.modal', '.modal', function () { if ($(this).hasClass("modal-scroll")) { $('body').addClass("modal-open-noscroll"); } }); $('body').on('hide.bs.modal', '.modal', function () { $('body').removeClass("modal-open-noscroll"); }); } // Handles Bootstrap Tooltips. var handleTooltips = function () { jQuery('.tooltips').tooltip(); } // Handles Bootstrap Dropdowns var handleDropdowns = function () { /* Hold dropdown on click */ $('body').on('click', '.dropdown-menu.hold-on-click', function (e) { e.stopPropagation(); }); } // Handle Hower Dropdowns var handleDropdownHover = function () { $('[data-hover="dropdown"]').dropdownHover(); } var handleAlerts = function () { $('body').on('click', '[data-close="alert"]', function(e){ $(this).parent('.alert').hide(); e.preventDefault(); }); } // Handles Bootstrap Popovers // last popep popover var lastPopedPopover; var handlePopovers = function () { jQuery('.popovers').popover(); // close last poped popover $(document).on('click.bs.popover.data-api', function (e) { if (lastPopedPopover) { lastPopedPopover.popover('hide'); } }); } // Handles scrollable contents using jQuery SlimScroll plugin. var handleScrollers = function () { $('.scroller').each(function () { var height; if ($(this).attr("data-height")) { height = $(this).attr("data-height"); } else { height = $(this).css('height'); } $(this).slimScroll({ allowPageScroll: true, // allow page scroll when the element scroll is ended size: '7px', color: ($(this).attr("data-handle-color") ? $(this).attr("data-handle-color") : '#bbb'), railColor: ($(this).attr("data-rail-color") ? $(this).attr("data-rail-color") : '#eaeaea'), position: isRTL ? 'left' : 'right', height: height, alwaysVisible: ($(this).attr("data-always-visible") == "1" ? true : false), railVisible: ($(this).attr("data-rail-visible") == "1" ? true : false), disableFadeOut: true }); }); } // Handles Image Preview using jQuery Fancybox plugin var handleFancybox = function () { if (!jQuery.fancybox) { return; } if (jQuery(".fancybox-button").size() > 0) { jQuery(".fancybox-button").fancybox({ groupAttr: 'data-rel', prevEffect: 'none', nextEffect: 'none', closeBtn: true, helpers: { title: { type: 'inside' } } }); } } // Fix input placeholder issue for IE8 and IE9 var handleFixInputPlaceholderForIE = function () { //fix html5 placeholder attribute for ie7 & ie8 if (isIE8 || isIE9) { // ie8 & ie9 // this is html5 placeholder fix for inputs, inputs with placeholder-no-fix class will be skipped(e.g: we need this for password fields) jQuery('input[placeholder]:not(.placeholder-no-fix), textarea[placeholder]:not(.placeholder-no-fix)').each(function () { var input = jQuery(this); if (input.val() == '' && input.attr("placeholder") != '') { input.addClass("placeholder").val(input.attr('placeholder')); } input.focus(function () { if (input.val() == input.attr('placeholder')) { input.val(''); } }); input.blur(function () { if (input.val() == '' || input.val() == input.attr('placeholder')) { input.val(input.attr('placeholder')); } }); }); } } // Handle full screen mode toggle var handleFullScreenMode = function() { // mozfullscreenerror event handler // toggle full screen function toggleFullScreen() { if (!document.fullscreenElement && // alternative standard method !document.mozFullScreenElement && !document.webkitFullscreenElement) { // current working methods if (document.documentElement.requestFullscreen) { document.documentElement.requestFullscreen(); } else if (document.documentElement.mozRequestFullScreen) { document.documentElement.mozRequestFullScreen(); } else if (document.documentElement.webkitRequestFullscreen) { document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); } } else { if (document.cancelFullScreen) { document.cancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } } } $('#trigger_fullscreen').click(function() { toggleFullScreen(); }); } // Handle Select2 Dropdowns var handleSelect2 = function() { if (jQuery().select2) { $('.select2me').select2({ placeholder: "Select", allowClear: true }); } } // Handle Theme Settings var handleTheme = function () { var panel = $('.theme-panel'); if ($('body').hasClass('page-boxed') == false) { $('.layout-option', panel).val("fluid"); } $('.sidebar-option', panel).val("default"); $('.header-option', panel).val("fixed"); $('.footer-option', panel).val("default"); if ( $('.sidebar-pos-option').attr("disabled") === false) { $('.sidebar-pos-option', panel).val(App.isRTL() ? 'right' : 'left'); } //handle theme layout var resetLayout = function () { $("body"). removeClass("page-boxed"). removeClass("page-footer-fixed"). removeClass("page-sidebar-fixed"). removeClass("page-header-fixed"). removeClass("page-sidebar-reversed"); $('.header > .header-inner').removeClass("container"); if ($('.page-container').parent(".container").size() === 1) { $('.page-container').insertAfter('body > .clearfix'); } if ($('.footer > .container').size() === 1) { $('.footer').html($('.footer > .container').html()); } else if ($('.footer').parent(".container").size() === 1) { $('.footer').insertAfter('.page-container'); } $('body > .container').remove(); } var lastSelectedLayout = ''; var setLayout = function () { var layoutOption = $('.layout-option', panel).val(); var sidebarOption = $('.sidebar-option', panel).val(); var headerOption = $('.header-option', panel).val(); var footerOption = $('.footer-option', panel).val(); var sidebarPosOption = $('.sidebar-pos-option', panel).val(); if (sidebarOption == "fixed" && headerOption == "default") { alert('Default Header with Fixed Sidebar option is not supported. Proceed with Fixed Header with Fixed Sidebar.'); $('.header-option', panel).val("fixed"); $('.sidebar-option', panel).val("fixed"); sidebarOption = 'fixed'; headerOption = 'fixed'; } resetLayout(); // reset layout to default state if (layoutOption === "boxed") { $("body").addClass("page-boxed"); // set header $('.header > .header-inner').addClass("container"); var cont = $('body > .clearfix').after('<div class="container"></div>'); // set content $('.page-container').appendTo('body > .container'); // set footer if (footerOption === 'fixed') { $('.footer').html('<div class="container">' + $('.footer').html() + '</div>'); } else { $('.footer').appendTo('body > .container'); } } if (lastSelectedLayout != layoutOption) { //layout changed, run responsive handler: runResponsiveHandlers(); } lastSelectedLayout = layoutOption; //header if (headerOption === 'fixed') { $("body").addClass("page-header-fixed"); $(".header").removeClass("navbar-static-top").addClass("navbar-fixed-top"); } else { $("body").removeClass("page-header-fixed"); $(".header").removeClass("navbar-fixed-top").addClass("navbar-static-top"); } //sidebar if ($('body').hasClass('page-full-width') === false) { if (sidebarOption === 'fixed') { $("body").addClass("page-sidebar-fixed"); } else { $("body").removeClass("page-sidebar-fixed"); } } //footer if (footerOption === 'fixed') { $("body").addClass("page-footer-fixed"); } else { $("body").removeClass("page-footer-fixed"); } //sidebar position if (App.isRTL()) { if (sidebarPosOption === 'left') { $("body").addClass("page-sidebar-reversed"); $('#frontend-link').tooltip('destroy').tooltip({placement: 'right'}); } else { $("body").removeClass("page-sidebar-reversed"); $('#frontend-link').tooltip('destroy').tooltip({placement: 'left'}); } } else { if (sidebarPosOption === 'right') { $("body").addClass("page-sidebar-reversed"); $('#frontend-link').tooltip('destroy').tooltip({placement: 'left'}); } else { $("body").removeClass("page-sidebar-reversed"); $('#frontend-link').tooltip('destroy').tooltip({placement: 'right'}); } } handleSidebarAndContentHeight(); // fix content height handleFixedSidebar(); // reinitialize fixed sidebar handleFixedSidebarHoverable(); // reinitialize fixed sidebar hover effect } // handle theme colors var setColor = function (color) { var color_ = (App.isRTL() ? color + '-rtl' : color); $('#style_color').attr("href", "assets/css/themes/" + color_ + ".css"); if ($.cookie) { $.cookie('style_color', color); } } $('.toggler', panel).click(function () { $('.toggler').hide(); $('.toggler-close').show(); $('.theme-panel > .theme-options').show(); }); $('.toggler-close', panel).click(function () { $('.toggler').show(); $('.toggler-close').hide(); $('.theme-panel > .theme-options').hide(); }); $('.theme-colors > ul > li', panel).click(function () { var color = $(this).attr("data-style"); setColor(color); $('ul > li', panel).removeClass("current"); $(this).addClass("current"); }); $('.layout-option, .header-option, .sidebar-option, .footer-option, .sidebar-pos-option', panel).change(setLayout); if ($.cookie && $.cookie('style_color')) { setColor($.cookie('style_color')); } } //* END:CORE HANDLERS *// return { //main function to initiate the theme init: function () { //IMPORTANT!!!: Do not modify the core handlers call order. //core handlers handleInit(); // initialize core variables handleResponsiveOnResize(); // set and handle responsive handleUniform(); // hanfle custom radio & checkboxes handleBootstrapSwitch(); // handle bootstrap switch plugin handleScrollers(); // handles slim scrolling contents handleResponsiveOnInit(); // handler responsive elements on page load //layout handlers handleFixedSidebar(); // handles fixed sidebar menu handleFixedSidebarHoverable(); // handles fixed sidebar on hover effect handleSidebarMenu(); // handles main menu handleHorizontalMenu(); // handles horizontal menu handleSidebarToggler(); // handles sidebar hide/show handleFixInputPlaceholderForIE(); // fixes/enables html5 placeholder attribute for IE9, IE8 handleGoTop(); //handles scroll to top functionality in the footer handleTheme(); // handles style customer tool //ui component handlers handleFancybox() // handle fancy box handleSelect2(); // handle custom Select2 dropdowns handlePortletTools(); // handles portlet action bar functionality(refresh, configure, toggle, remove) handleAlerts(); //handle closabled alerts handleDropdowns(); // handle dropdowns handleTabs(); // handle tabs handleTooltips(); // handle bootstrap tooltips handlePopovers(); // handles bootstrap popovers handleAccordions(); //handles accordions handleModals(); // handle modals handleFullScreenMode(); // handles full screen }, //main function to initiate core javascript after ajax complete initAjax: function () { handleScrollers(); // handles slim scrolling contents handleSelect2(); // handle custom Select2 dropdowns handleDropdowns(); // handle dropdowns handleTooltips(); // handle bootstrap tooltips handlePopovers(); // handles bootstrap popovers handleAccordions(); //handles accordions handleUniform(); // hanfle custom radio & checkboxes handleBootstrapSwitch(); // handle bootstrap switch plugin handleDropdownHover() // handles dropdown hover }, //public function to fix the sidebar and content height accordingly fixContentHeight: function () { handleSidebarAndContentHeight(); }, //public function to remember last opened popover that needs to be closed on click setLastPopedPopover: function (el) { lastPopedPopover = el; }, //public function to add callback a function which will be called on window resize addResponsiveHandler: function (func) { responsiveHandlers.push(func); }, // useful function to make equal height for contacts stand side by side setEqualHeight: function (els) { var tallestEl = 0; els = jQuery(els); els.each(function () { var currentHeight = $(this).height(); if (currentHeight > tallestEl) { tallestColumn = currentHeight; } }); els.height(tallestEl); }, // wrapper function to scroll(focus) to an element scrollTo: function (el, offeset) { var pos = (el && el.size() > 0) ? el.offset().top : 0; if (el) { if ($('body').hasClass('page-header-fixed')) { pos = pos - $('.header').height(); } pos = pos + (offeset ? offeset : -1 * el.height()); } jQuery('html,body').animate({ scrollTop: pos }, 'slow'); }, // function to scroll to the top scrollTop: function () { App.scrollTo(); }, // wrapper function to block element(indicate loading) blockUI: function (options) { var options = $.extend(true, {}, options); var html = ''; if (options.iconOnly) { html = '<div class="loading-message ' + (options.boxed ? 'loading-message-boxed' : '')+'"><img style="" src="./assets/img/loading-spinner-grey.gif" align=""></div>'; } else if (options.textOnly) { html = '<div class="loading-message ' + (options.boxed ? 'loading-message-boxed' : '')+'"><span>&nbsp;&nbsp;' + (options.message ? options.message : 'LOADING...') + '</span></div>'; } else { html = '<div class="loading-message ' + (options.boxed ? 'loading-message-boxed' : '')+'"><img style="" src="./assets/img/loading-spinner-grey.gif" align=""><span>&nbsp;&nbsp;' + (options.message ? options.message : 'LOADING...') + '</span></div>'; } if (options.target) { // element blocking var el = jQuery(options.target); if (el.height() <= ($(window).height())) { options.cenrerY = true; } el.block({ message: html, baseZ: options.zIndex ? options.zIndex : 1000, centerY: options.cenrerY != undefined ? options.cenrerY : false, css: { top: '10%', border: '0', padding: '0', backgroundColor: 'none' }, overlayCSS: { backgroundColor: options.overlayColor ? options.overlayColor : '#000', opacity: options.boxed ? 0.05 : 0.1, cursor: 'wait' } }); } else { // page blocking $.blockUI({ message: html, baseZ: options.zIndex ? options.zIndex : 1000, css: { border: '0', padding: '0', backgroundColor: 'none' }, overlayCSS: { backgroundColor: options.overlayColor ? options.overlayColor : '#000', opacity: options.boxed ? 0.05 : 0.1, cursor: 'wait' } }); } }, // wrapper function to un-block element(finish loading) unblockUI: function (target) { if (target) { jQuery(target).unblock({ onUnblock: function () { jQuery(target).css('position', ''); jQuery(target).css('zoom', ''); } }); } else { $.unblockUI(); } }, startPageLoading: function(message) { $('.page-loading').remove(); $('body').append('<div class="page-loading"><img src="assets/img/loading-spinner-grey.gif"/>&nbsp;&nbsp;<span>' + (message ? message : 'Loading...') + '</span></div>'); }, stopPageLoading: function() { $('.page-loading').remove(); }, // initializes uniform elements initUniform: function (els) { if (els) { jQuery(els).each(function () { if ($(this).parents(".checker").size() == 0) { $(this).show(); $(this).uniform(); } }); } else { handleUniform(); } }, //wrapper function to update/sync jquery uniform checkbox & radios updateUniform: function (els) { $.uniform.update(els); // update the uniform checkbox & radios UI after the actual input control state changed }, //public function to initialize the fancybox plugin initFancybox: function () { handleFancybox(); }, //public helper function to get actual input value(used in IE9 and IE8 due to placeholder attribute not supported) getActualVal: function (el) { var el = jQuery(el); if (el.val() === el.attr("placeholder")) { return ""; } return el.val(); }, //public function to get a paremeter by name from URL getURLParameter: function (paramName) { var searchString = window.location.search.substring(1), i, val, params = searchString.split("&"); for (i = 0; i < params.length; i++) { val = params[i].split("="); if (val[0] == paramName) { return unescape(val[1]); } } return null; }, // check for device touch support isTouchDevice: function () { try { document.createEvent("TouchEvent"); return true; } catch (e) { return false; } }, getUniqueID: function(prefix) { return 'prefix_' + Math.floor(Math.random() * (new Date()).getTime()); }, alert: function(options) { options = $.extend(true, { container: "", // alerts parent container(by default placed after the page breadcrumbs) place: "append", // append or prepent in container type: 'success', // alert's type message: "", // alert's message close: true, // make alert closable reset: true, // close all previouse alerts first focus: true, // auto scroll to the alert after shown closeInSeconds: 0, // auto close after defined seconds icon: "" // put icon before the message }, options); var id = App.getUniqueID("app_alert"); var html = '<div id="'+id+'" class="app-alerts alert alert-'+options.type+' fade in">' + (options.close ? '<button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>' : '' ) + (options.icon != "" ? '<i class="fa-lg fa fa-'+options.icon + '"></i> ' : '') + options.message+'</div>' if (options.reset) {0 $('.app-alerts').remove(); } if (!options.container) { $('.page-breadcrumb').after(html); } else { if (options.place == "append") { $(options.container).append(html); } else { $(options.container).prepend(html); } } if (options.focus) { App.scrollTo($('#' + id)); } if (options.closeInSeconds > 0) { setTimeout(function(){ $('#' + id).remove(); }, options.closeInSeconds * 1000); } }, // check IE8 mode isIE8: function () { return isIE8; }, // check IE9 mode isIE9: function () { return isIE9; }, //check RTL mode isRTL: function () { return isRTL; }, // get layout color code by color name getLayoutColorCode: function (name) { if (layoutColorCodes[name]) { return layoutColorCodes[name]; } else { return ''; } } }; }();
JavaScript
/*** Wrapper/Helper Class for datagrid based on jQuery Datatable Plugin ***/ var Datatable = function () { var tableOptions; // main options var dataTable; // datatable object var table; // actual table jquery object var tableContainer; // actual table container object var tableWrapper; // actual table wrapper jquery object var tableInitialized = false; var ajaxParams = []; // set filter mode var countSelectedRecords = function() { var selected = $('tbody > tr > td:nth-child(1) input[type="checkbox"]:checked', table).size(); var text = tableOptions.dataTable.oLanguage.sGroupActions; if (selected > 0) { $('.table-group-actions > span', tableWrapper).text(text.replace("_TOTAL_", selected)); } else { $('.table-group-actions > span', tableWrapper).text(""); } } return { //main function to initiate the module init: function (options) { if (!$().dataTable) { return; } var the = this; // default settings options = $.extend(true, { src: "", // actual table filterApplyAction: "filter", filterCancelAction: "filter_cancel", resetGroupActionInputOnSuccess: true, dataTable: { "sDom" : "<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r><'table-scrollable't><'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'>r>>", // datatable layout "aLengthMenu": [ // set available records per page [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ], "iDisplayLength": 10, // default records per page "oLanguage": { // language settings "sProcessing": '<img src="assets/img/loading-spinner-grey.gif"/><span>&nbsp;&nbsp;Loading...</span>', "sLengthMenu": "<span class='seperator'>|</span>View _MENU_ records", "sInfo": "<span class='seperator'>|</span>Found total _TOTAL_ records", "sInfoEmpty": "No records found to show", "sGroupActions": "_TOTAL_ records selected: ", "sAjaxRequestGeneralError": "Could not complete request. Please check your internet connection", "sEmptyTable": "No data available in table", "sZeroRecords": "No matching records found", "oPaginate": { "sPrevious": "Prev", "sNext": "Next", "sPage": "Page", "sPageOf": "of" } }, "aoColumnDefs" : [{ // define columns sorting options(by default all columns are sortable extept the first checkbox column) 'bSortable' : false, 'aTargets' : [ 0 ] }], "bAutoWidth": false, // disable fixed width and enable fluid table "bSortCellsTop": true, // make sortable only the first row in thead "sPaginationType": "bootstrap_extended", // pagination type(bootstrap, bootstrap_full_number or bootstrap_extended) "bProcessing": true, // enable/disable display message box on record load "bServerSide": true, // enable/disable server side ajax loading "sAjaxSource": "", // define ajax source URL "sServerMethod": "POST", // handle ajax request "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { oSettings.jqXHR = $.ajax( { "dataType": 'json', "type": "POST", "url": sSource, "data": aoData, "success": function(res, textStatus, jqXHR) { if (res.sMessage) { App.alert({type: (res.sStatus == 'OK' ? 'success' : 'danger'), icon: (res.sStatus == 'OK' ? 'check' : 'warning'), message: res.sMessage, container: tableWrapper, place: 'prepend'}); } if (res.sStatus) { if (tableOptions.resetGroupActionInputOnSuccess) { $('.table-group-action-input', tableWrapper).val(""); } } if ($('.group-checkable', table).size() === 1) { $('.group-checkable', table).attr("checked", false); $.uniform.update($('.group-checkable', table)); } if (tableOptions.onSuccess) { tableOptions.onSuccess.call(the); } fnCallback(res, textStatus, jqXHR); }, "error": function() { if (tableOptions.onError) { tableOptions.onError.call(the); } App.alert({type: 'danger', icon: 'warning', message: tableOptions.dataTable.oLanguage.sAjaxRequestGeneralError, container: tableWrapper, place: 'prepend'}); $('.dataTables_processing', tableWrapper).remove(); } } ); }, // pass additional parameter "fnServerParams": function ( aoData ) { //here can be added an external ajax request parameters. for(var i in ajaxParams) { var param = ajaxParams[i]; aoData.push({"name" : param.name, "value": param.value}); } }, "fnDrawCallback": function( oSettings ) { // run some code on table redraw if (tableInitialized === false) { // check if table has been initialized tableInitialized = true; // set table initialized table.show(); // display table } App.initUniform($('input[type="checkbox"]', table)); // reinitialize uniform checkboxes on each table reload countSelectedRecords(); // reset selected records indicator } } }, options); tableOptions = options; // create table's jquery object table = $(options.src); tableContainer = table.parents(".table-container"); // apply the special class that used to restyle the default datatable $.fn.dataTableExt.oStdClasses.sWrapper = $.fn.dataTableExt.oStdClasses.sWrapper + " dataTables_extended_wrapper"; // initialize a datatable dataTable = table.dataTable(options.dataTable); tableWrapper = table.parents('.dataTables_wrapper'); // modify table per page dropdown input by appliying some classes $('.dataTables_length select', tableWrapper).addClass("form-control input-xsmall input-sm"); // build table group actions panel if ($('.table-actions-wrapper', tableContainer).size() === 1) { $('.table-group-actions', tableWrapper).html($('.table-actions-wrapper', tableContainer).html()); // place the panel inside the wrapper $('.table-actions-wrapper', tableContainer).remove(); // remove the template container } // handle group checkboxes check/uncheck $('.group-checkable', table).change(function () { var set = $('tbody > tr > td:nth-child(1) input[type="checkbox"]', table); var checked = $(this).is(":checked"); $(set).each(function () { $(this).attr("checked", checked); }); $.uniform.update(set); countSelectedRecords(); }); // handle row's checkbox click table.on('change', 'tbody > tr > td:nth-child(1) input[type="checkbox"]', function(){ countSelectedRecords(); }); // handle filter submit button click table.on('click', '.filter-submit', function(e){ e.preventDefault(); the.addAjaxParam("sAction", tableOptions.filterApplyAction); // get all typeable inputs $('textarea.form-filter, select.form-filter, input.form-filter:not([type="radio"],[type="checkbox"])', table).each(function(){ the.addAjaxParam($(this).attr("name"), $(this).val()); }); // get all checkable inputs $('input.form-filter[type="checkbox"]:checked, input.form-filter[type="radio"]:checked', table).each(function(){ the.addAjaxParam($(this).attr("name"), $(this).val()); }); dataTable.fnDraw(); the.clearAjaxParams(); }); // handle filter cancel button click table.on('click', '.filter-cancel', function(e){ e.preventDefault(); $('textarea.form-filter, select.form-filter, input.form-filter', table).each(function(){ $(this).val(""); }); $('input.form-filter[type="checkbox"]', table).each(function(){ $(this).attr("checked", false); }); the.addAjaxParam("sAction", tableOptions.filterCancelAction); dataTable.fnDraw(); the.clearAjaxParams(); }); }, getSelectedRowsCount: function() { return $('tbody > tr > td:nth-child(1) input[type="checkbox"]:checked', table).size(); }, getSelectedRows: function() { var rows = []; $('tbody > tr > td:nth-child(1) input[type="checkbox"]:checked', table).each(function(){ rows.push({name: $(this).attr("name"), value: $(this).val()}); }); return rows; }, addAjaxParam: function(name, value) { ajaxParams.push({"name": name, "value": value}); }, clearAjaxParams: function(name, value) { ajaxParams = []; }, getDataTable: function() { return dataTable; }, getTableWrapper: function() { return tableWrapper; }, gettableContainer: function() { return tableContainer; }, getTable: function() { return table; } }; };
JavaScript
var Index = function () { return { //main function init: function () { App.addResponsiveHandler(function () { jQuery('.vmaps').each(function () { var map = jQuery(this); map.width(map.parent().width()); }); }); }, initJQVMAP: function () { var showMap = function (name) { jQuery('.vmaps').hide(); jQuery('#vmap_' + name).show(); } var setMap = function (name) { var data = { map: 'world_en', backgroundColor: null, borderColor: '#333333', borderOpacity: 0.5, borderWidth: 1, color: '#c6c6c6', enableZoom: true, hoverColor: '#c9dfaf', hoverOpacity: null, values: sample_data, normalizeFunction: 'linear', scaleColors: ['#b6da93', '#909cae'], selectedColor: '#c9dfaf', selectedRegion: null, showTooltip: true, onLabelShow: function (event, label, code) { }, onRegionOver: function (event, code) { if (code == 'ca') { event.preventDefault(); } }, onRegionClick: function (element, code, region) { var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase(); alert(message); } }; data.map = name + '_en'; var map = jQuery('#vmap_' + name); if (!map) { return; } map.width(map.parent().parent().width()); map.show(); map.vectorMap(data); map.hide(); } setMap("world"); setMap("usa"); setMap("europe"); setMap("russia"); setMap("germany"); showMap("world"); jQuery('#regional_stat_world').click(function () { showMap("world"); }); jQuery('#regional_stat_usa').click(function () { showMap("usa"); }); jQuery('#regional_stat_europe').click(function () { showMap("europe"); }); jQuery('#regional_stat_russia').click(function () { showMap("russia"); }); jQuery('#regional_stat_germany').click(function () { showMap("germany"); }); $('#region_statistics_loading').hide(); $('#region_statistics_content').show(); }, initCalendar: function () { if (!jQuery().fullCalendar) { return; } var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var h = {}; if ($('#calendar').width() <= 400) { $('#calendar').addClass("mobile"); h = { left: 'title, prev, next', center: '', right: 'today,month,agendaWeek,agendaDay' }; } else { $('#calendar').removeClass("mobile"); if (App.isRTL()) { h = { right: 'title', center: '', left: 'prev,next,today,month,agendaWeek,agendaDay' }; } else { h = { left: 'title', center: '', right: 'prev,next,today,month,agendaWeek,agendaDay' }; } } $('#calendar').fullCalendar('destroy'); // destroy the calendar $('#calendar').fullCalendar({ //re-initialize the calendar disableDragging: false, header: h, editable: true, events: [{ title: 'All Day Event', start: new Date(y, m, 1), backgroundColor: App.getLayoutColorCode('yellow') }, { title: 'Long Event', start: new Date(y, m, d - 5), end: new Date(y, m, d - 2), backgroundColor: App.getLayoutColorCode('green') }, { title: 'Repeating Event', start: new Date(y, m, d - 3, 16, 0), allDay: false, backgroundColor: App.getLayoutColorCode('red') }, { title: 'Repeating Event', start: new Date(y, m, d + 4, 16, 0), allDay: false, backgroundColor: App.getLayoutColorCode('green') }, { title: 'Meeting', start: new Date(y, m, d, 10, 30), allDay: false, }, { title: 'Lunch', start: new Date(y, m, d, 12, 0), end: new Date(y, m, d, 14, 0), backgroundColor: App.getLayoutColorCode('grey'), allDay: false, }, { title: 'Birthday Party', start: new Date(y, m, d + 1, 19, 0), end: new Date(y, m, d + 1, 22, 30), backgroundColor: App.getLayoutColorCode('purple'), allDay: false, }, { title: 'Click for Google', start: new Date(y, m, 28), end: new Date(y, m, 29), backgroundColor: App.getLayoutColorCode('yellow'), url: 'http://google.com/', } ] }); }, initCharts: function () { if (!jQuery.plot) { return; } function showChartTooltip(x, y, xValue, yValue) { $('<div id="tooltip" class="chart-tooltip">'+yValue+'<\/div>').css({ position: 'absolute', display: 'none', top: y - 40, left: x - 40, border: '0px solid #ccc', padding: '2px 6px', 'background-color': '#fff', }).appendTo("body").fadeIn(200); } var data = []; var totalPoints = 250; // random data generator for plot charts function getRandomData() { if (data.length > 0) data = data.slice(1); // do a random walk while (data.length < totalPoints) { var prev = data.length > 0 ? data[data.length - 1] : 50; var y = prev + Math.random() * 10 - 5; if (y < 0) y = 0; if (y > 100) y = 100; data.push(y); } // zip the generated y values with the x values var res = []; for (var i = 0; i < data.length; ++i) res.push([i, data[i]]) return res; } function randValue() { return (Math.floor(Math.random() * (1 + 50 - 20))) + 10; } var visitors = [ ['01/2013', 500], ['02/2013', 1500], ['03/2013', 2600], ['04/2013', 1200], ['05/2013', 560], ['06/2013', 2000], ['07/2013', 2350], ['08/2013', 1500], ['09/2013', 4700], ['10/2013', 1300], ]; if ($('#site_statistics').size() != 0) { $('#site_statistics_loading').hide(); $('#site_statistics_content').show(); var plot_statistics = $.plot($("#site_statistics"), [ { data:visitors, lines: { fill: 0.6, lineWidth: 0, }, color: ['#f89f9f'] }, { data: visitors, points: { show: true, fill: true, radius: 5, fillColor: "#f89f9f", lineWidth: 3 }, color: '#fff', shadowSize: 0 }, ], { xaxis: { tickLength: 0, tickDecimals: 0, mode: "categories", min: 2, font: { lineHeight: 14, style: "normal", variant: "small-caps", color: "#6F7B8A" } }, yaxis: { ticks: 5, tickDecimals: 0, tickColor: "#eee", font: { lineHeight: 14, style: "normal", variant: "small-caps", color: "#6F7B8A" } }, grid: { hoverable: true, clickable: true, tickColor: "#eee", borderColor: "#eee", borderWidth: 1 } }); var previousPoint = null; $("#site_statistics").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showChartTooltip(item.pageX, item.pageY, item.datapoint[0], item.datapoint[1] + ' visits'); } } else { $("#tooltip").remove(); previousPoint = null; } }); } if ($('#load_statistics').size() != 0) { //server load $('#load_statistics_loading').hide(); $('#load_statistics_content').show(); var updateInterval = 30; var plot_statistics = $.plot($("#load_statistics"), [getRandomData()], { series: { shadowSize: 1 }, lines: { show: true, lineWidth: 0.2, fill: true, fillColor: { colors: [{ opacity: 0.1 }, { opacity: 1 } ] } }, yaxis: { ticks: 4, min: 0, max: 100, tickFormatter: function (v) { return v + "%"; }, tickColor: "#eee" }, xaxis: { show: false }, colors: ["#fcb322"], grid: { tickColor: "#a8a3a3", borderWidth: 0 } }); function statisticsUpdate() { plot_statistics.setData([getRandomData()]); plot_statistics.draw(); setTimeout(statisticsUpdate, updateInterval); } statisticsUpdate(); $('#load_statistics').bind("mouseleave", function () { $("#tooltip").remove(); }); } if ($('#site_activities').size() != 0) { //site activities var previousPoint2 = null; $('#site_activities_loading').hide(); $('#site_activities_content').show(); var activities = [ [1, 10], [2, 9], [3, 8], [4, 6], [5, 5], [6, 3], [7, 9], [8, 10], [9, 12], [10, 14], [11, 15], [12, 13], [13, 11], [14, 10], [15, 9], [16, 8], [17, 12], [18, 14], [19, 16], [20, 19], [21, 20], [22, 20], [23, 19], [24, 17], [25, 15], [25, 14], [26, 12], [27, 10], [28, 8], [29, 10], [30, 12], [31, 10], [32, 9], [33, 8], [34, 6], [35, 5], [36, 3], [37, 9], [38, 10], [39, 12], [40, 14], [41, 15], [42, 13], [43, 11], [44, 10], [45, 9], [46, 8], [47, 12], [48, 14], [49, 16], [50, 12], [51, 10] ]; var plot_activities = $.plot( $("#site_activities"), [{ data: activities, color: "rgba(107,207,123, 0.9)", shadowSize: 0, bars: { show: true, lineWidth: 0, fill: true, fillColor: { colors: [{ opacity: 1 }, { opacity: 1 } ] } } } ], { series: { bars: { show: true, barWidth: 0.9 } }, grid: { show: false, hoverable: true, clickable: false, autoHighlight: true, borderWidth: 0 }, yaxis: { min: 0, max: 20 } }); $("#site_activities").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPoint2 != item.dataIndex) { previousPoint2 = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showChartTooltip(item.pageX, item.pageY, item.datapoint[0], item.datapoint[1] + ' activities'); } } }); $('#site_activities').bind("mouseleave", function () { $("#tooltip").remove(); }); } }, initMiniCharts: function () { $('.easy-pie-chart .number.transactions').easyPieChart({ animate: 1000, size: 75, lineWidth: 3, barColor: App.getLayoutColorCode('yellow') }); $('.easy-pie-chart .number.visits').easyPieChart({ animate: 1000, size: 75, lineWidth: 3, barColor: App.getLayoutColorCode('green') }); $('.easy-pie-chart .number.bounce').easyPieChart({ animate: 1000, size: 75, lineWidth: 3, barColor: App.getLayoutColorCode('red') }); $('.easy-pie-chart-reload').click(function(){ $('.easy-pie-chart .number').each(function() { var newValue = Math.floor(100*Math.random()); $(this).data('easyPieChart').update(newValue); $('span', this).text(newValue); }); }); $("#sparkline_bar").sparkline([8,9,10,11,10,10,12,10,10,11,9,12,11,10,9,11,13,13,12], { type: 'bar', width: '100', barWidth: 5, height: '55', barColor: '#35aa47', negBarColor: '#e02222'} ); $("#sparkline_bar2").sparkline([9,11,12,13,12,13,10,14,13,11,11,12,11,11,10,12,11,10], { type: 'bar', width: '100', barWidth: 5, height: '55', barColor: '#ffb848', negBarColor: '#e02222'} ); $("#sparkline_line").sparkline([9,10,9,10,10,11,12,10,10,11,11,12,11,10,12,11,10,12], { type: 'line', width: '100', height: '55', lineColor: '#ffb848' }); }, initChat: function () { var cont = $('#chats'); var list = $('.chats', cont); var form = $('.chat-form', cont); var input = $('input', form); var btn = $('.btn', form); var handleClick = function (e) { e.preventDefault(); var text = input.val(); if (text.length == 0) { return; } var time = new Date(); var time_str = time.toString('MMM dd, yyyy hh:mm'); var tpl = ''; tpl += '<li class="out">'; tpl += '<img class="avatar" alt="" src="assets/img/avatar1.jpg"/>'; tpl += '<div class="message">'; tpl += '<span class="arrow"></span>'; tpl += '<a href="#" class="name">Bob Nilson</a>&nbsp;'; tpl += '<span class="datetime">at ' + time_str + '</span>'; tpl += '<span class="body">'; tpl += text; tpl += '</span>'; tpl += '</div>'; tpl += '</li>'; var msg = list.append(tpl); input.val(""); $('.scroller', cont).slimScroll({ scrollTo: list.height() }); } /* $('.scroller', cont).slimScroll({ scrollTo: list.height() }); */ $('body').on('click', '.message .name', function(e){ e.preventDefault(); // prevent click event var name = $(this).text(); // get clicked user's full name input.val('@' + name + ':'); // set it into the input field App.scrollTo(input); // scroll to input if needed }); btn.click(handleClick); input.keypress(function (e) { if (e.which == 13) { handleClick(); return false; //<---- Add this line } }); }, initDashboardDaterange: function () { $('#dashboard-report-range').daterangepicker({ opens: (App.isRTL() ? 'right' : 'left'), startDate: moment().subtract('days', 29), endDate: moment(), minDate: '01/01/2012', maxDate: '12/31/2014', dateLimit: { days: 60 }, showDropdowns: false, showWeekNumbers: true, timePicker: false, timePickerIncrement: 1, timePicker12Hour: true, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)], 'Last 7 Days': [moment().subtract('days', 6), moment()], 'Last 30 Days': [moment().subtract('days', 29), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')] }, buttonClasses: ['btn'], applyClass: 'blue', cancelClass: 'default', format: 'MM/DD/YYYY', separator: ' to ', locale: { applyLabel: 'Apply', fromLabel: 'From', toLabel: 'To', customRangeLabel: 'Custom Range', daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], firstDay: 1 } }, function (start, end) { console.log("Callback has been called!"); $('#dashboard-report-range span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } ); $('#dashboard-report-range span').html(moment().subtract('days', 29).format('MMMM D, YYYY') + ' - ' + moment().format('MMMM D, YYYY')); $('#dashboard-report-range').show(); }, initIntro: function () { if ($.cookie('intro_show')) { return; } $.cookie('intro_show', 1); setTimeout(function () { var unique_id = $.gritter.add({ // (string | mandatory) the heading of the notification title: 'Meet Metronic!', // (string | mandatory) the text inside the notification text: 'Metronic is a brand new Responsive Admin Dashboard Template you have always been looking for!', // (string | optional) the image to display on the left image: './assets/img/avatar1.jpg', // (bool | optional) if you want it to fade out on its own or just sit there sticky: true, // (int | optional) the time you want it to be alive for before fading out time: '', // (string | optional) the class name you want to apply to that specific message class_name: 'my-sticky-class' }); // You can have it return a unique id, this can be used to manually remove it later using setTimeout(function () { $.gritter.remove(unique_id, { fade: true, speed: 'slow' }); }, 12000); }, 2000); setTimeout(function () { var unique_id = $.gritter.add({ // (string | mandatory) the heading of the notification title: 'Buy Metronic!', // (string | mandatory) the text inside the notification text: 'Metronic comes with a huge collection of reusable and easy customizable UI components and plugins. Buy Metronic today!', // (string | optional) the image to display on the left image: './assets/img/avatar1.jpg', // (bool | optional) if you want it to fade out on its own or just sit there sticky: true, // (int | optional) the time you want it to be alive for before fading out time: '', // (string | optional) the class name you want to apply to that specific message class_name: 'my-sticky-class' }); // You can have it return a unique id, this can be used to manually remove it later using setTimeout(function () { $.gritter.remove(unique_id, { fade: true, speed: 'slow' }); }, 13000); }, 8000); setTimeout(function () { $('#styler').pulsate({ color: "#bb3319", repeat: 10 }); $.extend($.gritter.options, { position: 'top-left' }); var unique_id = $.gritter.add({ position: 'top-left', // (string | mandatory) the heading of the notification title: 'Customize Metronic!', // (string | mandatory) the text inside the notification text: 'Metronic allows you to easily customize the theme colors and layout settings.', // (string | optional) the image to display on the left image1: './assets/img/avatar1.png', // (bool | optional) if you want it to fade out on its own or just sit there sticky: true, // (int | optional) the time you want it to be alive for before fading out time: '', // (string | optional) the class name you want to apply to that specific message class_name: 'my-sticky-class' }); $.extend($.gritter.options, { position: 'top-right' }); // You can have it return a unique id, this can be used to manually remove it later using setTimeout(function () { $.gritter.remove(unique_id, { fade: true, speed: 'slow' }); }, 15000); }, 23000); setTimeout(function () { $.extend($.gritter.options, { position: 'top-left' }); var unique_id = $.gritter.add({ // (string | mandatory) the heading of the notification title: 'Notification', // (string | mandatory) the text inside the notification text: 'You have 3 new notifications.', // (string | optional) the image to display on the left image1: './assets/img/image1.jpg', // (bool | optional) if you want it to fade out on its own or just sit there sticky: true, // (int | optional) the time you want it to be alive for before fading out time: '', // (string | optional) the class name you want to apply to that specific message class_name: 'my-sticky-class' }); setTimeout(function () { $.gritter.remove(unique_id, { fade: true, speed: 'slow' }); }, 4000); $.extend($.gritter.options, { position: 'top-right' }); var number = $('#header_notification_bar .badge').text(); number = parseInt(number); number = number + 3; $('#header_notification_bar .badge').text(number); $('#header_notification_bar').pulsate({ color: "#66bce6", repeat: 5 }); }, 40000); setTimeout(function () { $.extend($.gritter.options, { position: 'top-left' }); var unique_id = $.gritter.add({ // (string | mandatory) the heading of the notification title: 'Inbox', // (string | mandatory) the text inside the notification text: 'You have 2 new messages in your inbox.', // (string | optional) the image to display on the left image1: './assets/img/avatar1.jpg', // (bool | optional) if you want it to fade out on its own or just sit there sticky: true, // (int | optional) the time you want it to be alive for before fading out time: '', // (string | optional) the class name you want to apply to that specific message class_name: 'my-sticky-class' }); $.extend($.gritter.options, { position: 'top-right' }); setTimeout(function () { $.gritter.remove(unique_id, { fade: true, speed: 'slow' }); }, 4000); var number = $('#header_inbox_bar .badge').text(); number = parseInt(number); number = number + 2; $('#header_inbox_bar .badge').text(number); $('#header_inbox_bar').pulsate({ color: "#dd5131", repeat: 5 }); }, 60000); } }; }();
JavaScript
var EcommerceIndex = function () { function showTooltip(x, y, labelX, labelY) { $('<div id="tooltip" class="chart-tooltip">' + (labelY.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')) + 'USD<\/div>').css({ position: 'absolute', display: 'none', top: y - 40, left: x - 60, border: '0px solid #ccc', padding: '2px 6px', 'background-color': '#fff', }).appendTo("body").fadeIn(200); } var initChart1 = function () { var data = [ ['01/2013', 0], ['02/2013', 8], ['03/2013', 10], ['04/2013', 12], ['05/2013', 2125], ['06/2013', 324], ['07/2013', 1223], ['08/2013', 1365], ['09/2013', 250], ['10/2013', 999], ['11/2013', 390], ]; var plot_statistics = $.plot( $("#statistics_1"), [ { data:data, lines: { fill: 0.6, lineWidth: 0, }, color: ['#f89f9f'] }, { data: data, points: { show: true, fill: true, radius: 5, fillColor: "#f89f9f", lineWidth: 3 }, color: '#fff', shadowSize: 0 }, ], { xaxis: { tickLength: 0, tickDecimals: 0, mode: "categories", min: 2, font: { lineHeight: 15, style: "normal", variant: "small-caps", color: "#6F7B8A" } }, yaxis: { ticks: 3, tickDecimals: 0, tickColor: "#f0f0f0", font: { lineHeight: 15, style: "normal", variant: "small-caps", color: "#6F7B8A" } }, grid: { backgroundColor: { colors: ["#fff", "#fff"] }, borderWidth: 1, borderColor: "#f0f0f0", margin: 0, minBorderMargin: 0, labelMargin: 20, hoverable: true, clickable: true, mouseActiveRadius: 6 }, legend: { show: false } } ); var previousPoint = null; $("#statistics_1").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX, item.pageY, item.datapoint[0], item.datapoint[1]); } } else { $("#tooltip").remove(); previousPoint = null; } }); } var initChart2 = function() { var data = [ ['01/2013', 10], ['02/2013', 0], ['03/2013', 10], ['04/2013', 12], ['05/2013', 212], ['06/2013', 324], ['07/2013', 122], ['08/2013', 136], ['09/2013', 250], ['10/2013', 99], ['11/2013', 190], ]; var plot_statistics = $.plot( $("#statistics_2"), [ { data:data, lines: { fill: 0.6, lineWidth: 0, }, color: ['#BAD9F5'] }, { data: data, points: { show: true, fill: true, radius: 5, fillColor: "#BAD9F5", lineWidth: 3 }, color: '#fff', shadowSize: 0 }, ], { xaxis: { tickLength: 0, tickDecimals: 0, mode: "categories", min: 2, font: { lineHeight: 14, style: "normal", variant: "small-caps", color: "#6F7B8A" } }, yaxis: { ticks: 3, tickDecimals: 0, tickColor: "#f0f0f0", font: { lineHeight: 14, style: "normal", variant: "small-caps", color: "#6F7B8A" } }, grid: { backgroundColor: { colors: ["#fff", "#fff"] }, borderWidth: 1, borderColor: "#f0f0f0", margin: 0, minBorderMargin: 0, labelMargin: 20, hoverable: true, clickable: true, mouseActiveRadius: 6 }, legend: { show: false } } ); var previousPoint = null; $("#statistics_2").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX, item.pageY, item.datapoint[0], item.datapoint[1]); } } else { $("#tooltip").remove(); previousPoint = null; } }); } return { //main function init: function () { initChart1(); $('#statistics_amounts_tab').on('shown.bs.tab', function (e) { initChart2(); }); } }; }();
JavaScript