code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
define(['services/request-edit'], function(loadRequestEdit) { 'use strict'; return function(gettextCatalog) { var RequestEdit = loadRequestEdit(gettextCatalog); // Service to edit a overtime declaration, // shared by account/request/worperiod-recover-edit and admin/request/worperiod-recover-edit /** * @param {Resource} unavailableEvents * @param {Object} [user] for admin only */ function getLoadNonWorkingTimes(unavailableEvents, user) { return function(interval) { var queryParams = { dtstart: interval.from, dtend: interval.to }; if (undefined !== user) { queryParams.user = user._id; } return unavailableEvents.query(queryParams).$promise; }; } function getSave($scope) { /** * Action for save button */ return function() { // cleanup object delete $scope.request.requestLog; delete $scope.request.approvalSteps; var q; var quantity_unit = 'H'; if ($scope.request.workperiod_recover[0].recoverQuantity) { quantity_unit = $scope.request.workperiod_recover[0].recoverQuantity.quantity_unit; } if ('H' === quantity_unit) { q = $scope.selection.hours.split(' ')[0]; } else { q = $scope.selection.days.split(' ')[0]; } q = q.replace(',', '.'); $scope.request.workperiod_recover[0].quantity = q; $scope.request.events = $scope.selection.periods; $scope.request.gadaSave($scope.back); }; } function initNewRequest($scope) { $scope.request.events = []; $scope.request.timeCreated = new Date(); $scope.request.workperiod_recover = []; } return { initScope: RequestEdit.initScope, setSelectionFromRequest: RequestEdit.setSelectionFromRequest, getLoadPersonalEvents: RequestEdit.getLoadPersonalEvents, getLoadNonWorkingDaysEvents: RequestEdit.getLoadNonWorkingDaysEvents, getLoadEvents: RequestEdit.getLoadEvents, getLoadScholarHolidays: RequestEdit.getLoadScholarHolidays, onceUserLoaded: RequestEdit.onceUserLoaded, getLoadNonWorkingTimes: getLoadNonWorkingTimes, getSave: getSave, initNewRequest: initNewRequest }; }; });
gadael/gadael
public/js/services/workperiod-recover-edit.js
JavaScript
mit
2,749
/* * Kendo UI Complete v2013.2.918 (http://kendoui.com) * Copyright 2013 Telerik AD. All rights reserved. * * Kendo UI Complete commercial licenses may be obtained at * https://www.kendoui.com/purchase/license-agreement/kendo-ui-complete-commercial.aspx * If you do not own a commercial license, this file shall be governed by the trial license terms. */ kendo_module({ id: "draganddrop", name: "Drag & drop", category: "framework", description: "Drag & drop functionality for any DOM element.", depends: [ "core", "userevents" ] }); (function ($, undefined) { var kendo = window.kendo, support = kendo.support, document = window.document, Class = kendo.Class, Widget = kendo.ui.Widget, Observable = kendo.Observable, UserEvents = kendo.UserEvents, proxy = $.proxy, extend = $.extend, getOffset = kendo.getOffset, draggables = {}, dropTargets = {}, dropAreas = {}, lastDropTarget, OS = support.mobileOS, invalidZeroEvents = OS && OS.android, mobileChrome = (invalidZeroEvents && OS.browser == "chrome"), KEYUP = "keyup", CHANGE = "change", // Draggable events DRAGSTART = "dragstart", DRAG = "drag", DRAGEND = "dragend", DRAGCANCEL = "dragcancel", // DropTarget events DRAGENTER = "dragenter", DRAGLEAVE = "dragleave", DROP = "drop"; function contains(parent, child) { try { return $.contains(parent, child) || parent == child; } catch (e) { return false; } } function elementUnderCursor(e) { if (mobileChrome) { return document.elementFromPoint(e.x.screen, e.y.screen); } else { return document.elementFromPoint(e.x.client, e.y.client); } } function numericCssPropery(element, property) { return parseInt(element.css(property), 10) || 0; } function within(value, range) { return Math.min(Math.max(value, range.min), range.max); } function containerBoundaries(container, element) { var offset = getOffset(container), minX = offset.left + numericCssPropery(container, "borderLeftWidth") + numericCssPropery(container, "paddingLeft"), minY = offset.top + numericCssPropery(container, "borderTopWidth") + numericCssPropery(container, "paddingTop"), maxX = minX + container.width() - element.outerWidth(true), maxY = minY + container.height() - element.outerHeight(true); return { x: { min: minX, max: maxX }, y: { min: minY, max: maxY } }; } function checkTarget(target, targets, areas) { var theTarget, theFilter, i = 0, targetLen = targets && targets.length, areaLen = areas && areas.length; while (target && target.parentNode) { for (i = 0; i < targetLen; i ++) { theTarget = targets[i]; if (theTarget.element[0] === target) { return { target: theTarget, targetElement: target }; } } for (i = 0; i < areaLen; i ++) { theFilter = areas[i]; if (support.matchesSelector.call(target, theFilter.options.filter)) { return { target: theFilter, targetElement: target }; } } target = target.parentNode; } return undefined; } var TapCapture = Observable.extend({ init: function(element, options) { var that = this, domElement = element[0]; that.capture = false; $.each(kendo.eventMap.down.split(" "), function() { domElement.addEventListener(this, proxy(that._press, that), true); }); $.each(kendo.eventMap.up.split(" "), function() { domElement.addEventListener(this, proxy(that._release, that), true); }); Observable.fn.init.call(that); that.bind(["press", "release"], options || {}); }, captureNext: function() { this.capture = true; }, cancelCapture: function() { this.capture = false; }, _press: function(e) { var that = this; that.trigger("press"); if (that.capture) { e.preventDefault(); } }, _release: function(e) { var that = this; that.trigger("release"); if (that.capture) { e.preventDefault(); that.cancelCapture(); } } }); var PaneDimension = Observable.extend({ init: function(options) { var that = this; Observable.fn.init.call(that); that.forcedEnabled = false; $.extend(that, options); that.scale = 1; if (that.horizontal) { that.measure = "offsetWidth"; that.scrollSize = "scrollWidth"; that.axis = "x"; } else { that.measure = "offsetHeight"; that.scrollSize = "scrollHeight"; that.axis = "y"; } }, makeVirtual: function() { $.extend(this, { virtual: true, forcedEnabled: true, _virtualMin: 1000, _virtualMax: -1000 }); }, virtualSize: function(min, max) { if (this._virtualMin !== min || this._virtualMax !== max) { this._virtualMin = min; this._virtualMax = max; this.update(); } }, outOfBounds: function(offset) { return offset > this.max || offset < this.min; }, forceEnabled: function() { this.forcedEnabled = true; }, getSize: function() { return this.container[0][this.measure]; }, getTotal: function() { return this.element[0][this.scrollSize]; }, rescale: function(scale) { this.scale = scale; }, update: function(silent) { var that = this, total = that.virtual ? that._virtualMax : that.getTotal(), scaledTotal = total * that.scale, size = that.getSize(); that.max = that.virtual ? -that._virtualMin : 0; that.size = size; that.total = scaledTotal; that.min = Math.min(that.max, size - scaledTotal); that.minScale = size / total; that.centerOffset = (scaledTotal - size) / 2; that.enabled = that.forcedEnabled || (scaledTotal > size); if (!silent) { that.trigger(CHANGE, that); } } }); var PaneDimensions = Observable.extend({ init: function(options) { var that = this, refresh = proxy(that.refresh, that); Observable.fn.init.call(that); that.x = new PaneDimension(extend({horizontal: true}, options)); that.y = new PaneDimension(extend({horizontal: false}, options)); that.forcedMinScale = options.minScale; that.bind(CHANGE, options); kendo.onResize(refresh); }, rescale: function(newScale) { this.x.rescale(newScale); this.y.rescale(newScale); this.refresh(); }, centerCoordinates: function() { return { x: Math.min(0, -this.x.centerOffset), y: Math.min(0, -this.y.centerOffset) }; }, refresh: function() { var that = this; that.x.update(); that.y.update(); that.enabled = that.x.enabled || that.y.enabled; that.minScale = that.forcedMinScale || Math.min(that.x.minScale, that.y.minScale); that.fitScale = Math.max(that.x.minScale, that.y.minScale); that.trigger(CHANGE); } }); var PaneAxis = Observable.extend({ init: function(options) { var that = this; extend(that, options); Observable.fn.init.call(that); }, dragMove: function(delta) { var that = this, dimension = that.dimension, axis = that.axis, movable = that.movable, position = movable[axis] + delta; if (!dimension.enabled) { return; } if ((position < dimension.min && delta < 0) || (position > dimension.max && delta > 0)) { delta *= that.resistance; } movable.translateAxis(axis, delta); that.trigger(CHANGE, that); } }); var Pane = Class.extend({ init: function(options) { var that = this, x, y, resistance, movable; extend(that, {elastic: true}, options); resistance = that.elastic ? 0.5 : 0; movable = that.movable; that.x = x = new PaneAxis({ axis: "x", dimension: that.dimensions.x, resistance: resistance, movable: movable }); that.y = y = new PaneAxis({ axis: "y", dimension: that.dimensions.y, resistance: resistance, movable: movable }); that.userEvents.bind(["move", "end", "gesturestart", "gesturechange"], { gesturestart: function(e) { that.gesture = e; }, gesturechange: function(e) { var previousGesture = that.gesture, previousCenter = previousGesture.center, center = e.center, scaleDelta = e.distance / previousGesture.distance, minScale = that.dimensions.minScale, coordinates; if (movable.scale <= minScale && scaleDelta < 1) { // Resist shrinking. Instead of shrinking from 1 to 0.5, it will shrink to 0.5 + (1 /* minScale */ - 0.5) * 0.8 = 0.9; scaleDelta += (1 - scaleDelta) * 0.8; } coordinates = { x: (movable.x - previousCenter.x) * scaleDelta + center.x - movable.x, y: (movable.y - previousCenter.y) * scaleDelta + center.y - movable.y }; movable.scaleWith(scaleDelta); x.dragMove(coordinates.x); y.dragMove(coordinates.y); that.dimensions.rescale(movable.scale); that.gesture = e; e.preventDefault(); }, move: function(e) { if (e.event.target.tagName.match(/textarea|input/i)) { return; } if (x.dimension.enabled || y.dimension.enabled) { x.dragMove(e.x.delta); y.dragMove(e.y.delta); e.preventDefault(); } else { e.touch.skip(); } }, end: function(e) { e.preventDefault(); } }); } }); var TRANSFORM_STYLE = support.transitions.prefix + "Transform", translate; if (support.hasHW3D) { translate = function(x, y, scale) { return "translate3d(" + x + "px," + y +"px,0) scale(" + scale + ")"; }; } else { translate = function(x, y, scale) { return "translate(" + x + "px," + y +"px) scale(" + scale + ")"; }; } var Movable = Observable.extend({ init: function(element) { var that = this; Observable.fn.init.call(that); that.element = $(element); that.element[0].style.webkitTransformOrigin = "left top"; that.x = 0; that.y = 0; that.scale = 1; that._saveCoordinates(translate(that.x, that.y, that.scale)); }, translateAxis: function(axis, by) { this[axis] += by; this.refresh(); }, scaleTo: function(scale) { this.scale = scale; this.refresh(); }, scaleWith: function(scaleDelta) { this.scale *= scaleDelta; this.refresh(); }, translate: function(coordinates) { this.x += coordinates.x; this.y += coordinates.y; this.refresh(); }, moveAxis: function(axis, value) { this[axis] = value; this.refresh(); }, moveTo: function(coordinates) { extend(this, coordinates); this.refresh(); }, refresh: function() { var that = this, newCoordinates = translate(that.x, that.y, that.scale); if (newCoordinates != that.coordinates) { that.element[0].style[TRANSFORM_STYLE] = newCoordinates; that._saveCoordinates(newCoordinates); that.trigger(CHANGE); } }, _saveCoordinates: function(coordinates) { this.coordinates = coordinates; } }); var DropTarget = Widget.extend({ init: function(element, options) { var that = this; Widget.fn.init.call(that, element, options); var group = that.options.group; if (!(group in dropTargets)) { dropTargets[group] = [ that ]; } else { dropTargets[group].push( that ); } }, events: [ DRAGENTER, DRAGLEAVE, DROP ], options: { name: "DropTarget", group: "default" }, destroy: function() { var groupName = this.options.group, group = dropTargets[groupName] || dropAreas[groupName], i; if (group.length > 1) { Widget.fn.destroy.call(this); for (i = 0; i < group.length; i++) { if (group[i] == this) { group.splice(i, 1); break; } } } else { DropTarget.destroyGroup(groupName); } }, _trigger: function(eventName, e) { var that = this, draggable = draggables[that.options.group]; if (draggable) { return that.trigger(eventName, extend({}, e.event, { draggable: draggable, dropTarget: e.dropTarget })); } }, _over: function(e) { this._trigger(DRAGENTER, e); }, _out: function(e) { this._trigger(DRAGLEAVE, e); }, _drop: function(e) { var that = this, draggable = draggables[that.options.group]; if (draggable) { draggable.dropped = !that._trigger(DROP, e); } } }); DropTarget.destroyGroup = function(groupName) { var group = dropTargets[groupName] || dropAreas[groupName], i; if (group) { for (i = 0; i < group.length; i++) { Widget.fn.destroy.call(group[i]); } group.length = 0; delete dropTargets[groupName]; delete dropAreas[groupName]; } }; DropTarget._cache = dropTargets; var DropTargetArea = DropTarget.extend({ init: function(element, options) { var that = this; Widget.fn.init.call(that, element, options); var group = that.options.group; if (!(group in dropAreas)) { dropAreas[group] = [ that ]; } else { dropAreas[group].push( that ); } }, options: { name: "DropTargetArea", group: "default", filter: null } }); var Draggable = Widget.extend({ init: function (element, options) { var that = this; Widget.fn.init.call(that, element, options); that.userEvents = new UserEvents(that.element, { global: true, stopPropagation: true, filter: that.options.filter, threshold: that.options.distance, start: proxy(that._start, that), move: proxy(that._drag, that), end: proxy(that._end, that), cancel: proxy(that._cancel, that) }); that._afterEndHandler = proxy(that._afterEnd, that); that.captureEscape = function(e) { if (e.keyCode === kendo.keys.ESC) { that._trigger(DRAGCANCEL, {event: e}); that.userEvents.cancel(); } }; }, events: [ DRAGSTART, DRAG, DRAGEND, DRAGCANCEL ], options: { name: "Draggable", distance: 5, group: "default", cursorOffset: null, axis: null, container: null, dropped: false }, _updateHint: function(e) { var that = this, coordinates, options = that.options, boundaries = that.boundaries, axis = options.axis, cursorOffset = that.options.cursorOffset; if (cursorOffset) { coordinates = { left: e.x.location + cursorOffset.left, top: e.y.location + cursorOffset.top }; } else { that.hintOffset.left += e.x.delta; that.hintOffset.top += e.y.delta; coordinates = $.extend({}, that.hintOffset); } if (boundaries) { coordinates.top = within(coordinates.top, boundaries.y); coordinates.left = within(coordinates.left, boundaries.x); } if (axis === "x") { delete coordinates.top; } else if (axis === "y") { delete coordinates.left; } that.hint.css(coordinates); }, _start: function(e) { var that = this, options = that.options, container = options.container, hint = options.hint; that.currentTarget = e.target; that.currentTargetOffset = getOffset(that.currentTarget); if (hint) { if (that.hint) { that.hint.stop(true, true).remove(); } that.hint = $.isFunction(hint) ? $(hint.call(that, that.currentTarget)) : hint; var offset = getOffset(that.currentTarget); that.hintOffset = offset; that.hint.css( { position: "absolute", zIndex: 20000, // the Window's z-index is 10000 and can be raised because of z-stacking left: offset.left, top: offset.top }) .appendTo(document.body); } draggables[options.group] = that; that.dropped = false; if (container) { that.boundaries = containerBoundaries(container, that.hint); } if (that._trigger(DRAGSTART, e)) { that.userEvents.cancel(); that._afterEnd(); } $(document).on(KEYUP, that.captureEscape); }, _drag: function(e) { var that = this; e.preventDefault(); that._withDropTarget(e, function(target, targetElement) { if (!target) { if (lastDropTarget) { lastDropTarget._trigger(DRAGLEAVE, extend(e, { dropTarget: $(lastDropTarget.targetElement) })); lastDropTarget = null; } return; } if (lastDropTarget) { if (targetElement === lastDropTarget.targetElement) { return; } lastDropTarget._trigger(DRAGLEAVE, extend(e, { dropTarget: $(lastDropTarget.targetElement) })); } target._trigger(DRAGENTER, extend(e, { dropTarget: $(targetElement) })); lastDropTarget = extend(target, { targetElement: targetElement }); }); that._trigger(DRAG, e); if (that.hint) { that._updateHint(e); } }, _end: function(e) { var that = this; that._withDropTarget(e, function(target, targetElement) { if (target) { target._drop(extend({}, e, { dropTarget: $(targetElement) })); lastDropTarget = null; } }); that._trigger(DRAGEND, e); that._cancel(e.event); }, _cancel: function() { var that = this; if (that.hint && !that.dropped) { setTimeout(function() { that.hint.stop(true, true).animate(that.currentTargetOffset, "fast", that._afterEndHandler); }, 0); } else { that._afterEnd(); } }, _trigger: function(eventName, e) { var that = this; return that.trigger( eventName, extend( {}, e.event, { x: e.x, y: e.y, currentTarget: that.currentTarget, dropTarget: e.dropTarget } )); }, _withDropTarget: function(e, callback) { var that = this, target, result, options = that.options, targets = dropTargets[options.group], areas = dropAreas[options.group]; if (targets && targets.length || areas && areas.length) { target = elementUnderCursor(e); if (that.hint && contains(that.hint[0], target)) { that.hint.hide(); target = elementUnderCursor(e); // IE8 does not return the element in iframe from first attempt if (!target) { target = elementUnderCursor(e); } that.hint.show(); } result = checkTarget(target, targets, areas); if (result) { callback(result.target, result.targetElement); } else { callback(); } } }, destroy: function() { var that = this; Widget.fn.destroy.call(that); that._afterEnd(); that.userEvents.destroy(); }, _afterEnd: function() { var that = this; if (that.hint) { that.hint.remove(); } delete draggables[that.options.group]; that.trigger("destroy"); $(document).off(KEYUP, that.captureEscape); } }); kendo.ui.plugin(DropTarget); kendo.ui.plugin(DropTargetArea); kendo.ui.plugin(Draggable); kendo.TapCapture = TapCapture; kendo.containerBoundaries = containerBoundaries; extend(kendo.ui, { Pane: Pane, PaneDimensions: PaneDimensions, Movable: Movable }); })(window.kendo.jQuery);
staafl/team-azure-dragon
src/LearningSystem.App/Scripts/KendoUI/kendo.draganddrop.js
JavaScript
mit
24,537
/* This software is allowed to use under GPL or you need to obtain Commercial or Enterise License to use it in non-GPL project. Please contact [email protected] for details */ scheduler.templates.calendar_month = scheduler.date.date_to_str("%F %Y"); scheduler.templates.calendar_scale_date = scheduler.date.date_to_str("%D"); scheduler.templates.calendar_date = scheduler.date.date_to_str("%d"); scheduler.config.minicalendar = { mark_events: true }; scheduler._synced_minicalendars = []; scheduler.renderCalendar = function(obj, _prev, is_refresh) { var cal = null; var date = obj.date || (scheduler._currentDate()); if (typeof date == "string") date = this.templates.api_date(date); if (!_prev) { var cont = obj.container; var pos = obj.position; if (typeof cont == "string") cont = document.getElementById(cont); if (typeof pos == "string") pos = document.getElementById(pos); if (pos && (typeof pos.left == "undefined")) { var tpos = getOffset(pos); pos = { top: tpos.top + pos.offsetHeight, left: tpos.left }; } if (!cont) cont = scheduler._get_def_cont(pos); cal = this._render_calendar(cont, date, obj); cal.onclick = function(e) { e = e || event; var src = e.target || e.srcElement; if (src.className.indexOf("dhx_month_head") != -1) { var pname = src.parentNode.className; if (pname.indexOf("dhx_after") == -1 && pname.indexOf("dhx_before") == -1) { var newdate = scheduler.templates.xml_date(this.getAttribute("date")); newdate.setDate(parseInt(src.innerHTML, 10)); scheduler.unmarkCalendar(this); scheduler.markCalendar(this, newdate, "dhx_calendar_click"); this._last_date = newdate; if (this.conf.handler) this.conf.handler.call(scheduler, newdate, this); } } }; } else { cal = this._render_calendar(_prev.parentNode, date, obj, _prev); scheduler.unmarkCalendar(cal); } if (scheduler.config.minicalendar.mark_events) { var start = scheduler.date.month_start(date); var end = scheduler.date.add(start, 1, "month"); var evs = this.getEvents(start, end); var filter = this["filter_" + this._mode]; for (var i = 0; i < evs.length; i++) { var ev = evs[i]; if (filter && !filter(ev.id, ev)) continue; var d = ev.start_date; if (d.valueOf() < start.valueOf()) d = start; d = scheduler.date.date_part(new Date(d.valueOf())); while (d < ev.end_date) { this.markCalendar(cal, d, "dhx_year_event"); d = this.date.add(d, 1, "day"); if (d.valueOf() >= end.valueOf()) break; } } } this._markCalendarCurrentDate(cal); cal.conf = obj; if (obj.sync && !is_refresh) this._synced_minicalendars.push(cal); return cal; }; scheduler._get_def_cont = function(pos) { if (!this._def_count) { this._def_count = document.createElement("DIV"); this._def_count.className = "dhx_minical_popup"; this._def_count.onclick = function(e) { (e || event).cancelBubble = true; }; document.body.appendChild(this._def_count); } this._def_count.style.left = pos.left + "px"; this._def_count.style.top = pos.top + "px"; this._def_count._created = new Date(); return this._def_count; }; scheduler._locateCalendar = function(cal, date) { var table = cal.childNodes[2].childNodes[0]; if (typeof date == "string") date = scheduler.templates.api_date(date); var d = cal.week_start + date.getDate() - 1; return table.rows[Math.floor(d / 7)].cells[d % 7].firstChild; }; scheduler.markCalendar = function(cal, date, css) { this._locateCalendar(cal, date).className += " " + css; }; scheduler.unmarkCalendar = function(cal, date, css) { date = date || cal._last_date; css = css || "dhx_calendar_click"; if (!date) return; var el = this._locateCalendar(cal, date); el.className = (el.className || "").replace(RegExp(css, "g")); }; scheduler._week_template = function(width) { var summ = (width || 250); var left = 0; var week_template = document.createElement("div"); var dummy_date = this.date.week_start(scheduler._currentDate()); for (var i = 0; i < 7; i++) { this._cols[i] = Math.floor(summ / (7 - i)); this._render_x_header(i, left, dummy_date, week_template); dummy_date = this.date.add(dummy_date, 1, "day"); summ -= this._cols[i]; left += this._cols[i]; } week_template.lastChild.className += " dhx_scale_bar_last"; return week_template; }; scheduler.updateCalendar = function(obj, sd) { obj.conf.date = sd; this.renderCalendar(obj.conf, obj, true); }; scheduler._mini_cal_arrows = ["&nbsp", "&nbsp"]; scheduler._render_calendar = function(obj, sd, conf, previous) { /*store*/ var ts = scheduler.templates; var temp = this._cols; this._cols = []; var temp2 = this._mode; this._mode = "calendar"; var temp3 = this._colsS; this._colsS = {height: 0}; var temp4 = new Date(this._min_date); var temp5 = new Date(this._max_date); var temp6 = new Date(scheduler._date); var temp7 = ts.month_day; ts.month_day = ts.calendar_date; sd = this.date.month_start(sd); var week_template = this._week_template(obj.offsetWidth - 1); var d; if (previous) d = previous; else { d = document.createElement("DIV"); d.className = "dhx_cal_container dhx_mini_calendar"; } d.setAttribute("date", this.templates.xml_format(sd)); d.innerHTML = "<div class='dhx_year_month'></div><div class='dhx_year_week'>" + week_template.innerHTML + "</div><div class='dhx_year_body'></div>"; d.childNodes[0].innerHTML = this.templates.calendar_month(sd); if (conf.navigation) { var move_minicalendar_date = function(calendar, diff) { var date = scheduler.date.add(calendar._date, diff, "month"); scheduler.updateCalendar(calendar, date); if (scheduler._date.getMonth() == calendar._date.getMonth() && scheduler._date.getFullYear() == calendar._date.getFullYear()) { scheduler._markCalendarCurrentDate(calendar); } }; var css_classnames = ["dhx_cal_prev_button", "dhx_cal_next_button"]; var css_texts = ["left:1px;top:2px;position:absolute;", "left:auto; right:1px;top:2px;position:absolute;"]; var diffs = [-1, 1]; var handler = function(diff) { return function() { if (conf.sync) { var calendars = scheduler._synced_minicalendars; for (var k = 0; k < calendars.length; k++) { move_minicalendar_date(calendars[k], diff); } } else { move_minicalendar_date(d, diff); } } }; for (var j = 0; j < 2; j++) { var arrow = document.createElement("DIV"); //var diff = diffs[j]; arrow.className = css_classnames[j]; arrow.style.cssText = css_texts[j]; arrow.innerHTML = this._mini_cal_arrows[j]; d.firstChild.appendChild(arrow); arrow.onclick = handler(diffs[j]) } } d._date = new Date(sd); d.week_start = (sd.getDay() - (this.config.start_on_monday ? 1 : 0) + 7) % 7; var dd = this.date.week_start(sd); this._reset_month_scale(d.childNodes[2], sd, dd); var r = d.childNodes[2].firstChild.rows; for (var k = r.length; k < 6; k++) { var last_row = r[r.length - 1]; r[0].parentNode.appendChild(last_row.cloneNode(true)); var last_day_number = parseInt(last_row.childNodes[last_row.childNodes.length - 1].childNodes[0].innerHTML); last_day_number = (last_day_number < 10) ? last_day_number : 0; // previous week could end on 28-31, so we should start with 0 for (var ri = 0; ri < r[k].childNodes.length; ri++) { r[k].childNodes[ri].className = "dhx_after"; r[k].childNodes[ri].childNodes[0].innerHTML = scheduler.date.to_fixed(++last_day_number); } } if (!previous) obj.appendChild(d); d.childNodes[1].style.height = (d.childNodes[1].childNodes[0].offsetHeight - 1) + "px"; // dhx_year_week should have height property so that day dates would get correct position. dhx_year_week height = height of it's child (with the day name) /*restore*/ this._cols = temp; this._mode = temp2; this._colsS = temp3; this._min_date = temp4; this._max_date = temp5; scheduler._date = temp6; ts.month_day = temp7; return d; }; scheduler.destroyCalendar = function(cal, force) { if (!cal && this._def_count && this._def_count.firstChild) { if (force || (new Date()).valueOf() - this._def_count._created.valueOf() > 500) cal = this._def_count.firstChild; } if (!cal) return; cal.onclick = null; cal.innerHTML = ""; if (cal.parentNode) cal.parentNode.removeChild(cal); if (this._def_count) this._def_count.style.top = "-1000px"; }; scheduler.isCalendarVisible = function() { if (this._def_count && parseInt(this._def_count.style.top, 10) > 0) return this._def_count; return false; }; scheduler.attachEvent("onTemplatesReady", function() { dhtmlxEvent(document.body, "click", function() { scheduler.destroyCalendar(); }); }); scheduler.templates.calendar_time = scheduler.date.date_to_str("%d-%m-%Y"); scheduler.form_blocks.calendar_time = { render: function() { var html = "<input class='dhx_readonly' type='text' readonly='true'>"; var cfg = scheduler.config; var dt = this.date.date_part(scheduler._currentDate()); var last = 24 * 60, first = 0; if (cfg.limit_time_select) { first = 60 * cfg.first_hour; last = 60 * cfg.last_hour + 1; // to include "17:00" option if time select is limited } dt.setHours(first / 60); html += " <select>"; for (var i = first; i < last; i += this.config.time_step * 1) { // `<` to exclude last "00:00" option var time = this.templates.time_picker(dt); html += "<option value='" + i + "'>" + time + "</option>"; dt = this.date.add(dt, this.config.time_step, "minute"); } html += "</select>"; var full_day = scheduler.config.full_day; return "<div style='height:30px;padding-top:0; font-size:inherit;' class='dhx_section_time'>" + html + "<span style='font-weight:normal; font-size:10pt;'> &nbsp;&ndash;&nbsp; </span>" + html + "</div>"; }, set_value: function(node, value, ev) { var inputs = node.getElementsByTagName("input"); var selects = node.getElementsByTagName("select"); var _init_once = function(inp, date, number) { inp.onclick = function() { scheduler.destroyCalendar(null, true); scheduler.renderCalendar({ position: inp, date: new Date(this._date), navigation: true, handler: function(new_date) { inp.value = scheduler.templates.calendar_time(new_date); inp._date = new Date(new_date); scheduler.destroyCalendar(); if (scheduler.config.event_duration && scheduler.config.auto_end_date && number == 0) { //first element = start date _update_minical_select(); } } }); }; }; if (scheduler.config.full_day) { if (!node._full_day) { var html = "<label class='dhx_fullday'><input type='checkbox' name='full_day' value='true'> " + scheduler.locale.labels.full_day + "&nbsp;</label></input>"; if (!scheduler.config.wide_form) html = node.previousSibling.innerHTML + html; node.previousSibling.innerHTML = html; node._full_day = true; } var input = node.previousSibling.getElementsByTagName("input")[0]; var isFulldayEvent = (scheduler.date.time_part(ev.start_date) == 0 && scheduler.date.time_part(ev.end_date) == 0); input.checked = isFulldayEvent; selects[0].disabled = input.checked; selects[1].disabled = input.checked; input.onclick = function() { if (input.checked == true) { var obj = {}; scheduler.form_blocks.calendar_time.get_value(node, obj); var start_date = scheduler.date.date_part(obj.start_date); var end_date = scheduler.date.date_part(obj.end_date); if (+end_date == +start_date || (+end_date >= +start_date && (ev.end_date.getHours() != 0 || ev.end_date.getMinutes() != 0))) end_date = scheduler.date.add(end_date, 1, "day"); } var start = start_date || ev.start_date; var end = end_date || ev.end_date; _attach_action(inputs[0], start); _attach_action(inputs[1], end); selects[0].value = start.getHours() * 60 + start.getMinutes(); selects[1].value = end.getHours() * 60 + end.getMinutes(); selects[0].disabled = input.checked; selects[1].disabled = input.checked; }; } if (scheduler.config.event_duration && scheduler.config.auto_end_date) { function _update_minical_select() { start_date = scheduler.date.add(inputs[0]._date, selects[0].value, "minute"); end_date = new Date(start_date.getTime() + (scheduler.config.event_duration * 60 * 1000)); inputs[1].value = scheduler.templates.calendar_time(end_date); inputs[1]._date = scheduler.date.date_part(new Date(end_date)); selects[1].value = end_date.getHours() * 60 + end_date.getMinutes(); } selects[0].onchange = _update_minical_select; // only update on first select should trigger update so user could define other end date if he wishes too } function _attach_action(inp, date, number) { _init_once(inp, date, number); inp.value = scheduler.templates.calendar_time(date); inp._date = scheduler.date.date_part(new Date(date)); } _attach_action(inputs[0], ev.start_date, 0); _attach_action(inputs[1], ev.end_date, 1); _init_once = function() {}; selects[0].value = ev.start_date.getHours() * 60 + ev.start_date.getMinutes(); selects[1].value = ev.end_date.getHours() * 60 + ev.end_date.getMinutes(); }, get_value: function(node, ev) { var inputs = node.getElementsByTagName("input"); var selects = node.getElementsByTagName("select"); ev.start_date = scheduler.date.add(inputs[0]._date, selects[0].value, "minute"); ev.end_date = scheduler.date.add(inputs[1]._date, selects[1].value, "minute"); if (ev.end_date <= ev.start_date) ev.end_date = scheduler.date.add(ev.start_date, scheduler.config.time_step, "minute"); }, focus: function(node) { } }; scheduler.linkCalendar = function(calendar, datediff) { var action = function() { var date = scheduler._date; var dateNew = new Date(date.valueOf()); if (datediff) dateNew = datediff(dateNew); dateNew.setDate(1); scheduler.updateCalendar(calendar, dateNew); return true; }; scheduler.attachEvent("onViewChange", action); scheduler.attachEvent("onXLE", action); scheduler.attachEvent("onEventAdded", action); scheduler.attachEvent("onEventChanged", action); scheduler.attachEvent("onAfterEventDelete", action); action(); }; scheduler._markCalendarCurrentDate = function(calendar) { var date = scheduler._date; var mode = scheduler._mode; var month_start = scheduler.date.month_start(new Date(calendar._date)); var month_end = scheduler.date.add(month_start, 1, "month"); if (mode == 'day' || (this._props && !!this._props[mode])) { // if day or units view if (month_start.valueOf() <= date.valueOf() && month_end > date) { scheduler.markCalendar(calendar, date, "dhx_calendar_click"); } } else if (mode == 'week') { var dateNew = scheduler.date.week_start(new Date(date.valueOf())); for (var i = 0; i < 7; i++) { if (month_start.valueOf() <= dateNew.valueOf() && month_end > dateNew) // >= would mean mark first day of the next month scheduler.markCalendar(calendar, dateNew, "dhx_calendar_click"); dateNew = scheduler.date.add(dateNew, 1, "day"); } } }; scheduler.attachEvent("onEventCancel", function(){ scheduler.destroyCalendar(null, true); });
tottaz/yggdrasil
third_party/modules/dhtmlx/sources/ext/dhtmlxscheduler_minical.js
JavaScript
mit
15,580
version https://git-lfs.github.com/spec/v1 oid sha256:376ee7c826f27d7b8c628af1fa07715a8627f4e736f9c3321de71cd97a30d3df size 795
yogeshsaroya/new-cdnjs
ajax/libs/jcarousel/0.3.0-beta.3/jquery.jcarousel-scrollintoview.min.js
JavaScript
mit
128
module.exports = function(config) { var webpackTest = require('./config/webpack.test.js'); var configuration = { basePath: '', frameworks: ['jasmine'], files: [{ pattern: './config/karma-test-shim.js', watched: false }], preprocessors: { './config/karma-test-shim.js': ['coverage', 'webpack', 'sourcemap'] }, webpack: webpackTest, webpackServer: { noInfo: true }, webpackMiddleware: { stats: 'errors-only' }, coverageReporter: { dir : 'coverage/', reporters: [ { type: 'text-summary' }, { type: 'json' }, { type: 'html' } ] }, reporters: [ 'mocha', 'coverage' ], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['Chrome'], singleRun: true }; config.set(configuration); }
seansean11/ng2-webpack
karma.conf.js
JavaScript
mit
820
/** * Created by michal frystacky on 11/27/16. */ var webpack = require('webpack'); // @Ref: https://blog.risingstack.com/the-react-way-getting-started-tutorial/ // @Ref: https://www.codementor.io/tamizhvendan/tutorials/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr // @Ref: http://survivejs.com/webpack/advanced-techniques/configuring-react/ module.exports = { entry: `${__dirname}/src/app.js`, output: { path: `${__dirname}/dist`, filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: 'babel', query: { presets: ['es2015'] } } ] }, plugins: [ new webpack.NoErrorsPlugin ] }
MFry/pyItemCatalog
vagrant/webpack.config.js
JavaScript
mit
857
/* global io */ 'use strict'; angular.module('voteroidApp') .factory('socket', function(socketFactory) { // socket.io now auto-configures its connection when we ommit a connection url var ioSocket = io('', { // Send auth token on connection, you will need to DI the Auth service above // 'query': 'token=' + Auth.getToken() path: '/socket.io-client' }); var socket = socketFactory({ ioSocket }); return { socket, /** * Register listeners to sync an array with updates on a model * * Takes the array we want to sync, the model name that socket updates are sent from, * and an optional callback function after new items are updated. * * @param {String} modelName * @param {Array} array * @param {Function} cb */ syncUpdates(modelName, array, cb) { cb = cb || angular.noop; /** * Syncs item creation/updates on 'model:save' */ socket.on(modelName + ':save', function (item) { var oldItem = _.find(array, {_id: item._id}); var index = array.indexOf(oldItem); var event = 'created'; // replace oldItem if it exists // otherwise just add item to the collection if (oldItem) { array.splice(index, 1, item); event = 'updated'; } else { array.push(item); } cb(event, item, array); }); /** * Syncs removed items on 'model:remove' */ socket.on(modelName + ':remove', function (item) { var event = 'deleted'; _.remove(array, {_id: item._id}); cb(event, item, array); }); }, /** * Removes listeners for a models updates on the socket * * @param modelName */ unsyncUpdates(modelName) { socket.removeAllListeners(modelName + ':save'); socket.removeAllListeners(modelName + ':remove'); } }; });
cmdaniels/voteroid
client/components/socket/socket.service.js
JavaScript
mit
2,031
import earthConstants from '../constants/earth'; // x: [ L, B, h ] export function geodeticToCartesian (x, a=earthConstants.a, e=earthConstants.e) { var N = a / Math.sqrt( 1 - Math.pow(e * Math.sin(x[1]), 2) ); // return [ (N + x[2]) * Math.cos(x[1]) * Math.cos(x[0]), // x (N + x[2]) * Math.cos(x[1]) * Math.sin(x[0]), // y (N * (1 - Math.pow(e, 2)) + x[2]) * Math.sin(x[1]) // z ]; } // x: [ x, y, z ] export function cartesianToGeodetic (x, a=earthConstants.a, e=earthConstants.e) { var L = Math.atan2( x[1], x[0] ), p = Math.hypot( x[0], x[1] ); var Btmp = Math.atan2(x[2], p), N, B, Ztmp; var i = 0; while (i < 100) { N = a / Math.sqrt( 1 - Math.pow(e * Math.sin(Btmp), 2) ); Ztmp = x[2] + Math.pow(e, 2) * N * Math.sin(Btmp); B = Math.atan2(Ztmp, p); if ( Math.abs(B - Btmp) < 1e-15 ) { break; } else { Btmp = B; } i++; } var h = p / Math.cos(B) - N; return [L, B, h]; }
benelsen/orb
src/transformations/geodetic.js
JavaScript
mit
977
import React from 'react'; import { expect } from 'chai'; import { BarChart, Bar, XAxis, YAxis, Tooltip } from 'recharts'; import { mount, render } from 'enzyme'; describe('<BarChart />', () => { const data = [ { name: 'food', uv: 400, pv: 2400 }, { name: 'cosmetic', uv: 300, pv: 4567 }, { name: 'storage', uv: 300, pv: 1398 }, { name: 'digital', uv: 200, pv: 9800 }, ]; it('Renders 8 bars in simple BarChart', () => { const wrapper = render( <BarChart width={100} height={50} data={data}> <Bar dataKey="uv" fill="#ff7300"/> <Bar dataKey="pv" fill="#387908"/> </BarChart> ); expect(wrapper.find('.recharts-rectangle').length).to.equal(8); }); it('Render 4 labels when label is setted to be true', () => { const wrapper = render( <BarChart width={100} height={50} data={data}> <Bar isAnimationActive={false} dataKey="uv" label fill="#ff7300"/> </BarChart> ); expect(wrapper.find('.recharts-bar-rectangle-labels').length).to.equal(1); expect(wrapper.find('.recharts-bar-label').length).to.equal(4); }); it('Renders 4 bar labels when label is set to be a react element', () => { const Label = (props) => { const { x, y, index } = props; return <text key={`label-${index}`} x={x} y={y} className="customized-label">test</text> }; const wrapper = render( <BarChart width={100} height={50} data={data}> <Bar isAnimationActive={false} dataKey="uv" fill="#ff7300" label={<Label/>}/> </BarChart> ); expect(wrapper.find('.customized-label').length).to.equal(4); }); it('Renders 4 bar labels when label is set to be a function', () => { const renderLabel = (props) => { const { x, y, index } = props; return <text key={`label-${index}`} x={x} y={y} className="customized-label">test</text> }; const wrapper = render( <BarChart width={100} height={50} data={data}> <Bar isAnimationActive={false} dataKey="uv" fill="#ff7300" label={renderLabel}/> </BarChart> ); expect(wrapper.find('.customized-label').length).to.equal(4); }); it('Don\'t renders any bars when no Bar item is added', () => { const wrapper = render( <BarChart width={100} height={50} data={data}> </BarChart> ); expect(wrapper.find('.recharts-rectangle').length).to.equal(0); }); it('Renders 8 bars in a vertical BarChart', () => { const wrapper = render( <BarChart width={100} height={50} data={data} layout="vertical"> <XAxis type="number"/> <YAxis type="category" dataKey="name"/> <Bar dataKey="uv" fill="#ff7300"/> <Bar dataKey="pv" fill="#387908"/> </BarChart> ); expect(wrapper.find('.recharts-rectangle').length).to.equal(8); }); it('Renders 8 bars in a stacked BarChart', () => { const wrapper = render( <BarChart width={100} height={50} data={data}> <YAxis /> <Bar dataKey="uv" stackId="test" fill="#ff7300"/> <Bar dataKey="pv" stackId="test" fill="#387908"/> </BarChart> ); expect(wrapper.find('.recharts-rectangle').length).to.equal(8); }); it('Renders 4 bars in a stacked BarChart which only have one Bar', () => { const wrapper = render( <BarChart width={100} height={50} data={data}> <YAxis /> <Bar dataKey="uv" stackId="test" fill="#ff7300"/> </BarChart> ); expect(wrapper.find('.recharts-rectangle').length).to.equal(4); }); // it('Renders tooltip when Tooltip item is added', () => { // const wrapper = mount( // <BarChart width={100} height={50} data={data}> // <Bar dataKey="uv" stackId="test" fill="#ff7300" /> // <Bar dataKey="pv" stackId="test" fill="#387908" /> // <Tooltip /> // </BarChart> // ); // wrapper.setState({ // isTooltipActive: true, // activeTooltipIndex: 3, // activeTooltipLabel: 4, // activeTooltipCoord: { // x: 95, // y: 21, // }, // }); // expect(wrapper.find('.recharts-default-tooltip').length).to.equal(1); // expect(wrapper.find('.recharts-tooltip-wrapper').length).to.equal(1); // }); it('Render empty when data is empty', () => { const wrapper = render( <BarChart width={100} height={50} data={[]}> <Bar dataKey="uv" label fill="#ff7300"/> </BarChart> ); expect(wrapper.find('path').length).to.equal(0); }); it('Render customized shapem when shape is set to be a react element', () => { const Shape = (props) => { const {x, y, width, height} = props; return <circle className="customized-shape" cx={x} cy={y} r={8}/> } const wrapper = render( <BarChart width={100} height={50} data={data}> <Bar dataKey="uv" label fill="#ff7300" shape={<Shape/>}/> </BarChart> ); expect(wrapper.find('.customized-shape').length).to.equal(4); }); it('Render customized shapem when shape is set to be a function', () => { const renderShape = (props) => { const {x, y, width, height} = props; return <circle className="customized-shape" cx={x} cy={y} r={8}/> } const wrapper = render( <BarChart width={100} height={50} data={data}> <Bar dataKey="uv" label fill="#ff7300" shape={renderShape}/> </BarChart> ); expect(wrapper.find('.customized-shape').length).to.equal(4); }); });
thoqbk/recharts
test/specs/chart/BarChartSpec.js
JavaScript
mit
5,445
/** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; module.exports = require('../src/traces/heatmapgl');
aburato/plotly.js
lib/heatmapgl.js
JavaScript
mit
261
(function($){ /** * Transform constructor * @param {String|DOM} [el] */ window.Transform = function(el){ this.term = [ {name: 'translate', unit: 'px', special: true, len: 2}, {name: 'translate3d', unit: 'px', special: true, len: 3}, {name: 'translateX', unit: 'px'}, {name: 'translateY', unit: 'px'}, {name: 'translateZ', unit: 'px'}, // TODO: rotate3d() not work //{name: 'rotate3d', unit: 'deg', special: true}, {name: 'rotate', unit: 'deg'}, {name: 'rotateX', unit: 'deg'}, {name: 'rotateY', unit: 'deg'}, {name: 'rotateZ', unit: 'deg'}, {name: 'scale', unit: '', special: true, len: 2}, {name: 'scaleX', unit: ''}, {name: 'scaleY', unit: ''} ]; var obj = el||''; // object if($.isPlainObject(obj)) this.transform = obj; // dom or string else{ // element if(typeof obj !== 'string'){ var cssPrefixes = ['', '-webkit-', '-moz-', '-o-']; var el = obj.get(0); var good = false; for(var i=0; i<cssPrefixes.length; i++){ if(el.style[cssPrefixes[i]+'transform']){ obj = el.style[cssPrefixes[i]+'transform']; good = true; break; } } if(!good) obj = ''; } this.transform = this.convert(obj); } }; Transform.prototype = { /** * Convert css to object * @param {String} css * @returns {Object} transform element */ convert: function(css){ var transform = css||''; var obj = {}, temp; var name; var i, l; var s, sl; var axe = ['X', 'Y', 'Z']; for(i=0, l=this.term.length; i<l; i++){ name = this.term[i].name; if(transform.indexOf(name+'(') != -1){ temp = transform.substr(transform.indexOf(name+'(')+name.length+1, transform.length); temp = temp.substr(0, temp.indexOf(')')); if(this.term[i].special){ temp = temp.split(','); name = name.indexOf('3d')!=-1? name.substr(0, name.length-2):name; for(s=0, sl=this.term[i].len; s<sl; s++){ obj[name+axe[s]] = parseFloat(temp[s]||((name=='scale')?temp[0]:0)); } } else{ if(name == 'rotate') name += 'Z'; obj[name] = parseFloat(temp); } } } return obj; }, /** * Return unit of element * @param {String} name * @returns {String} unit */ getTermUnit: function(name){ for(var i=0, l=this.term.length; i<l; i++){ if(name == this.term[i].name) return this.term[i].unit; } return ''; }, /** * Return transform object in format Css * @param {Object} aOrder - default object for order * @param {Boolean} [aRound=true] - 0.02 or 0.0197848645 * @returns {String} */ getCssFormat: function(aOrder, aRound){ var round = aRound!==undefined? aRound: true; var order = typeof aOrder=='object'? aOrder:[ 'translateX', 'translateY', 'translateZ', 'scaleX', 'scaleY', 'rotateX', 'rotateY', 'rotateZ' ]; var str = ''; for(var i=0, l=order.length; i<l; i++){ if(this.transform[order[i]] !== undefined){ if(round) this.transform[order[i]] = roundNumber(this.transform[order[i]], 2); str += order[i]+'('+this.transform[order[i]]+this.getTermUnit(order[i])+') '; } } return str; }, /** * Set transform * @param {String} type * @param {Number} val * @param {Boolean} add - val is add * @returns {String} */ set: function(type, val, add){ if(add && this.transform[type]) this.transform[type] += val||0; else this.transform[type] = val||0; return this; }, hasTransform: function(){ for(var key in this.transform){ if(this.transform[key]){ return true; } } return false; }, /** * Get object transform * @param {Boolean|String} opt - true: return all parameter; name: return name of parameter * @returns {Object} */ get: function(opt){ var order = [ 'translateX', 'translateY',// 'translateZ', 'scaleX', 'scaleY', 'rotateX', 'rotateY', 'rotateZ' ]; if(typeof opt==='boolean' && opt){ var obj = {}; for(var i=6; i>=0; i--){ obj[order[i]] = this.transform[order[i]]||(order[i].indexOf('scale')!=-1? 1:0); } return obj; } else if(typeof opt==='string'){ return this.transform[opt]||(opt.indexOf('scale')!=-1? 1:0); } return this.transform; }, /** * Add css string to our object * @param {String|Object} obj */ add: function(obj){ var obj; if(typeof obj === 'string') obj = this.convert(obj); for(var key in obj){ if(this.transform[key]){ this.transform[key] += obj[key]; } else{ this.transform[key] = obj[key]; } } return this; }, /** * Translate transform * @param {Number} x * @param {Number} y * @param {Number} z */ translate: function(x, y, z){ this.set('translateX', x, true); if(y!==undefined || y !== null) this.set('translateY', y, true); if(z!==undefined || z !== null) this.set('translateZ', z, true); return this; }, /** * Rotate transform * @param {Number} x * @param {Number} y * @param {Number} z */ rotate: function(x, y, z){ if(y === undefined || y !== null){ this.set('rotateZ', x); } else{ this.set('rotateX', x); this.set('rotateY', y); if(z!==undefined || y !== null) this.set('rotateZ', z); } return this; }, /** * Scale transform * @param {Number} x * @param {Number} y */ scale: function(x, y){ this.set('scaleX', x); this.set('scaleY', y===undefined || y !== null? x: y); return this; } }; /** * Return round number with offset * @param {Number} n original number * @param {Number} o offset * @returns {Number} */ var roundNumber = function(n, o){ var offset = Math.pow(10, o); n *= offset; n = Math.round(n)/offset; return n; }; })(jQuery);
flavienliger/jQuery-Draggable-Touch
transform-css.js
JavaScript
mit
5,942
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > If thisArg is null or undefined, the called function is passed the global object as the this value es5id: 15.3.4.4_A3_T8 description: > Argument at call function is undefined and it called inside function declaration ---*/ (function FACTORY(){ (function(){this.feat="kamon beyba"}).call(undefined); })(); //CHECK#1 if (this["feat"] !== "kamon beyba") { $ERROR('#1: If thisArg is null or undefined, the called function is passed the global object as the this value'); }
PiotrDabkowski/Js2Py
tests/test_cases/built-ins/Function/prototype/call/S15.3.4.4_A3_T8.js
JavaScript
mit
639
export default /* glsl */` #ifdef MAPTEXTURE uniform sampler2D texture_normalDetailMap; uniform float material_normalDetailMapBumpiness; vec3 blendNormals(vec3 n1, vec3 n2) { // https://blog.selfshadow.com/publications/blending-in-detail/#detail-oriented n1 += vec3(0, 0, 1); n2 *= vec3(-1, -1, 1); return normalize(n1*dot(n1, n2)/n1.z - n2); } #endif vec3 addNormalDetail(vec3 normalMap) { #ifdef MAPTEXTURE vec3 normalDetailMap = unpackNormal(texture2D(texture_normalDetailMap, $UV, textureBias)); normalDetailMap = normalize(mix(vec3(0.0, 0.0, 1.0), normalDetailMap, material_normalDetailMapBumpiness)); return blendNormals(normalMap, normalDetailMap); #else return normalMap; #endif } `;
playcanvas/engine
src/graphics/program-lib/chunks/normalDetailMap.frag.js
JavaScript
mit
738
/** @jsx jsx */ import { jsx } from "@emotion/core"; const IconPanel = ({ children }) => ( <div css={{ display: "flex", flexDirection: "row", width: "96px", height: "48px", position: "absolute", right: 0, zIndex: 1, "& svg": { width: "50%" } }} > {children} </div> ); export default IconPanel;
Mathspy/binary-clock
src/components/IconPanel.js
JavaScript
mit
376
'use strict'; const Big = require('big.js'); const l10n = require('./l10n'); const normalise = require('./number'); let iso4217 = /^[A-Z]{3}$/, roundingMode = 2, // ROUND_HALF_EVEN, banker's rounding zero = new Big(0); function Money(amount, currency) { // Allow new Money('1.2 EUR') if (arguments.length === 1 && typeof amount === 'string') { let i = amount.lastIndexOf(' '); currency = amount.slice(i + 1); amount = amount.slice(0, i); } // Allow new Money(json) if (arguments.length === 1 && typeof amount === 'object') { let o = amount; amount = o.amount; currency = o.currency; } // Validation if (typeof amount === 'string') { amount = normalise(amount); } amount = new Big(amount); if (!iso4217.test(currency)) { throw new Error(`'${currency}' is not a valid ISO-4217 currency code`); } this.amount = Object.freeze(amount); this.currency = currency; Object.freeze(this); } Money.defaultLocale = function() { return undefined; }; Money.defaultLocaleOptions = function() { return undefined; }; Money.forexService = require('./free-forex'); Money.prototype.precision = function precision() { let options = l10n(this.currency).resolvedOptions(); return options.maximumFractionDigits; }; Money.prototype.plus = function plus(that) { if (this.currency !== that.currency) { throw new Error('Currencies must be the same'); } return new Money(this.amount.plus(that.amount), this.currency); }; Money.prototype.minus = function plus(that) { if (this.currency !== that.currency) { throw new Error('Currencies must be the same'); } return new Money(this.amount.minus(that.amount), this.currency); }; Money.prototype.times = function times(that) { if (typeof that !== 'number') { throw new TypeError('Money multiplication needs a Number'); } return new Money(this.amount.times(that), this.currency); }; Money.prototype.allocate = function allocate(ratios, precision) { if (!Array.isArray(ratios)) { throw new TypeError('Money allocation needs an Array'); } if (ratios.length < 1) { throw new TypeError('Money allocation needs a non-empty Array'); } let total = ratios.reduce((a,b) => a + b, 0), amount = this.round(precision), remainder = amount, shares = ratios.map(ratio => { let share = amount.times(ratio / total).round(precision); remainder = remainder.minus(share); return share; }) ; if (remainder.isNotZero()) { shares[0] = shares[0].plus(remainder).round(precision); } return shares; }; Money.prototype.round = function round(precision) { if (precision && !Number.isInteger(precision)) { throw new TypeError('Precision must be an integer'); } if (precision === undefined) { precision = this.precision(); } return new Money(this.amount.round(precision, roundingMode), this.currency); }; Money.prototype.toString = function toString() { return this.amount.toString() + ' ' + this.currency; }; Money.prototype.toLocaleString = function toLocaleString(locale, options) { locale = locale || Money.defaultLocale(); options = options || Money.defaultLocaleOptions(); let rounded = (options && 'maximumFractionDigits' in options) ? this.round(options.maximumFractionDigits) : this.round(); return l10n(locale, this.currency, options).format(Number(rounded.amount)); }; Money.prototype.compare = function compare(that) { if (this.currency !== that.currency) { throw new Error('Currencies must be the same'); } return this.amount.cmp(that.amount); }; Money.prototype.eq = function eq(that) { return this.currency === that.currency && this.compare(that) === 0; }; Money.prototype.ne = function ne(that) { return this.currency !== that.currency || this.compare(that) !== 0; }; Money.prototype.lt = function lt(that) { return this.compare(that) < 0; }; Money.prototype.lte = function lte(that) { return this.compare(that) <= 0; }; Money.prototype.gt = function gt(that) { return this.compare(that) > 0; }; Money.prototype.gte = function gte(that) { return this.compare(that) >= 0; }; Money.prototype.isZero = function isZero() { return this.amount.cmp(zero) === 0; }; Money.prototype.isNotZero = function isNotZero() { return this.amount.cmp(zero) !== 0; }; Money.prototype.isPositive = function isPositive() { return this.amount.cmp(zero) > 0; }; Money.prototype.isNegative = function isNegative() { return this.amount.cmp(zero) < 0; }; Money.prototype.to = function to(currency) { if (this.currency === currency) { return Promise.resolve(this); } if (!iso4217.test(currency)) { return Promise.reject(new Error(`'${currency}' is not a valid ISO-4217 currency code`)); } let self = this; return Money .forexService(self.currency, currency) .then(rate => { try { if (rate === undefined) { return Promise.reject(new Error(`Undefined exchange rate for ${self.currency} to ${currency}`)); } return new Money(self.amount.times(rate), currency); } catch (e) { return Promise.reject(e); } }) ; }; module.exports = Money;
richardschneider/money-works
lib/money.js
JavaScript
mit
5,498
'use strict'; angular .module('court', [ 'ngRoute', 'ui.bootstrap' ]);
Clearent-Gateway/GlobalHackV
src/main/resources/frontend/main/main.js
JavaScript
mit
96
'use strict'; var _ = require('lodash'); var Holodeck = require('../../../../holodeck'); var Request = require('../../../../../../lib/http/request'); var Response = require('../../../../../../lib/http/response'); var Twilio = require('../../../../../../lib'); var client; var holodeck; describe('Transcription', function() { beforeEach(function() { holodeck = new Holodeck(); client = new Twilio('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'AUTHTOKEN', holodeck); }); it('should generate valid fetch request', function() { holodeck.mock(new Response(500, '')); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .transcriptions('TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').fetch(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(Error.prototype.constructor); }); promise.done(); var solution = { accountSid: 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', sid: 'TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var url = _.template('https://api.twilio.com/2010-04-01/Accounts/<%= accountSid %>/Transcriptions/<%= sid %>.json')(solution); holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid fetch response', function() { var body = JSON.stringify({ 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'api_version': '2008-08-01', 'date_created': 'Sun, 13 Feb 2011 02:12:08 +0000', 'date_updated': 'Sun, 13 Feb 2011 02:30:01 +0000', 'duration': '1', 'price': '-0.05000', 'price_unit': 'USD', 'recording_sid': 'REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'sid': 'TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'status': 'failed', 'transcription_text': '(blank)', 'type': 'fast', 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json' }); holodeck.mock(new Response(200, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .transcriptions('TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').fetch(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid remove request', function() { holodeck.mock(new Response(500, '')); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .transcriptions('TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').remove(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(Error.prototype.constructor); }); promise.done(); var solution = { accountSid: 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', sid: 'TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var url = _.template('https://api.twilio.com/2010-04-01/Accounts/<%= accountSid %>/Transcriptions/<%= sid %>.json')(solution); holodeck.assertHasRequest(new Request({ method: 'DELETE', url: url })); } ); it('should generate valid delete response', function() { var body = JSON.stringify(null); holodeck.mock(new Response(204, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .transcriptions('TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').remove(); promise = promise.then(function(response) { expect(response).toBe(true); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid list request', function() { holodeck.mock(new Response(500, '')); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .transcriptions.list(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(Error.prototype.constructor); }); promise.done(); var solution = { accountSid: 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var url = _.template('https://api.twilio.com/2010-04-01/Accounts/<%= accountSid %>/Transcriptions.json')(solution); holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid read_full response', function() { var body = JSON.stringify({ 'end': 0, 'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=1&Page=0', 'last_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=1&Page=3', 'next_page_uri': null, 'num_pages': 4, 'page': 0, 'page_size': 1, 'previous_page_uri': null, 'start': 0, 'total': 4, 'transcriptions': [ { 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'api_version': '2008-08-01', 'date_created': 'Thu, 25 Aug 2011 20:59:45 +0000', 'date_updated': 'Thu, 25 Aug 2011 20:59:45 +0000', 'duration': '10', 'price': '0.00000', 'price_unit': 'USD', 'recording_sid': 'REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'sid': 'TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'status': 'completed', 'transcription_text': null, 'type': 'fast', 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json' } ], 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=1&Page=0' }); holodeck.mock(new Response(200, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .transcriptions.list(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid read_empty response', function() { var body = JSON.stringify({ 'end': 0, 'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=1&Page=0', 'last_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=1&Page=3', 'next_page_uri': null, 'num_pages': 4, 'page': 0, 'page_size': 1, 'previous_page_uri': null, 'start': 0, 'total': 4, 'transcriptions': [], 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=1&Page=0' }); holodeck.mock(new Response(200, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .transcriptions.list(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); });
sagnew/floppy-bird-demo
twilio-temp/spec/integration/rest/api/v2010/account/transcription.spec.js
JavaScript
mit
7,725
return Patchbay; }));
krambuhl/Patchbay
source/build/_after.js
JavaScript
mit
24
Ext.define('Packt.view.toolbar.CancelClearAdd', { extend: 'Ext.toolbar.Toolbar', alias: 'widget.cancelclearadd', flex: 1, dock: 'bottom', ui: 'footer', layout: { pack: 'end', type: 'hbox' }, items: [ { xtype: 'button', text: 'Cancel', itemId: 'cancel', iconCls: 'cancel' }, { xtype: 'button', text: 'Clear', itemId: 'clear', iconCls: 'clear' }, { xtype: 'button', text: 'Add Selected', itemId: 'save', iconCls: 'save' } ] });
Sakchai/CarRental
CarRental.Mvc/Scripts/app/view/toolbar/CancelClearAdd.js
JavaScript
mit
670
var Category = require('../models/category').Category; var User = require('../models/user').User; var Workshop = require('../models/workshop').Workshop; var Product = require('../models/product').Product; var util = require('util'); var async = require('async'); var ServiceProduct = require('../models/serviceproduct').ServiceProduct; /*exports.get = function(req, res) { console.log(req.params.id); var ObjectId = require('mongoose').Types.ObjectId; var objId = new ObjectId((req.params.id.length < 12) ? "123456789012" : req.params.id); async.waterfall([ function(callback){ console.log(req.params.id); Workshop.findOne({ $or: [ {'_id' : objId}, {'alias': req.params.id} ] },callback); },*/ exports.get = function(req, res) { console.log(req.params.id); async.waterfall([ function(callback){ console.log(req.params.id); Workshop.findOne({ $or: [ {'alias': req.params.id} ] },callback); }, function(work, callback){ //ะŸะพะปัƒั‡ะธะผ ะดะตั€ะตะฒะพ ะบะฐั‚ะฐะปะพะณะฐ if (!work) { console.log (work); return res.render('../views/404'); } Category.getCatalogueTree(function(catalogueTree){ callback(null, work, catalogueTree); }); }, function( work, catalogueTree, callback){ Product.getProductsByWorkshop(work._id, function(matchedProducts) { callback(null, work, catalogueTree, matchedProducts); }); }, function( work, catalogueTree, matchedProducts, callback){ var productsWorkshops = []; for (var i in matchedProducts) { productsWorkshops.push(matchedProducts[i]._id); } //console.log('********************' + util.inspect(productsWorkshops)); callback(null, work, catalogueTree, matchedProducts, productsWorkshops); }, function( work, catalogueTree, matchedProducts, productsWorkshops, callback){ var prodWorkInfo = []; function getProductsWorkshop(productid, callback) { process.nextTick(function () { Product.findById(productid, function(err, productobj){ Workshop.findById(productobj._workshopId, function(err, workshoper){ prodWorkInfo[productid] = workshoper; callback(null, prodWorkInfo); }) }); }); } function done(error, result) { callback(null, work, catalogueTree, matchedProducts, prodWorkInfo); } async.map(productsWorkshops, getProductsWorkshop, done); }, function( work, catalogueTree, matchedProducts, prodWorkInfo, callback){ ServiceProduct.find({"type" : "highlight"}, function(err, highlighted){ var highlightarray=[]; for (var i in highlighted) { highlightarray[highlighted[i].productid] = highlighted[i]; } callback(null, work, catalogueTree, matchedProducts, prodWorkInfo, highlightarray); }); }, function( work, catalogueTree, matchedProducts, prodWorkInfo, highlightarray, callback) { Workshop.findById(work._id, function(err, workshoptocustomer){ callback(null, work, catalogueTree, matchedProducts, prodWorkInfo, highlightarray,workshoptocustomer ) }) } ], function (err, work, catalogueTree, matchedProducts, prodWorkInfo, highlightarray, workshoptocustomer) { console.log(workshoptocustomer); workshoptocustomer.views += 1; workshoptocustomer.save(function() { console.log('Views updated'); }) res.render('workshop', { datka:catalogueTree, path: req.path, matchedProducts:matchedProducts, prodWorkInfo:prodWorkInfo, highlightarray:highlightarray, workshoptocustomer:workshoptocustomer }); }); };
iobotstoboi/lavka
routes/workshop-new.js
JavaScript
mit
4,460
#!/usr/bin/env node require('../'); var japan = { // moustache scope / opts getBig: $$in(function Japan(delay, resolve, reject, notify) { setTimeout(function it( takes, time, to, get, big, In, Japan ) { resolve([ 'Big in Japan-tonight', 'Big in Japan-be-tight', 'Big in Japan ooh the eastern sea\'s so .blue' ]) }, delay); }), home: process.env.HOME, player: process.env.MP3_PLAYER } $$in(japan, function( Japan, // in. {{ getBig(1000) }} ooh, // in. {{ console.log "when you're #{Big}" for Big in Japan }} the // in. {{ resolve "eastern sea's so .blue" }} ){}).then( $$in(japan, function(result, play){ // in. $ {{player}} {{home}}/music/Alphaville/Big\ In\ Japan.mp3 console.log(play) }), function(err) { // TODO: - how to get err into $$in above as error // - or is that a bad idea? // - rather fall to catch... // } );
nomilous/in.
in.jokes/big-in.japan('All right!').js
JavaScript
mit
944
version https://git-lfs.github.com/spec/v1 oid sha256:de80c5f52e74ecdd67683b2375705bfabd2ff87351bf546c7576f08c1379382a size 9446
yogeshsaroya/new-cdnjs
ajax/libs/mathjax/1.1a/extensions/TeX/AMSmath.js
JavaScript
mit
129
(function() {var implementors = {}; implementors['pcap'] = ["impl <a class='trait' href='https://doc.rust-lang.org/nightly/core/fmt/trait.Display.html' title='core::fmt::Display'>Display</a> for <a class='enum' href='pcap/enum.Error.html' title='pcap::Error'>Error</a>",]; if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })()
ebfull/ebfull.github.io
pcap/implementors/core/fmt/trait.Display.js
JavaScript
mit
491
/* * grunt-jsdoc-docset * https://github.com/alexb/grunt-jsdoc-docset * * Copyright (c) 2014 Alexandrine Boissiere * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); // By default, lint and run all tests. grunt.registerTask('default', ['jshint']); };
theasta/grunt-jsdoc-docset
Gruntfile.js
JavaScript
mit
693
'use strict'; var _globals = { apiAddress: 'https://platform.api.onesky.io/' }; module.exports = _globals;
brainly/nodejs-onesky-utils
lib/globals.js
JavaScript
mit
112
$(document).on('page:change', function(){ $( "<b>URL's</b>" ).replaceAll('td#sch_url'); });
ecbohler/onescholarship_rails
app/assets/javascripts/scholarships.js
JavaScript
mit
91
import { type } from "superouter"; const routeConfig = { Home: "/", Login: "/login", Settings: "/settings", Tea: "/tea", TeaDetails: "/tea/:id", TeaSearch: "/tea/search", NotFound: "/...any" }; export const Route = type("Route", routeConfig); export const routes = keys => fn => keys.reduce((result, key) => Object.assign(result, { [key]: fn }), {}); export const allRoutes = routes(Object.keys(routeConfig));
foxdonut/meiosis
docs/code/router-setup/superouter-common/src/router/index.js
JavaScript
mit
430
// modified from http://html5demos.com/file-api var $gcode = $('html'); $gcode.on('dragover', function(e) { this.className = 'hover'; e.preventDefault(); e.stopPropagation(); return false; }); $gcode.on('dragend', function(e) { this.className = ''; e.preventDefault(); e.stopPropagation(); return false; }); $gcode.on('drop', function(e){ this.className = ''; e.preventDefault(); e.stopPropagation(); var file = e.originalEvent.dataTransfer.files[0]; var reader = new FileReader(); reader.readAsText(file); reader.onload = function(event) { $('#gcode').val(event.target.result); $('#simstart').click(); }; return false; });
techninja/PancakeBot-simulator
sim.js
JavaScript
mit
671
// gulp-util is used to created well-formed plugin errors var gutil = require('gulp-util'); var _ = require('lodash'); var through = require('through2'); var readmeBuilder = require('./readmeBuilder.js'); // The main function for the plugin โ€“ what the user calls โ€“ should return // a stream. var buildReadmePlugin = function() { return through.obj(function(file, encoding, callback) { var readmeString = readmeBuilder.compileToMdFormat(); var error = null; if (!_.isString(readmeString)) { error = gutil.PluginError('gulp-buildReadme', 'readmeBuilder returned ' + readmeString); } var fileContents = new Buffer(readmeString); if (file.isBuffer()) { file.contents = fileContents; } callback(error, file); }); }; // Export the plugin main function module.exports = buildReadmePlugin;
JSystemsTech/lodash-collection-helpers
gulpCustomPlugins/build-readme.js
JavaScript
mit
859
import can from 'can/'; import 'can/map/define/'; let VM = can.Map.extend({ define: { // `files` is the gateway to get into the uploads. Set a list of files here // and it will be pushed into the uploads array. files: { set(files){ return files; } }, /** * The `done` attribute is a boolean that is false until there are no * `pending` or `uploading` files. Once it becomes true, it increments the * viewModel's `currentBatch` number. */ done: { get(){ let files = this.attr('files'), done = true; if (files.attr('length')){ files.forEach(file => { let batch = file.attr('batch'), state = file.attr('state'); if (batch === this.attr('currentBatch') && (state === 'pending' || state === 'uploading')) { done = false; } }); } else { done = false; } // If we're done, increment the `currentBatch` number. if (done) { this.attr('currentBatch', this.attr('currentBatch') + 1); } return done; } }, /** * `errored` is an array that contains all files with an `errorMessage` * attribute. */ errored: { value: [], get(){ let files = this.attr('files'), messages = []; files.each(file => { let message = file.attr('errorMessage'); if (message) { messages.push(message); } }); return messages; } }, /** * `fileTypes` is configurable using a comma-separated string. It gets * converted to a map where each fileType as a key and the value is `true` * for efficient comparison like `if(fileTypes.jpg)`. */ extensions: { set(value){ let types = {}, values = value.replace(' ', '').split(','); values.forEach(type => { types[type] = true; }); return types; } }, /** * `uploadingCount` is an integer that represents the number of files that * are currently `uploading`. */ uploadingCount: { get(){ let files = this.attr('files').attr(); let uploading = files.filter(function(file){ return file.state === 'uploading'; }); return uploading.length; } }, /** * The `progress` attribute is an integer that represents the overall * percentage of completion. */ progress: { get(){ let files = this.attr('files'), done = this.attr('done'), progressSize = 0, totalSize = 0; files.each(file => { if (file.attr('batch') === this.attr('currentBatch')) { totalSize += parseInt(file.attr('size')); progressSize += parseInt(file.attr('progressSize')); } }); let percentage = Math.round((progressSize / totalSize) * 100); if (done && !percentage) { percentage = 100; } return percentage || 0; } }, /** * The maximum number of simultaneous uploads. */ maxConcurrent: { value: 3, type: Number } }, /** * `currentBatch` is an integer that represents the progress bar's batch * number. Whenever the `done` attribute is true, it increments this number * so that the next set of files added to the list get a progress bar that * starts at '0'. */ currentBatch: 0, /** * If `autoUpload` is true, it will start uploading as soon as a file is pushed * into the `files` List. */ autoUpload: true, /** * The maximum file size in bytes. */ maxFileSize: null, /** * Send a single file to the server. If `keepGoing` is passed as `true`, it * will call `uploadAll()` once there is a response from the server. */ upload(file, keepGoing){ var self = this; file.attr('state', 'uploading'); this.resetProgress(file); function checkKeepGoing(){ if(keepGoing) { self.uploadAll(); } } this.attr('model').create(file) .then(checkKeepGoing, checkKeepGoing); }, uploadAll(){ // Looks for 'pending' files only. var files = this.attr('files'), canUpload = (this.attr('maxConcurrent') - this.attr('uploadingCount')) > 0; // Prevent unnecessary looping. if (canUpload) { files.each(file => { let state = file.attr('state'); canUpload = (this.attr('maxConcurrent') - this.attr('uploadingCount')) > 0; if (state === 'pending' && canUpload){ this.upload(file, true); } }); } }, /** * Cancels the xhr request, if applicable, then sets the `state` to `"stopped"`. */ stop(file){ let xhr = file.attr('xhr'); if (xhr) { xhr.abort(); } file.attr('state', 'stopped'); this.resetProgress(file); }, /** * Calls `stop()` on all files. */ stopAll(){ let files = this.attr('files'); files.each(file => { this.stop(file); }); }, /** * Stops the file upload, if applicable, then splices the file from the list. */ remove(file){ let files = this.attr('files'), index = files.indexOf(file); this.stop(file); files.splice(index, 1); }, /** * Calls `remove()` on all files. */ removeAll(){ let files = this.attr('files'); this.stopAll(); files.replace([]); }, /** * Sets the progress-related attributes of a file to `0`; */ resetProgress(file){ file.attr('progressPercent', 0); file.attr('progressSize', 0); } }); export default VM;
icanjs/file-uploadlet
src/view-model.js
JavaScript
mit
5,697
$("td").filter(".rating").each(function (index) { var rating = parseInt($(this).text()); if (rating < 40) { $(this).addClass("danger"); } else if (rating < 70) { $(this).addClass("warning"); } else { $(this).addClass("success"); } });
rskwan/ncindex
ncindex/static/js/colors.js
JavaScript
mit
279
/* * grunt-string-baker * https://github.com/xdranik/grunt-string-baker * * Copyright (c) 2014 Andranik Andy Tonoyan * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/**/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'] }, // Configuration to be run (and then tested). string_baker: { default_options: { options: { }, src: 'templates/test.html', dest: 'templates/dest/', dataFiles: 'data/test.*', replacements: [ { pattern: '[NON_DEFAULT_KEY]', keyString: 'NON_DEFAULT_KEY' }, { pattern: '{{KEY}}' } ] } }, // Unit tests. nodeunit: { tests: ['test/*_test.js'] } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'string_baker', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
xDranik/grunt-string-baker
Gruntfile.js
JavaScript
mit
1,629
import Icon from '../components/Icon.vue' Icon.register({ ring: { width: 512, height: 512, paths: [ { d: 'M256 64c145.9 0 256 61.9 256 144v98.1c0 78.4-114.6 141.9-256 141.9s-256-63.5-256-141.9v-98.1c0-82.1 110.1-144 256-144zM256 128c-106 0-192 35.8-192 80 0 9.3 4 18.1 10.9 26.4 44.9-26.2 108.9-42.4 181.1-42.4s136.2 16.2 181.1 42.4c6.9-8.3 10.9-17.1 10.9-26.4 0-44.2-86-80-192-80zM120.4 264.6c34.7 14.4 82.6 23.4 135.6 23.4s100.8-8.9 135.6-23.4c-34.6-14.7-81.2-24.6-135.6-24.6s-101 9.9-135.6 24.6z' } ] } })
Justineo/vue-awesome
src/icons/ring.js
JavaScript
mit
550
var classhryky_1_1http_1_1method_1_1_entity = [ [ "this_type", "classhryky_1_1http_1_1method_1_1_entity.html#a3953ff7f851afb4c64fde9ab521deb88", null ], [ "Entity", "classhryky_1_1http_1_1method_1_1_entity.html#afc0427c309ca95105eeda86095bd7773", null ], [ "Entity", "classhryky_1_1http_1_1method_1_1_entity.html#a0a824f44ca5488fbbbf1066d5ce72357", null ], [ "Entity", "classhryky_1_1http_1_1method_1_1_entity.html#afab3ba3f2653e7a8d774896960d612db", null ], [ "Entity", "classhryky_1_1http_1_1method_1_1_entity.html#a9fd2ac1efeb2a1ab0b6b76d9b36e404c", null ], [ "~Entity", "classhryky_1_1http_1_1method_1_1_entity.html#a972aa8a766ee5e20f742f8694d55f17f", null ], [ "clear", "classhryky_1_1http_1_1method_1_1_entity.html#a6ef7841c5cd1abeb83b3add076fe1d73", null ], [ "reduce", "classhryky_1_1http_1_1method_1_1_entity.html#af566f6444977307aae49759f466ca0ea", null ], [ "swap", "classhryky_1_1http_1_1method_1_1_entity.html#a5e7fb9634f8b20eca0b6d14b04ed01e4", null ], [ "hryky_assign_op", "classhryky_1_1http_1_1method_1_1_entity.html#afec9520084c04892ec3d09ca4a900042", null ] ];
hiroyuki-seki/hryky-codebase
doc/html/classhryky_1_1http_1_1method_1_1_entity.js
JavaScript
mit
1,119
'use strict'; require('dotenv').config(); const Pg = require('pg'); const MEASUREMENTS_TABLE = process.env.MEASUREMENTS_TABLE; const STATION_IDS_TABLE = process.env.STATION_IDS_TABLE; const pg = new Pg.Client({ connectionString: process.env.DATABASE_URL, ssl: true }); pg.connect(); const measurementsTable = pg.query(`CREATE TABLE ${MEASUREMENTS_TABLE} (timestamp TIMESTAMP NOT NULL PRIMARY KEY, station_id VARCHAR(12) NOT NULL, is_occupied BOOL NOT NULL, distance INT NOT NULL)`) .then(result => console.log(`${MEASUREMENTS_TABLE} created`)) .catch(error => console.log(error)); const stationIdsTable = pg.query(`CREATE TABLE ${STATION_IDS_TABLE}(station_id VARCHAR(12) NOT NULL)`) .then(result => console.log(`${STATION_IDS_TABLE} created`)) .catch(error => console.log(error)); Promise.all([measurementsTable, stationIdsTable]).then(values => pg.end());
andrzejdus/orange-sensors-api
server/createTables.js
JavaScript
mit
889
import express from 'express'; import db from './db.js'; import path from 'path'; // import favicon from 'serve-favicon'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import session from 'express-session'; // const MongoStore = require('connect-mongo')(session); import settings from './Setting'; import router from './routes'; const app = express(); app.use(bodyParser.json());//for 'application/json' app.use(bodyParser.urlencoded({ extended: true }));//for 'application/x-www-form-urlencoded' app.use(cookieParser()); //session app.use(session({ secret: settings.cookieSecret, resave: false, saveUninitialized: true, cookie: { maxAge: 60 * 1000 }, // store: new MongoStore({ // url: 'mongodb://'+ settings.host +'/'+ settings.db // }) })); //static sources app.use('/static',express.static(path.join(__dirname, 'static'))); app.all('/*', (req,res,next) => { res.header("Access-Control-Allow-Origin", req.headers.origin || '*'); res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS'); res.header("Access-Control-Allow-Credentials", true); res.header('Access-Control-Allow-Headers', 'Accept, Content-Type'); res.header('X-Powered-By', 'Ocean'); // if (req.method === 'OPTIONS') { // res.send(200); // } else { // next(); // } next(); }); router(app); module.exports = app;//่ฟ™้‡Œๆณจๆ„ๅฟ…้กป็”จCommonJS่พ“ๅ‡บ
Maxpsc/Ocean
server/app.js
JavaScript
mit
1,405
var fs = require('fs'); var path = require('path'); var ExternalsPlugin = require('webpack-externals-plugin'); module.exports = { entry: [ 'babel-polyfill', path.resolve(__dirname, 'server/server.js'), ], output: { path: __dirname + '/dist/', filename: 'server.bundle.js', }, target: 'node', node: { __filename: true, __dirname: true, }, resolve: { extensions: ['', '.js', '.jsx'], modules: [ 'client', 'node_modules', ], }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: [ 'react', 'es2015', 'stage-0', ], plugins: [ [ 'babel-plugin-webpack-loaders', { 'config': './webpack.config.babel.js', "verbose": false } ] ] }, }, { test: /\.json$/, loader: 'json-loader', }, ], }, plugins: [ new ExternalsPlugin({ type: 'commonjs', include: path.join(__dirname, './node_modules/'), }), ], };
Blaumeiser/dronegames
webpack.config.server.js
JavaScript
mit
1,188
'use strict'; const registration = require('../../../lib/plugins/helpers/body_splitter'); describe('splitBody()', () => { let splitBody; beforeAll(() => { registration((type, name, fn) => { splitBody = fn; }); }); it('should return an object with all contents if no sections were found', () => { const body = 'The body of the file'; const result = splitBody(body, '---(.*)---'); expect(result).toEqual({ content: body }); }); it('should be able to handle a file with only one section', () => { const section1 = 'This is the first section'; const body = ` ---section1--- ${section1} `; const result = splitBody(body, '---(.*)---'); expect(result.section1.indexOf(section1)).not.toBe(-1); }); it('should be able to handle files with multiple sections', () => { const section1 = 'This is the first section'; const section2 = 'This is the second section'; const body = ` ---section1--- ${section1} ---section2--- ${section2} `; const result = splitBody(body, '---(.*)---'); expect(result.section1.indexOf(section1)).not.toBe(-1); expect(result.section1.indexOf(section2)).toBe(-1); expect(result.section2.indexOf(section1)).toBe(-1); expect(result.section2.indexOf(section2)).not.toBe(-1); }); it('should be able to handle a custom splitter', () => { const section1 = 'This is the first section'; const section2 = 'This is the second section'; const body = ` ===section1=== ${section1} ===section2=== ${section2} `; const result = splitBody(body, '===(.*)==='); expect(result.section1.indexOf(section1)).not.toBe(-1); expect(result.section1.indexOf(section2)).toBe(-1); expect(result.section2.indexOf(section1)).toBe(-1); expect(result.section2.indexOf(section2)).not.toBe(-1); }); it('should work with arbitrary long splitters', () => { const section1 = 'This is the first section'; const section2 = 'This is the second section'; const body = ` <!--section1---> ${section1} <!--section2---> ${section2} `; const result = splitBody(body, '<!--(.*)--->'); expect(result.section1.indexOf(section1)).not.toBe(-1); expect(result.section1.indexOf(section2)).toBe(-1); expect(result.section2.indexOf(section1)).toBe(-1); expect(result.section2.indexOf(section2)).not.toBe(-1); }); it('should work when the content contains the word "undefined"', () => { const section1 = 'This section contains undefined'; const section2 = 'This section does not contain undefined'; const body = ` ---section1--- ${section1} ---section2--- ${section2} `; const result = splitBody(body, '---(.*)---'); expect(result.section1.indexOf(section1)).not.toBe(-1); expect(result.section1.indexOf(section2)).toBe(-1); expect(result.section2.indexOf(section1)).toBe(-1); expect(result.section2.indexOf(section2)).not.toBe(-1); }); });
nponiros/FlexiSiteGen
spec/plugins/helpers/body_splitter.spec.js
JavaScript
mit
3,082
var zeroScale = 0.00001; AFRAME.registerComponent('fixedsize', { schema: { default: 1 }, init: function () { this.scale = 1; this.factor = 1; }, update: function () { var data = this.data; this.scale = data === 0 ? zeroScale : data; }, tick: function (t) { var object3D = this.el.object3D; var camera = this.el.sceneEl.camera; if (!camera) {return;} var cameraPos = camera.getWorldPosition(); var thisPos = object3D.getWorldPosition(); var distance = thisPos.distanceTo(cameraPos); // base the factor on the viewport height. // I think we need to use the renderviewport size, since we really care about what is rendered. // This means that when we're rendering on an HMD, and are using this to scale HTML content, the content might be // the wrong size var height = this.el.sceneEl.argonApp.view.renderHeight; this.factor = 2 * (this.scale / height); // let's get the fov scale factor from the camera fovScale = Math.tan(THREE.Math.degToRad(camera.fov) / 2) * 2; // if distance < near clipping plane, just use scale at the near plane. Don't go any bigger var factor = fovScale * (distance < camera.near ? camera.near * this.factor : distance * this.factor); object3D.scale.set(factor, factor, factor); } }); AFRAME.registerComponent('trackvisibility', { schema: { default: true }, init: function () { var self = this; this.el.addEventListener('referenceframe-statuschanged', function(evt) { self.updateVisibility(evt); }); }, updateVisibility: function (evt) { console.log("visibility changed: " + evt.detail.found) if (this.data && evt.detail.target === this.el) { this.el.object3D.visible = evt.detail.found; } }, update: function () { } }); AFRAME.registerComponent('physical', { schema: { default: true }, init: function () { }, // "mesh" could change and we won't be notified. Bummer update: function (oldData) { var mesh = this.el.getOrCreateObject3D("mesh"); if (mesh) { mesh.material.colorWrite = !this.data; // only update the depth mesh.renderOrder = this.data ? -2 : 0; // before everything else } } }); AFRAME.registerComponent('show-in', { schema: { ar: {default: false}, vr: {default: false}, "arhmd": { default: false}, "vrhmd": { default: false} }, init: function () { var self = this; this.el.sceneEl.addEventListener('enter-vr', function (evt) { self.updateVisibility(evt); }); this.el.sceneEl.addEventListener('exit-vr', function (evt) { self.updateVisibility(evt); }); this.el.sceneEl.addEventListener('enter-ar', function (evt) { self.updateVisibility(evt); }); this.el.sceneEl.addEventListener('exit-ar', function (evt) { self.updateVisibility(evt); }); self.updateVisibility(); }, updateVisibility: function () { var sceneEl = this.el.sceneEl; var armode = sceneEl.is('ar-mode'); var hmdmode = sceneEl.is('vr-mode'); var data = this.data; var visible = false; if (data.arhmd && armode && hmdmode) { visible = true;} if (data.vrhmd && !armode && hmdmode) { visible = true;} if (data.ar && armode) { visible = true;} if (data.vr && !armode) { visible = true;} this.el.object3D.visible = visible; }, update: function () { } }); AFRAME.registerComponent('desiredreality', { schema: { src: {type: 'src'}, name: {default: "Custom Reality"} }, init: function () { var el = this.el; if (!el.isArgon) { console.warn('vuforiadataset should be attached to an <ar-scene>.'); } }, remove: function () { var el = this.el; if (el.isArgon) { el.argonApp.reality.setDesired(undefined); } }, update: function () { var el = this.el; var data = this.data; if (el.isArgon) { el.argonApp.reality.setDesired({ title: data.name, uri: Argon.resolveURL(data.src) }); } } }); AFRAME.registerComponent('enablehighaccuracy', { schema: { default: true }, init: function () { var el = this.el; if (!el.isArgon) { console.warn('enablehighaccuracy should be attached to an <ar-scene>.'); } }, update: function () { var el = this.el; var data = this.data; // do nothing if it's not an argon scene entity if (el.isArgon) { // remember our current desired accuracy el.enableHighAccuracy = data; // re-request geolocation, so it uses the new accuracy el.subscribeGeolocation(); } } }); /* * create some lights based on the sun and moon */ AFRAME.registerComponent('sunmoon', { schema: { default: true }, init: function () { var el = this.el; if (!el.isArgon) { console.warn('sunmoon should be attached to an <ar-scene>.'); } // requires that you've included if (THREE.SunMoonLights) { // this needs geoposed content, so subscribe to geolocation updates if (el.isArgon) { this.el.subscribeGeolocation(); } this.sunMoonLights = new THREE.SunMoonLights(); window.CESIUM_BASE_URL='https://samples-develop.argonjs.io/resources/cesium/'; } }, remove: function () { var el = this.el; if (el.isArgon && this.sunMoonLights) { this.sunMoonLights = null; this.el.removeObject3D('sunmoon'); } }, update: function () { var el = this.el; var data = this.data; if (el.isArgon) { if (data) { this.el.setObject3D('sunmoon', this.sunMoonLights.lights); } else { this.el.removeObject3D('sunmoon'); } } }, tick: function () { if (this.data && this.sunMoonLights) { var context = this.el.argonApp.context; this.sunMoonLights.update(context.time,context.defaultReferenceFrame); } } }); /** * based on https://github.com/Utopiah/aframe-triggerbox-component * * Usage <a-entity radius=10 trigger="event: mytrigger" /> will make a 10 unit * trigger region around the entity that emits the event mytrigger_entered once * the camera moves in and event mytrigger_exited once the camera leaves it. * * It can also be used on other entity e.g. an enemy or a bonus. * * inspired by https://github.com/atomicguy/aframe-fence-component/ * */ AFRAME.registerComponent('trigger', { multiple: true, schema: { radius: {default: 1}, event: {default: 'trigger'}, initial: {default: false} }, init: function() { // we don't know yet where we are this.teststateset = false; this.laststateinthetrigger = false; this.name = ""; }, update: function (oldData) { this.radiusSquared = this.data.radius * this.data.radius; this.name = this.id ? this.id : ""; }, tick: function() { // gathering all the data var data = this.data; var thisradiusSquared = this.radiusSquared; var triggereventname = data.event; var laststateset = this.laststateset; var laststateinthetrigger = this.laststateinthetrigger; var camera = this.el.sceneEl.camera; // camera might not be set immediately if (!camera) { return; } var cameraPosition = camera.position; //var position = this.el.getComputedAttribute('position'); // we don't want the attribute value, we want the "real" value var distanceSquared = this.el.object3D.position.distanceToSquared(cameraPosition); if (distanceSquared <= thisradiusSquared) { // we are in if ((!laststateset && data.initial) || (laststateset && !laststateinthetrigger)){ this.el.emit(triggereventname, {name: this.name, inside: true, initial: !laststateset, distanceSquared: distanceSquared}); } this.laststateinthetrigger = true; } else { // we are out if ((!laststateset && data.initial) || (laststateset && laststateinthetrigger)){ // we were not before this.el.emit(triggereventname, {name: this.name, inside: false, initial: !laststateset, distanceSquared: distanceSquared}); } this.laststateinthetrigger = false; } this.laststateset = true; }, });
argonjs/argon-aframe
src/ar-components.js
JavaScript
mit
8,574
import {Provider} from 'react-redux'; import store from './src/redux/store'; import AppViewContainer from './src/modules/AppViewContainer'; import React, {Component} from 'react'; import {AppRegistry} from 'react-native'; class barcodebar extends Component { render() { return ( <Provider store={store}> <AppViewContainer /> </Provider> ); } } AppRegistry.registerComponent('barcodebar', () => barcodebar);
salokas/barcodebar
index.ios.js
JavaScript
mit
442
/*! * jQuery JavaScript Library v1.10.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03T13:48Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.2", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.10.2 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName("tbody").length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName("link").length; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior. div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( jQuery.support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, data = null, i = 0, elem = this[0]; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } })( window ); (function($, undefined) { /** * Unobtrusive scripting adapter for jQuery * https://github.com/rails/jquery-ujs * * Requires jQuery 1.7.0 or later. * * Released under the MIT license * */ // Cut down on the number of issues from people inadvertently including jquery_ujs twice // by detecting and raising an error when it happens. if ( $.rails !== undefined ) { $.error('jquery-ujs has already been loaded!'); } // Shorthand to make it a little easier to call public rails functions from within rails.js var rails; var $document = $(document); $.rails = rails = { // Link elements bound by jquery-ujs linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote], a[data-disable-with]', // Button elements boud jquery-ujs buttonClickSelector: 'button[data-remote]', // Select elements bound by jquery-ujs inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]', // Form elements bound by jquery-ujs formSubmitSelector: 'form', // Form input elements bound by jquery-ujs formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type])', // Form input elements disabled during form submission disableSelector: 'input[data-disable-with], button[data-disable-with], textarea[data-disable-with]', // Form input elements re-enabled after form submission enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled', // Form required input elements requiredInputSelector: 'input[name][required]:not([disabled]),textarea[name][required]:not([disabled])', // Form file input elements fileInputSelector: 'input[type=file]', // Link onClick disable selector with possible reenable after remote submission linkDisableSelector: 'a[data-disable-with]', // Make sure that every Ajax request sends the CSRF token CSRFProtection: function(xhr) { var token = $('meta[name="csrf-token"]').attr('content'); if (token) xhr.setRequestHeader('X-CSRF-Token', token); }, // Triggers an event on an element and returns false if the event result is false fire: function(obj, name, data) { var event = $.Event(name); obj.trigger(event, data); return event.result !== false; }, // Default confirm dialog, may be overridden with custom confirm dialog in $.rails.confirm confirm: function(message) { return confirm(message); }, // Default ajax function, may be overridden with custom function in $.rails.ajax ajax: function(options) { return $.ajax(options); }, // Default way to get an element's href. May be overridden at $.rails.href. href: function(element) { return element.attr('href'); }, // Submits "remote" forms and links with ajax handleRemote: function(element) { var method, url, data, elCrossDomain, crossDomain, withCredentials, dataType, options; if (rails.fire(element, 'ajax:before')) { elCrossDomain = element.data('cross-domain'); crossDomain = elCrossDomain === undefined ? null : elCrossDomain; withCredentials = element.data('with-credentials') || null; dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType); if (element.is('form')) { method = element.attr('method'); url = element.attr('action'); data = element.serializeArray(); // memoized value from clicked submit button var button = element.data('ujs:submit-button'); if (button) { data.push(button); element.data('ujs:submit-button', null); } } else if (element.is(rails.inputChangeSelector)) { method = element.data('method'); url = element.data('url'); data = element.serialize(); if (element.data('params')) data = data + "&" + element.data('params'); } else if (element.is(rails.buttonClickSelector)) { method = element.data('method') || 'get'; url = element.data('url'); data = element.serialize(); if (element.data('params')) data = data + "&" + element.data('params'); } else { method = element.data('method'); url = rails.href(element); data = element.data('params') || null; } options = { type: method || 'GET', data: data, dataType: dataType, // stopping the "ajax:beforeSend" event will cancel the ajax request beforeSend: function(xhr, settings) { if (settings.dataType === undefined) { xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script); } return rails.fire(element, 'ajax:beforeSend', [xhr, settings]); }, success: function(data, status, xhr) { element.trigger('ajax:success', [data, status, xhr]); }, complete: function(xhr, status) { element.trigger('ajax:complete', [xhr, status]); }, error: function(xhr, status, error) { element.trigger('ajax:error', [xhr, status, error]); }, crossDomain: crossDomain }; // There is no withCredentials for IE6-8 when // "Enable native XMLHTTP support" is disabled if (withCredentials) { options.xhrFields = { withCredentials: withCredentials }; } // Only pass url to `ajax` options if not blank if (url) { options.url = url; } var jqxhr = rails.ajax(options); element.trigger('ajax:send', jqxhr); return jqxhr; } else { return false; } }, // Handles "data-method" on links such as: // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a> handleMethod: function(link) { var href = rails.href(link), method = link.data('method'), target = link.attr('target'), csrf_token = $('meta[name=csrf-token]').attr('content'), csrf_param = $('meta[name=csrf-param]').attr('content'), form = $('<form method="post" action="' + href + '"></form>'), metadata_input = '<input name="_method" value="' + method + '" type="hidden" />'; if (csrf_param !== undefined && csrf_token !== undefined) { metadata_input += '<input name="' + csrf_param + '" value="' + csrf_token + '" type="hidden" />'; } if (target) { form.attr('target', target); } form.hide().append(metadata_input).appendTo('body'); form.submit(); }, /* Disables form elements: - Caches element value in 'ujs:enable-with' data store - Replaces element text with value of 'data-disable-with' attribute - Sets disabled property to true */ disableFormElements: function(form) { form.find(rails.disableSelector).each(function() { var element = $(this), method = element.is('button') ? 'html' : 'val'; element.data('ujs:enable-with', element[method]()); element[method](element.data('disable-with')); element.prop('disabled', true); }); }, /* Re-enables disabled form elements: - Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`) - Sets disabled property to false */ enableFormElements: function(form) { form.find(rails.enableSelector).each(function() { var element = $(this), method = element.is('button') ? 'html' : 'val'; if (element.data('ujs:enable-with')) element[method](element.data('ujs:enable-with')); element.prop('disabled', false); }); }, /* For 'data-confirm' attribute: - Fires `confirm` event - Shows the confirmation dialog - Fires the `confirm:complete` event Returns `true` if no function stops the chain and user chose yes; `false` otherwise. Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog. Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog. */ allowAction: function(element) { var message = element.data('confirm'), answer = false, callback; if (!message) { return true; } if (rails.fire(element, 'confirm')) { answer = rails.confirm(message); callback = rails.fire(element, 'confirm:complete', [answer]); } return answer && callback; }, // Helper function which checks for blank inputs in a form that match the specified CSS selector blankInputs: function(form, specifiedSelector, nonBlank) { var inputs = $(), input, valueToCheck, selector = specifiedSelector || 'input,textarea', allInputs = form.find(selector); allInputs.each(function() { input = $(this); valueToCheck = input.is('input[type=checkbox],input[type=radio]') ? input.is(':checked') : input.val(); // If nonBlank and valueToCheck are both truthy, or nonBlank and valueToCheck are both falsey if (!valueToCheck === !nonBlank) { // Don't count unchecked required radio if other radio with same name is checked if (input.is('input[type=radio]') && allInputs.filter('input[type=radio]:checked[name="' + input.attr('name') + '"]').length) { return true; // Skip to next input } inputs = inputs.add(input); } }); return inputs.length ? inputs : false; }, // Helper function which checks for non-blank inputs in a form that match the specified CSS selector nonBlankInputs: function(form, specifiedSelector) { return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank }, // Helper function, needed to provide consistent behavior in IE stopEverything: function(e) { $(e.target).trigger('ujs:everythingStopped'); e.stopImmediatePropagation(); return false; }, // replace element's html with the 'data-disable-with' after storing original html // and prevent clicking on it disableElement: function(element) { element.data('ujs:enable-with', element.html()); // store enabled state element.html(element.data('disable-with')); // set to disabled state element.bind('click.railsDisable', function(e) { // prevent further clicking return rails.stopEverything(e); }); }, // restore element to its original state which was disabled by 'disableElement' above enableElement: function(element) { if (element.data('ujs:enable-with') !== undefined) { element.html(element.data('ujs:enable-with')); // set to old enabled state element.removeData('ujs:enable-with'); // clean up cache } element.unbind('click.railsDisable'); // enable element } }; if (rails.fire($document, 'rails:attachBindings')) { $.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { rails.CSRFProtection(xhr); }}); $document.delegate(rails.linkDisableSelector, 'ajax:complete', function() { rails.enableElement($(this)); }); $document.delegate(rails.linkClickSelector, 'click.rails', function(e) { var link = $(this), method = link.data('method'), data = link.data('params'); if (!rails.allowAction(link)) return rails.stopEverything(e); if (link.is(rails.linkDisableSelector)) rails.disableElement(link); if (link.data('remote') !== undefined) { if ( (e.metaKey || e.ctrlKey) && (!method || method === 'GET') && !data ) { return true; } var handleRemote = rails.handleRemote(link); // response from rails.handleRemote() will either be false or a deferred object promise. if (handleRemote === false) { rails.enableElement(link); } else { handleRemote.error( function() { rails.enableElement(link); } ); } return false; } else if (link.data('method')) { rails.handleMethod(link); return false; } }); $document.delegate(rails.buttonClickSelector, 'click.rails', function(e) { var button = $(this); if (!rails.allowAction(button)) return rails.stopEverything(e); rails.handleRemote(button); return false; }); $document.delegate(rails.inputChangeSelector, 'change.rails', function(e) { var link = $(this); if (!rails.allowAction(link)) return rails.stopEverything(e); rails.handleRemote(link); return false; }); $document.delegate(rails.formSubmitSelector, 'submit.rails', function(e) { var form = $(this), remote = form.data('remote') !== undefined, blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector), nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector); if (!rails.allowAction(form)) return rails.stopEverything(e); // skip other logic when required values are missing or file upload is present if (blankRequiredInputs && form.attr("novalidate") == undefined && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) { return rails.stopEverything(e); } if (remote) { if (nonBlankFileInputs) { // slight timeout so that the submit button gets properly serialized // (make it easy for event handler to serialize form without disabled values) setTimeout(function(){ rails.disableFormElements(form); }, 13); var aborted = rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]); // re-enable form elements if event bindings return false (canceling normal form submission) if (!aborted) { setTimeout(function(){ rails.enableFormElements(form); }, 13); } return aborted; } rails.handleRemote(form); return false; } else { // slight timeout so that the submit button gets properly serialized setTimeout(function(){ rails.disableFormElements(form); }, 13); } }); $document.delegate(rails.formInputClickSelector, 'click.rails', function(event) { var button = $(this); if (!rails.allowAction(button)) return rails.stopEverything(event); // register the pressed submit button var name = button.attr('name'), data = name ? {name:name, value:button.val()} : null; button.closest('form').data('ujs:submit-button', data); }); $document.delegate(rails.formSubmitSelector, 'ajax:beforeSend.rails', function(event) { if (this == event.target) rails.disableFormElements($(this)); }); $document.delegate(rails.formSubmitSelector, 'ajax:complete.rails', function(event) { if (this == event.target) rails.enableFormElements($(this)); }); $(function(){ // making sure that all forms have actual up-to-date token(cached forms contain old one) var csrf_token = $('meta[name=csrf-token]').attr('content'); var csrf_param = $('meta[name=csrf-param]').attr('content'); $('form input[name="' + csrf_param + '"]').val(csrf_token); }); } })( jQuery ); (function() { var CSRFToken, anchoredLink, assetsChanged, browserCompatibleDocumentParser, browserIsntBuggy, browserSupportsPushState, cacheCurrentPage, changePage, constrainPageCacheTo, createDocument, crossOriginLink, currentState, executeScriptTags, extractLink, extractTitleAndBody, extractTrackAssets, fetchHistory, fetchReplacement, handleClick, ignoreClick, initializeTurbolinks, initialized, installClickHandlerLast, intersection, invalidContent, loadedAssets, noTurbolink, nonHtmlLink, nonStandardClick, pageCache, recallScrollPosition, referer, reflectNewUrl, reflectRedirectedUrl, rememberCurrentState, rememberCurrentUrl, rememberInitialPage, removeHash, removeNoscriptTags, requestMethod, requestMethodIsSafe, resetScrollPosition, targetLink, triggerEvent, visit, xhr, _ref, __hasProp = {}.hasOwnProperty, __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; }; initialized = false; currentState = null; referer = document.location.href; loadedAssets = null; pageCache = {}; createDocument = null; requestMethod = ((_ref = document.cookie.match(/request_method=(\w+)/)) != null ? _ref[1].toUpperCase() : void 0) || ''; xhr = null; visit = function(url) { if (browserSupportsPushState && browserIsntBuggy) { cacheCurrentPage(); reflectNewUrl(url); return fetchReplacement(url); } else { return document.location.href = url; } }; fetchReplacement = function(url) { var safeUrl, _this = this; triggerEvent('page:fetch'); safeUrl = removeHash(url); if (xhr != null) { xhr.abort(); } xhr = new XMLHttpRequest; xhr.open('GET', safeUrl, true); xhr.setRequestHeader('Accept', 'text/html, application/xhtml+xml, application/xml'); xhr.setRequestHeader('X-XHR-Referer', referer); xhr.onload = function() { var doc; triggerEvent('page:receive'); if (invalidContent(xhr) || assetsChanged((doc = createDocument(xhr.responseText)))) { return document.location.reload(); } else { changePage.apply(null, extractTitleAndBody(doc)); reflectRedirectedUrl(xhr); if (document.location.hash) { document.location.href = document.location.href; } else { resetScrollPosition(); } return triggerEvent('page:load'); } }; xhr.onloadend = function() { return xhr = null; }; xhr.onabort = function() { return rememberCurrentUrl(); }; xhr.onerror = function() { return document.location.href = url; }; return xhr.send(); }; fetchHistory = function(state) { var page; cacheCurrentPage(); if (page = pageCache[state.position]) { if (xhr != null) { xhr.abort(); } changePage(page.title, page.body); recallScrollPosition(page); return triggerEvent('page:restore'); } else { return fetchReplacement(document.location.href); } }; cacheCurrentPage = function() { rememberInitialPage(); pageCache[currentState.position] = { url: document.location.href, body: document.body, title: document.title, positionY: window.pageYOffset, positionX: window.pageXOffset }; return constrainPageCacheTo(10); }; constrainPageCacheTo = function(limit) { var key, value; for (key in pageCache) { if (!__hasProp.call(pageCache, key)) continue; value = pageCache[key]; if (key <= currentState.position - limit) { pageCache[key] = null; } } }; changePage = function(title, body, csrfToken, runScripts) { document.title = title; document.documentElement.replaceChild(body, document.body); if (csrfToken != null) { CSRFToken.update(csrfToken); } removeNoscriptTags(); if (runScripts) { executeScriptTags(); } currentState = window.history.state; return triggerEvent('page:change'); }; executeScriptTags = function() { var attr, copy, nextSibling, parentNode, script, scripts, _i, _j, _len, _len1, _ref1, _ref2; scripts = Array.prototype.slice.call(document.body.getElementsByTagName('script')); for (_i = 0, _len = scripts.length; _i < _len; _i++) { script = scripts[_i]; if (!((_ref1 = script.type) === '' || _ref1 === 'text/javascript')) { continue; } copy = document.createElement('script'); _ref2 = script.attributes; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { attr = _ref2[_j]; copy.setAttribute(attr.name, attr.value); } copy.appendChild(document.createTextNode(script.innerHTML)); parentNode = script.parentNode, nextSibling = script.nextSibling; parentNode.removeChild(script); parentNode.insertBefore(copy, nextSibling); } }; removeNoscriptTags = function() { var noscript, noscriptTags, _i, _len; noscriptTags = Array.prototype.slice.call(document.body.getElementsByTagName('noscript')); for (_i = 0, _len = noscriptTags.length; _i < _len; _i++) { noscript = noscriptTags[_i]; noscript.parentNode.removeChild(noscript); } }; reflectNewUrl = function(url) { if (url !== document.location.href) { referer = document.location.href; return window.history.pushState({ turbolinks: true, position: currentState.position + 1 }, '', url); } }; reflectRedirectedUrl = function(xhr) { var location; if ((location = xhr.getResponseHeader('X-XHR-Current-Location')) && location !== document.location.pathname + document.location.search) { return window.history.replaceState(currentState, '', location + document.location.hash); } }; rememberCurrentUrl = function() { return window.history.replaceState({ turbolinks: true, position: Date.now() }, '', document.location.href); }; rememberCurrentState = function() { return currentState = window.history.state; }; rememberInitialPage = function() { if (!initialized) { rememberCurrentUrl(); rememberCurrentState(); createDocument = browserCompatibleDocumentParser(); return initialized = true; } }; recallScrollPosition = function(page) { return window.scrollTo(page.positionX, page.positionY); }; resetScrollPosition = function() { return window.scrollTo(0, 0); }; removeHash = function(url) { var link; link = url; if (url.href == null) { link = document.createElement('A'); link.href = url; } return link.href.replace(link.hash, ''); }; triggerEvent = function(name) { var event; event = document.createEvent('Events'); event.initEvent(name, true, true); return document.dispatchEvent(event); }; invalidContent = function(xhr) { return !xhr.getResponseHeader('Content-Type').match(/^(?:text\/html|application\/xhtml\+xml|application\/xml)(?:;|$)/); }; extractTrackAssets = function(doc) { var node, _i, _len, _ref1, _results; _ref1 = doc.head.childNodes; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { node = _ref1[_i]; if ((typeof node.getAttribute === "function" ? node.getAttribute('data-turbolinks-track') : void 0) != null) { _results.push(node.src || node.href); } } return _results; }; assetsChanged = function(doc) { var fetchedAssets; loadedAssets || (loadedAssets = extractTrackAssets(document)); fetchedAssets = extractTrackAssets(doc); return fetchedAssets.length !== loadedAssets.length || intersection(fetchedAssets, loadedAssets).length !== loadedAssets.length; }; intersection = function(a, b) { var value, _i, _len, _ref1, _results; if (a.length > b.length) { _ref1 = [b, a], a = _ref1[0], b = _ref1[1]; } _results = []; for (_i = 0, _len = a.length; _i < _len; _i++) { value = a[_i]; if (__indexOf.call(b, value) >= 0) { _results.push(value); } } return _results; }; extractTitleAndBody = function(doc) { var title; title = doc.querySelector('title'); return [title != null ? title.textContent : void 0, doc.body, CSRFToken.get(doc).token, 'runScripts']; }; CSRFToken = { get: function(doc) { var tag; if (doc == null) { doc = document; } return { node: tag = doc.querySelector('meta[name="csrf-token"]'), token: tag != null ? typeof tag.getAttribute === "function" ? tag.getAttribute('content') : void 0 : void 0 }; }, update: function(latest) { var current; current = this.get(); if ((current.token != null) && (latest != null) && current.token !== latest) { return current.node.setAttribute('content', latest); } } }; browserCompatibleDocumentParser = function() { var createDocumentUsingDOM, createDocumentUsingParser, createDocumentUsingWrite, e, testDoc, _ref1; createDocumentUsingParser = function(html) { return (new DOMParser).parseFromString(html, 'text/html'); }; createDocumentUsingDOM = function(html) { var doc; doc = document.implementation.createHTMLDocument(''); doc.documentElement.innerHTML = html; return doc; }; createDocumentUsingWrite = function(html) { var doc; doc = document.implementation.createHTMLDocument(''); doc.open('replace'); doc.write(html); doc.close(); return doc; }; try { if (window.DOMParser) { testDoc = createDocumentUsingParser('<html><body><p>test'); return createDocumentUsingParser; } } catch (_error) { e = _error; testDoc = createDocumentUsingDOM('<html><body><p>test'); return createDocumentUsingDOM; } finally { if ((testDoc != null ? (_ref1 = testDoc.body) != null ? _ref1.childNodes.length : void 0 : void 0) !== 1) { return createDocumentUsingWrite; } } }; installClickHandlerLast = function(event) { if (!event.defaultPrevented) { document.removeEventListener('click', handleClick, false); return document.addEventListener('click', handleClick, false); } }; handleClick = function(event) { var link; if (!event.defaultPrevented) { link = extractLink(event); if (link.nodeName === 'A' && !ignoreClick(event, link)) { visit(link.href); return event.preventDefault(); } } }; extractLink = function(event) { var link; link = event.target; while (!(!link.parentNode || link.nodeName === 'A')) { link = link.parentNode; } return link; }; crossOriginLink = function(link) { return location.protocol !== link.protocol || location.host !== link.host; }; anchoredLink = function(link) { return ((link.hash && removeHash(link)) === removeHash(location)) || (link.href === location.href + '#'); }; nonHtmlLink = function(link) { var url; url = removeHash(link); return url.match(/\.[a-z]+(\?.*)?$/g) && !url.match(/\.html?(\?.*)?$/g); }; noTurbolink = function(link) { var ignore; while (!(ignore || link === document)) { ignore = link.getAttribute('data-no-turbolink') != null; link = link.parentNode; } return ignore; }; targetLink = function(link) { return link.target.length !== 0; }; nonStandardClick = function(event) { return event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey; }; ignoreClick = function(event, link) { return crossOriginLink(link) || anchoredLink(link) || nonHtmlLink(link) || noTurbolink(link) || targetLink(link) || nonStandardClick(event); }; initializeTurbolinks = function() { document.addEventListener('click', installClickHandlerLast, true); return window.addEventListener('popstate', function(event) { var _ref1; if ((_ref1 = event.state) != null ? _ref1.turbolinks : void 0) { return fetchHistory(event.state); } }, false); }; browserSupportsPushState = window.history && window.history.pushState && window.history.replaceState && window.history.state !== void 0; browserIsntBuggy = !navigator.userAgent.match(/CriOS\//); requestMethodIsSafe = requestMethod === 'GET' || requestMethod === ''; if (browserSupportsPushState && browserIsntBuggy && requestMethodIsSafe) { initializeTurbolinks(); } this.Turbolinks = { visit: visit }; }).call(this); /*! * Bootstrap v3.0.3 (http://getbootstrap.com) * Copyright 2013 Twitter, Inc. * Licensed under http://www.apache.org/licenses/LICENSE-2.0 */ if (typeof jQuery === "undefined") { throw new Error("Bootstrap requires jQuery") } /* ======================================================================== * Bootstrap: transition.js v3.0.3 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2013 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd otransitionend' , 'transition' : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false, $el = this $(this).one($.support.transition.end, function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.0.3 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2013 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.hasClass('alert') ? $this : $this.parent() } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent.trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one($.support.transition.end, removeElement) .emulateTransitionEnd(150) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.0.3 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2013 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) } Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (!data.resetText) $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout(function () { state == 'loadingText' ? $el.addClass(d).attr(d, d) : $el.removeClass(d).removeAttr(d); }, 0) } Button.prototype.toggle = function () { var $parent = this.$element.closest('[data-toggle="buttons"]') var changed = true if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') === 'radio') { // see if clicking on current one if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } if (changed) this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') e.preventDefault() }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.0.3 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2013 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.DEFAULTS = { interval: 5000 , pause: 'hover' , wrap: true } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getActiveIndex = function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getActiveIndex() if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || $active[type]() var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var fallback = type == 'next' ? 'first' : 'last' var that = this if (!$next.length) { if (!this.options.wrap) return $next = this.$element.find('.item')[fallback]() } this.sliding = true isCycling && this.pause() var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid.bs.carousel', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid.bs.carousel') }, 0) }) .emulateTransitionEnd(600) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid.bs.carousel') } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() }) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) $carousel.carousel($carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.0.3 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2013 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(this.options.parent) if (this.options.toggle) this.toggle() } Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var actives = this.$parent && this.$parent.find('> .panel > .in') if (actives && actives.length) { var hasData = actives.data('bs.collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing') [dimension](0) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('in') [dimension]('auto') this.transitioning = 0 this.$element.trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) [dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element [dimension](this.$element[dimension]()) [0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse') .removeClass('in') this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .trigger('hidden.bs.collapse') .removeClass('collapsing') .addClass('collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } // COLLAPSE PLUGIN DEFINITION // ========================== var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 var $target = $(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } $target.collapse(option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.0.3 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2013 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle=dropdown]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } $parent.trigger(e = $.Event('show.bs.dropdown')) if (e.isDefaultPrevented()) return $parent .toggleClass('open') .trigger('shown.bs.dropdown') $this.focus() } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27)/.test(e.keyCode)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } var $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return var index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index=0 $items.eq(index).focus() } function clearMenus() { $(backdrop).remove() $(toggle).each(function (e) { var $parent = getParent($(this)) if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown')) if (e.isDefaultPrevented()) return $parent.removeClass('open').trigger('hidden.bs.dropdown') }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.0.3 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2013 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$element = $(element) this.$backdrop = this.isShown = null if (this.options.remote) this.$element.load(this.options.remote) } Modal.DEFAULTS = { backdrop: true , keyboard: true , show: true } Modal.prototype.toggle = function (_relatedTarget) { return this[!this.isShown ? 'show' : 'hide'](_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.$element.on('click.dismiss.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) // don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one($.support.transition.end, function () { that.$element.focus().trigger(e) }) .emulateTransitionEnd(300) : that.$element.focus().trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one($.support.transition.end, $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.focus() } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$element.on('click.dismiss.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (callback) { callback() } } // MODAL PLUGIN DEFINITION // ======================= var old = $.fn.modal $.fn.modal = function (option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 var option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option, this) .one('hide', function () { $this.is(':visible') && $this.focus() }) }) $(document) .on('show.bs.modal', '.modal', function () { $(document.body).addClass('modal-open') }) .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.0.3 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2013 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.DEFAULTS = { animation: true , placement: 'top' , selector: false , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' , trigger: 'hover focus' , title: '' , delay: 0 , html: false , container: false } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focus' var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay , hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.'+ this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) if (e.isDefaultPrevented()) return var $tip = this.tip() this.setContent() if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var $parent = this.$element.parent() var orgPlacement = placement var docScroll = document.documentElement.scrollTop || document.body.scrollTop var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth() var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight() var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' : placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' : placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' : placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) this.$element.trigger('shown.bs.' + this.type) } } Tooltip.prototype.applyPlacement = function(offset, placement) { var replace var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft $tip .offset(offset) .addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { replace = true offset.top = offset.top + height - actualHeight } if (/bottom|top/.test(placement)) { var delta = 0 if (offset.left < 0) { delta = offset.left * -2 offset.left = 0 $tip.offset(offset) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight } this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') } else { this.replaceArrow(actualHeight - height, actualHeight, 'top') } if (replace) $tip.offset(offset) } Tooltip.prototype.replaceArrow = function(delta, dimension, position) { this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function () { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete() this.$element.trigger('hidden.bs.' + this.type) return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function () { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth , height: el.offsetHeight }, this.$element.offset()) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.tip = function () { return this.$tip = this.$tip || $(this.options.template) } Tooltip.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow') } Tooltip.prototype.validate = function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { this.hide().$element.off('.' + this.type).removeData('bs.' + this.type) } // TOOLTIP PLUGIN DEFINITION // ========================= var old = $.fn.tooltip $.fn.tooltip = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.0.3 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2013 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.DEFAULTS = $.extend({} , $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right' , trigger: 'click' , content: '' , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.arrow') } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.0.3 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2013 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var href var process = $.proxy(this.process, this) this.$element = $(element).is('body') ? $(window) : $(element) this.$body = $('body') this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.offsets = $([]) this.targets = $([]) this.activeTarget = null this.refresh() this.process() } ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.refresh = function () { var offsetMethod = this.$element[0] == window ? 'offset' : 'position' this.offsets = $([]) this.targets = $([]) var self = this var $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#\w/.test(href) && $(href) return ($href && $href.length && [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight var maxScroll = scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate(i) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target $(this.selector) .parents('.active') .removeClass('active') var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } // SCROLLSPY PLUGIN DEFINITION // =========================== var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.0.3 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2013 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ($this.parent('li').hasClass('active')) return var previous = $ul.find('.active:last a')[0] var e = $.Event('show.bs.tab', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return var $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown.bs.tab' , relatedTarget: previous }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active .one($.support.transition.end, next) .emulateTransitionEnd(150) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.0.3 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2013 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$window = $(window) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = null this.checkPosition() } Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0 } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() var scrollTop = this.$window.scrollTop() var position = this.$element.offset() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false if (this.affixed === affix) return if (this.unpin) this.$element.css('top', '') this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : '')) if (affix == 'bottom') { this.$element.offset({ top: document.body.offsetHeight - offsetBottom - this.$element.height() }) } } // AFFIX PLUGIN DEFINITION // ======================= var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom) data.offset.bottom = data.offsetBottom if (data.offsetTop) data.offset.top = data.offsetTop $spy.affix(data) }) }) }(jQuery); // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // ;
quickbunch/quickbunch
public/assets/application-49a8a79b627dbe401698369b536b1195.js
JavaScript
mit
360,392
version https://git-lfs.github.com/spec/v1 oid sha256:046ea9e156f49bfaee0b37cc6ec524938a50e6ac9092fad231e1a2749f631c84 size 8178
yogeshsaroya/new-cdnjs
ajax/libs/mathjax/2.4.0/jax/output/SVG/fonts/TeX/SansSerif/Bold/Other.js
JavaScript
mit
129
version https://git-lfs.github.com/spec/v1 oid sha256:71a027e2010c03df92f7315c34d66ba0607fbb29f74297ba575f4c45501b2cdb size 1134
yogeshsaroya/new-cdnjs
ajax/libs/angular-i18n/1.2.10/angular-locale_es.min.js
JavaScript
mit
129
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("circle", { cx: "9.5", cy: "10", r: "1", opacity: ".3" }), h("path", { d: "M11.5 17.21c0-1.88 2.98-2.7 4.5-2.7.88 0 2.24.27 3.24.87.48-1.02.75-2.16.75-3.37 0-4.41-3.59-8-8-8s-8 3.59-8 8c0 1.23.29 2.39.78 3.43 1.34-.98 3.43-1.43 4.73-1.43.44 0 .97.05 1.53.16-.63.57-1.06 1.22-1.3 1.86-.08 0-.15-.01-.23-.01-1.38 0-2.98.57-3.66 1.11 1.37 1.65 3.39 2.73 5.66 2.86v-2.78zM16 9c1.11 0 2 .89 2 2 0 1.11-.89 2-2 2-1.11 0-2-.89-2-2-.01-1.11.89-2 2-2zm-6.5 4c-1.65 0-3-1.35-3-3s1.35-3 3-3 3 1.35 3 3-1.35 3-3 3z", opacity: ".3" }), h("path", { d: "M12.5 10c0-1.65-1.35-3-3-3s-3 1.35-3 3 1.35 3 3 3 3-1.35 3-3zm-3 1c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm6.5 2c1.11 0 2-.89 2-2 0-1.11-.89-2-2-2-1.11 0-2.01.89-2 2 0 1.11.89 2 2 2zM11.99 2.01c-5.52 0-10 4.48-10 10s4.48 10 10 10 10-4.48 10-10-4.48-10-10-10zM5.84 17.12c.68-.54 2.27-1.11 3.66-1.11.07 0 .15.01.23.01.24-.64.67-1.29 1.3-1.86-.56-.1-1.09-.16-1.53-.16-1.3 0-3.39.45-4.73 1.43-.5-1.04-.78-2.2-.78-3.43 0-4.41 3.59-8 8-8s8 3.59 8 8c0 1.2-.27 2.34-.75 3.37-1-.59-2.36-.87-3.24-.87-1.52 0-4.5.81-4.5 2.7v2.78c-2.27-.13-4.29-1.21-5.66-2.86z" })), 'SupervisedUserCircleTwoTone');
AlloyTeam/Nuclear
components/icon/esm/supervised-user-circle-two-tone.js
JavaScript
mit
1,267
yama.register({ name : 'nereo.mycomponent', draw : function(){ /*! root div text:title div:cont2 text:otherTitle div:loopCont !*/ }, init : function(cont){ this.title = "Hey"; }, title : "Hey", otherTitle : "Other title" }); yama.addLoadEvent(function(){ var cont = document.getElementById("test"); var myComponent = new yama.components.nereo.mycomponent(cont); // console.log(yama.components.nereo.mycomponent); // console.log(myComponent); myComponent.title = "Simple tester"; var testBtn = document.getElementById("testBtn"); testBtn.onclick = function(){ myComponent.otherTitle = "Bonjour"; } });
Celebio/Yama.js
test/simple/app.js
JavaScript
mit
761
var _ = require('./util'); var ID = 0; /** * Base Node object for all scenegraph objects * * id: non-visual, unique value for all nodes * visible: if false, this node (and descendents) will not render nor pick * x: the x position (translation) applied to this node * y: the y position (translation) applied to this node * rotation: rotation in radians applied to this node and any descendents * scaleX, scaleY: x and y scale applied to this node and any descendents * opacity: the global opacity [0,1] of this node */ var Node = function(attributes) { this.id = ID++; this.parent = null; this.visible = true; this.handlers = {}; _.extend(this, attributes); }; Node.prototype = { /** * Simple */ data: function(data) { if (arguments.length === 0) { return this._data; } else { this._data = data; } }, /** * Bulk sets a group of node properties, takes a map of property names * to values. Functionally equivalent to setting each property via * `node.propertyName = value` */ attr: function(attributes) { _.extend(this, attributes); return this; }, /** * Queues a set of node properties for an animated transition. Only * numeric properties can be animated. The length of the transition * is specified in the transition property, defaults to 1 second. An * optional callback can be provided which will be called on animation * completion. * * Calling `update()` on the scene root will trigger the start of all * queued animations and cause them to run (and render) to completion. */ tweenAttr: function(attributes, transition) { var self = this; var key, statics; transition = transition || {}; // Only support tweening numbers - statically set everything else for (key in attributes) { if (attributes.hasOwnProperty(key) && typeof attributes[key] != 'number') { statics = statics || {}; statics[key] = attributes[key]; delete attributes[key]; } } if (statics) { this.attr(statics); } if (this.tween) { // TODO Jump to end state of vars not being transitioned this.tween.stop(); } this.tween = new TWEEN.Tween(this) .to(attributes, transition.duration || 1000) .onComplete(function() { self.tween = null; if (transition.callback) { transition.callback(this, attributes); } }) .start(); }, /** * Adds an event handler to this node. For example: * ``` * node.on('click', function(event) { * // do something * }); * ``` * An event object will be passed to the handler when the event * is triggered. The event object will be a standard JavaScript * event and will contain a `targetNode` property containing the * node that was the source of the event. Events bubble up the * scenegraph until handled. Handlers returning a truthy value * signal that the event has been handled. */ on: function(type, handler) { var handlers = this.handlers[type]; if (!handlers) { handlers = this.handlers[type] = []; } handlers.push(handler); return this; }, /** * Removes an event handler of the given type. If no handler is * provided, all handlers of the type will be removed. */ off: function(type, handler) { if (!handler) { this.handlers[type] = []; } else { var handlers = this.handlers[type]; var idx = handlers.indexOf(handler); if (idx >= 0) { handlers.splice(idx, 1); } } return this; }, /** * Triggers an event and begins bubbling. Returns truthy if the * event was handled. */ trigger: function(type, event) { var handled = false; var handlers = this.handlers[type]; if (handlers) { handlers.forEach(function(handler) { handled = handler(event) || handled; }); } if (!handled && this.parent) { handled = this.parent.trigger(type, event); } return handled; }, /** * Removes this node from its parent */ remove: function() { if (this.parent) { this.parent.remove(this); } }, /** * Internal: renders the node given the context */ render: function(ctx) { if (!this.visible) { return; } var x = this.x || 0; var y = this.y || 0; var scaleX = this.scaleX == null ? 1 : this.scaleX; var scaleY = this.scaleY == null ? 1 : this.scaleY; var transformed = !!x || !!y || !!this.rotation || scaleX !== 1 || scaleY !== 1 || this.opacity != null; // TODO Investigate cost of always save/restore if (transformed) { ctx.save(); } if (x || y) { ctx.translate(x,y); } if (scaleX !== 1 || scaleY !== 1) { ctx.scale(scaleX, scaleY); } if (this.rotation) { ctx.rotate(this.rotation); } if (this.opacity != null) { ctx.globalAlpha = this.opacity; } this.draw(ctx); if (transformed) { ctx.restore(); } }, /** * Internal: tests for pick hit given context, global and local * coordinate system transformed pick coordinates. */ pick: function(ctx, x, y, lx, ly) { if (!this.visible) { return; } var result = null; var s, c, temp; var tx = this.x || 0; var ty = this.y || 0; var scaleX = this.scaleX == null ? 1 : this.scaleX; var scaleY = this.scaleY == null ? 1 : this.scaleY; var transformed = !!tx || !!ty || !!this.rotation || scaleX !== 1 || scaleY !== 1 || this.opacity != null; // TODO Investigate cost of always save/restore if (transformed) { ctx.save(); } if (tx || ty) { ctx.translate(tx,ty); // Reverse translation on picked point lx -= tx; ly -= ty; } if (scaleX !== 1 || scaleY !== 1) { ctx.scale(scaleX, scaleY); // Reverse scale lx /= scaleX; ly /= scaleY; } if (this.rotation) { ctx.rotate(this.rotation); // Reverse rotation s = Math.sin(-this.rotation); c = Math.cos(-this.rotation); temp = c*lx - s*ly; ly = s*lx + c*ly; lx = temp; } result = this.hitTest(ctx, x, y, lx, ly); if (transformed) { ctx.restore(); } return result; }, /** * Template method for derived objects to actually perform draw operations. * The calling `render` call handles general transforms and opacity. */ draw: function(ctx) { // template method }, /** * Template method for derived objects to test if they (or child) is hit by * the provided pick coordinate. If hit, return object that was hit. */ hitTest: function(ctx, x, y, lx, ly) { // template method } } module.exports = Node;
unchartedsoftware/pathjs
src/node.js
JavaScript
mit
6,775
/** * Facebook API integration. * * @method modules.Facebook * @namespace modules.Facebook * @class modules.Facebook * @extends modules.Facebook * * @return {self} **/ /* exported APP */ var APP = window.APP || {}; APP.namespace('modules.Facebook'); APP.modules.Facebook = (function() { 'use strict'; // Generic variables and module dependencies var app = window.APP; // Public PROPERTIES and METHODS var module = $.extend(app.modules.Facebook, { 'NAME': 'APP.modules.Facebook', 'notifications': { 'API_READY': 'facebook/API_READY', 'RESPONSE_STATUS': 'facebook/response/status', 'LOGGED_CHANGE': 'facebook/user/logged/changed', 'NOT_LOGGED': 'facebook/user/not/logged', 'USER_INFO': 'facebook/user/info', 'LOGIN_FINISHED': 'facebook/login/finished', 'PERMISSIONS_OK': 'facebook/permissions/ok', 'PERMISSIONS_FAIL': 'facebook/permissions/fail', 'PROFILE_IMAGE': 'facebook/profile/image', 'PROFILE_INFO': 'facebook/profile' } }); // Private VARIABLES var isInitialized = false; var FB; var objUserVO = {}; var MSG_FB_NOT_READY = 'Error::call init before calling this method.'; var MSG_INVALID_CBFUNC = 'Error::Required param @cbFunc is invalid.'; var MSG_INVALID_FB_APPID = 'Warning::Required param @fbAppId is missing.'; /** * Initialize Facebook API. * @method module.init * @public * * @param wFocus {Boolean} {Optional} Set to true if wants to auto-check Facebook authentication status * when a window.focus event occurs. Default is false. * @param cbFunc {Function} {Optional} Callback function to return Facebook response. * * @return {Void} **/ module.init = function(wFocus, cbFunc) { if (cbFunc && !$.isFunction(cbFunc)) { throw MSG_INVALID_CBFUNC; } // Prevent multiple initializations (optional) if (module.getIsInitialized()) { return; } facebookInit(app.getFbAppId(), wFocus, cbFunc); }; function facebookInit(fbAppId, wFocus, cbFunc) { if (!fbAppId) { console.warn(MSG_INVALID_FB_APPID); return; } if (isInitialized) { PubSub.publish(module.notifications.API_READY); if ($.isFunction(cbFunc)) { cbFunc(); } return; } if (!$('#fb-root')[0]) { $('body').prepend('<div id="fb-root"></div>'); } window.fbAsyncInit = function() { window.FB.init({ 'appId': fbAppId, 'xfbml': true, 'version': 'v2.3' }); FB = window.FB; if (wFocus) { $(window).focus(module.getLoginStatus); } isInitialized = true; PubSub.publish(module.notifications.API_READY); if ($.isFunction(cbFunc)) { cbFunc(); } }; (function(d, s, id) { var js; var fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = '//connect.facebook.net/pt_BR/sdk.js'; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); } function updateStatus(response) { var loggedUserVO = {}; if (response) { PubSub.publish(module.notifications.RESPONSE_STATUS, response.status); if (response.status === 'connected') { // the user is logged in and has authenticated your // app, and response.authResponse supplies // the user's ID, a valid access token, a signed // request, and the time the access token // and signed request each expire if (response.authResponse) { loggedUserVO = { 'userID': response.authResponse.userID.toString(), 'accessToken': response.authResponse.accessToken.toString() }; } } loggedUserVO.status = response.status; } // Check for status change. // * 1. FB logged user has changed // * 2. FB logged user has logged out if (objUserVO.userID) { if (loggedUserVO.userID) { if (objUserVO.userID !== loggedUserVO.userID) { // FB USER IS LOGGED, BUT HAS CHANGED objUserVO = loggedUserVO; PubSub.publish(module.notifications.LOGGED_CHANGE, loggedUserVO); } } else { // FB USER IS NOT LOGGED objUserVO = loggedUserVO; PubSub.publish(module.notifications.NOT_LOGGED, loggedUserVO); } } objUserVO = loggedUserVO; PubSub.publish(module.notifications.USER_INFO, objUserVO); } /** * Check Facebook authentication status by API FB.getLoginStatus. * @method module.getLoginStatus * @public * * @param cbFunc {Function} {Optional} Callback function to return Facebook response. * * @return {Void} **/ module.getLoginStatus = function(cbFunc) { if (!getIsFbReady()) { throw MSG_FB_NOT_READY; } if (cbFunc && !$.isFunction(cbFunc)) { throw MSG_INVALID_CBFUNC; } window.FB.getLoginStatus(function(response) { updateStatus(response); if (cbFunc) { cbFunc(response); } }, { 'force': 'true' }); }; module.getObjUserVO = function() { return objUserVO; }; /** * Call Facebook API FB.login. * @method module.login * @public * * @param arrScopes {Array} {Optional} Array with needed Facebook autorization scopes. Default is []. * @param cbFunc {Function} {Optional} Callback function to return Facebook response. * * @return {Void} **/ module.login = function(arrScopes, cbFunc) { if (!getIsFbReady()) { throw MSG_FB_NOT_READY; } if (!arrScopes) { arrScopes = app.getFbScopes(); } if (cbFunc && !$.isFunction(cbFunc)) { throw MSG_INVALID_CBFUNC; } window.FB.login(function(objResponseJSON) { updateStatus(objResponseJSON); if (cbFunc) { cbFunc(objResponseJSON); } }, { 'scope': arrScopes.toString() }); }; /** * Gets Facebook logged user public information. * Ref: https://developers.facebook.com/docs/graph-api/reference/v2.2/user * @method module.getUserProfileInfo * @public * * @param cbFunc {Function} {Optional} Callback function to return Facebook response. * * @return {Void} **/ module.getUserProfileInfo = function(cbFunc) { if (!getIsFbReady()) { throw MSG_FB_NOT_READY; } if (cbFunc && !$.isFunction(cbFunc)) { throw MSG_INVALID_CBFUNC; } window.FB.api('/me', function(objResponseJSON) { if (cbFunc) { cbFunc(objResponseJSON); } PubSub.publish(module.notifications.PROFILE_INFO, objResponseJSON); } ); }; /** * Gets Facebook logged user profile picture. * Ref: https://developers.facebook.com/docs/graph-api/reference/v2.2/user/picture * @method module.getImageProfile * @public * * @param objImage {Object} {Optional} Custom Facebook parameters. * @param cbFunc {Function} {Optional} Callback function to return Facebook response. * * @return {Void} **/ module.getImageProfile = function(objImage, cbFunc) { if (!getIsFbReady()) { throw MSG_FB_NOT_READY; } if (!objImage) { objImage = {}; } if (cbFunc && !$.isFunction(cbFunc)) { throw MSG_INVALID_CBFUNC; } var configImage = $.extend({}, { 'redirect': false, 'type': 'large' }, objImage); window.FB.api('/me/picture', configImage, function(objResponseJSON) { if (cbFunc) { cbFunc(objResponseJSON); } PubSub.publish(module.notifications.PROFILE_IMAGE, objResponseJSON); } ); }; /** * Get module initialization status. * @method module.getIsInitialized * @public * * @return {Boolean} **/ module.getIsInitialized = function() { return isInitialized; }; function getIsFbReady() { return (FB && window.FB === FB); } return module; }());
fpinatti/cow
src/main/webapp/js/common/SOCIAL-Facebook.js
JavaScript
mit
8,014
var classFilter = [ [ "Filter", "classFilter.html#add9c079e90b08a0075e5430dc02cb397", null ], [ "getFloatCoef", "classFilter.html#a47160b2aedfd49786b856e80dbdbad28", null ], [ "getIntCoef", "classFilter.html#a0f93a26b728565e83493c168d1c39f66", null ], [ "LoadFromCCX", "classFilter.html#a88d7c81e2db5723db2cdaa716164d709", null ] ];
DJGCrusader/ParallelScissorManipulator
lib/CML/html/classFilter.js
JavaScript
mit
348
//Casperjs test for SpektralVideo.js var environment, debug = true, capturePath = 'test/captures/'; //Determine environment //http://localhost/spektralvideo/ environment= casper.cli.args[1] || "http://spektraldevelopment.com/projects/spektralvideo/"; casper.echo("Environment is: " + environment); //Configure options casper.options.viewportSize = { width: 1024, height: 768 }; //Utils function screenshot(fileName) { if (debug === true) { casper.capture(capturePath + fileName + ".jpg"); } }; //Start test casper.test.begin('Spektral Video Test', 1, function suite(test) { casper.start(environment, function() { if (debug === true) { screenshot('pageReady'); } casper.waitForSelector('#theVideo'); }); casper.then(function() { screenshot('theVideo'); }); casper.run(function() { casper.echo('Test done.'); test.done(); }); });
spektraldevelopment/spektralvideo
test/spektralvideo_test.js
JavaScript
mit
946
import Controller from '@ember/controller'; export default Controller.extend({ countries: [ { name: 'United States' }, { name: 'Spain', }, { name: 'Portugal' }, { name: 'Russia' }, { name: 'Latvia' }, { name: 'Brazil' }, { name: 'United Kingdom' }, ] });
esbanarango/ember-power-select
tests/dummy/app/templates/snippets/the-search-3-js.js
JavaScript
mit
288
/** * Contains environment handling suff * @module machine.env */ 'use strict'; module.exports = function(kbox) { // Native var path = require('path'); var url = require('url'); // NPM modules var _ = require('lodash'); var fs = require('fs-extra'); // Kalabox modules var bin = require('./bin.js')(kbox); /* * Set Provider Env */ var setDockerEnv = function() { // Set Path environmental variable if we are on windows so we get access // to things like ssh.exe if (process.platform === 'win32') { var appData = process.env.LOCALAPPDATA; var programFiles = process.env.ProgramFiles; var programFiles2 = process.env.ProgramW6432; var gitBin1 = path.join(appData, 'Programs', 'Git', 'usr', 'bin'); var gitBin2 = path.join(programFiles, 'Git', 'usr', 'bin'); var gitBin3 = path.join(programFiles2, 'Git', 'usr', 'bin'); // Only add the gitbin to the path if the path doesn't start with // it. We want to make sure gitBin is first so other things like // putty don't F with it. // See https://github.com/kalabox/kalabox/issues/342 _.forEach([gitBin1, gitBin2, gitBin3], function(gBin) { if (fs.existsSync(gBin) && !_.startsWith(process.env.path, gBin)) { kbox.core.env.setEnv('Path', [gBin, process.env.Path].join(';')); } }); } // Add docker executables path to path to handle weird situations where // the user may not have machine in their path var pathString = (process.platform === 'win32') ? 'Path' : 'PATH'; var dockerPath = bin.getBinPath(); if (!_.startsWith(process.env[pathString], dockerPath)) { var newPath = [dockerPath, process.env[pathString]].join(path.delimiter); kbox.core.env.setEnv(pathString, newPath); } // Get our config so we can set our env correctly var engineConfig = kbox.core.deps.get('engineConfig'); // Parse the docker host url var dockerHost = url.format({ protocol: 'tcp', slashes: true, hostname: engineConfig.host, port: engineConfig.port }); // Set our docker host for compose if (process.platform === 'linux') { kbox.core.env.setEnv('DOCKER_HOST', dockerHost); } // Verify all DOCKER_* vars are stripped on darwin and windows if (process.platform === 'darwin' || process.platform === 'win32') { _.each(process.env, function(value, key) { if (_.includes(key, 'DOCKER_')) { delete process.env[key]; } }); } }; // Build module function. return { setDockerEnv: setDockerEnv }; };
kalabox/kalabox
plugins/kalabox-engine-docker/provider/docker/lib/env.js
JavaScript
mit
2,632
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14zm-1-6h-3V8h-2v5H8l4 4 4-4z" /></g> , 'SystemUpdate');
cherniavskii/material-ui
packages/material-ui-icons/src/SystemUpdate.js
JavaScript
mit
281
'use strict'; var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); module.exports = function(app) { app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(function(error, req, res, next) { if (error) { error = new Error('Invalid JSON'); error.status = 400; return next(error); } next(); }); };
ParalelniPolis/rfid-access-system-api
app/middleware/parsers.js
JavaScript
mit
416
var fs = require('fs'), mustache = require('mustache'), clientPath = __dirname + '/client/', licensePath = __dirname + '/../LICENSE', clientJS = '', newJS = '', view = {}; exports.build = function(url, callback){ view['url'] = url; setupJS(callback); }; var setupJS = function(callback){ getHTML(function(){ getCSS(function(){ getJS(function(){ renderJS(callback); }); }); }); }; var getHTML = function(callback){ fs.readFile(licensePath, 'utf8', function(err,data){ if(err) console.log(err); view['license'] = '/*' + data + '*/'; }); fs.readFile(clientPath + 'css-pcw-client.html','utf8',function(err,data) { if(err) console.log(err); view['html'] = data.replace(/^\s+/, '').replace(/\s+$/, '').replace(/\s+/g, ' ').replace(/<!--[\s\S]*?-->/g,''); callback(); }); }; var getCSS = function(callback){ fs.readFile(clientPath + 'css-pcw-client.css','utf8',function(err,data) { if(err) console.log(err); view['css'] = data; callback(); }); }; var getJS = function(callback){ fs.readFile(clientPath + 'css-pcw-client.js','utf8',function(err,data) { if(err) console.log(err); clientJS = data; callback(); }); }; var renderJS = function(callback){ newJS = mustache.render(clientJS,view); callback(newJS); };
aw2basc/css-pcw
src/css-pcw-build.js
JavaScript
mit
1,264
๏ปฟvar map; var markers = []; var initialLocation; var hk = new google.maps.LatLng(22.38,114.10); var browserSupportFlag = new Boolean(); var directionsDisplay; var oldDirections = []; var currentDirections = null; var geocoder = new google.maps.Geocoder(); var directionsService = new google.maps.DirectionsService(); var successCallback = function(position){ var x = position.coords.latitude; var y = position.coords.longitude; displayLocation(x,y); }; var errorCallback = function(error){ var errorMessage = 'Unknown error'; switch(error.code) { case 1: errorMessage = 'Permission denied'; break; case 2: errorMessage = 'Position unavailable'; break; case 3: errorMessage = 'Timeout'; break; } console.log(errorMessage); }; var options = { enableHighAccuracy: true, timeout: 1000, maximumAge: 0 }; function initialize() { var myOptions = { zoom: 17, zoomControl: true, mapTypeId: google.maps.MapTypeId.ROADMAP, scrollwheel: false }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); if(navigator.geolocation) { browserSupportFlag = true; navigator.geolocation.getCurrentPosition(function(position) { initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); map.setCenter(initialLocation); var marker = new google.maps.Marker({ position: initialLocation, map: map, title: 'You are Here.' }); }, function() { handleNoGeolocation(browserSupportFlag); }); } // Browser doesn't support Geolocation else { browserSupportFlag = false; handleNoGeolocation(browserSupportFlag); } function handleNoGeolocation(errorFlag) { if (errorFlag == true) { alert("ๅœฐๅœ–ๅฎšไฝๅคฑๆ•—"); } else { alert("ๆ‚จ็š„็€่ฆฝๅ™จไธๆ”ฏๆดๅฎšไฝๆœๅ‹™"); } initialLocation = hk; map.setCenter(initialLocation); } navigator.geolocation.getCurrentPosition(successCallback,errorCallback,options); } function calcRoute(pFrom,pEnd) { var start = pFrom; var end = pEnd; var request = { origin:start, destination:end, travelMode: google.maps.DirectionsTravelMode.DRIVING, avoidTolls: true }; codeAddress(); directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } }); } function codeAddress() { var address = document.getElementById( 'txtFrom' ).value; geocoder.geocode( { 'address' : address }, function( results, status ) { //console.log(address); if( status == google.maps.GeocoderStatus.OK ) { map.setCenter( results[0].geometry.location ); } else { alert( 'Geocode was not successful for the following reason: ' + status ); } } ); } function markerLatLng(allX,allY,allLoc,allX2,allY2) { //if(document.getElementById('txtFrom').value !='' && document.getElementById('txtEnd').value !=''){ var x = allX.split(","); var y = allY.split(","); var loc = allLoc.split(","); var Allx = allX2.split(","); var Ally = allY2.split(","); //console.log(loc); var str = "<table class='w3-table w3-table-all' style='position: absolute;top: 10px;right: 49px;display: block;height: 90vh;overflow-y: auto;'>"; deleteMarkers(); for ( var i = 0 ; i < x.length ; i++){ var xy = new google.maps.LatLng(x[i],y[i]); if ( i == 0 || i == x.length - 1) { var marker = new google.maps.Marker({ position: xy, map: map }); markers.push(marker); //if (i ==0){ //codeAddress(); //} } if ( i != x.length - 1) { var xy2 = new google.maps.LatLng(x[i+1],y[i+1]); calcRoute2(xy.lat(),xy.lng(),xy2.lat(),xy2.lng()); } } for ( var j = 0 ; j < loc.length ; j++){ var l; if (Allx[j] > 0){ l = Allx[j] + ',' + Ally[j] } str += "<tr><th>Stop " + (j+1) + "</th><td><a onclick='select(" + l + ")' class='w3-dropdown-click'>" + loc[j] + "</a></td></tr>"; } str += "</table>"; //console.log(str); document.getElementById("directions_panel").innerHTML = str; //directionsDisplay2.setPanel(document.getElementById("directions_panel")); //}else{ //alert("Please insert route."); //} } function select(x,y) { var initialLocation2 = new google.maps.LatLng(x,y); map.setCenter(initialLocation2); } function setMapOnAll(map) { for (var i = 0; i < markers.length; i++) { markers[i].setMap(map); } } function deleteMarkers() { setMapOnAll(null); markers = []; } function calcRoute2(x1,y1,x2,y2) { var directionsDisplay2 = new google.maps.DirectionsRenderer({ preserveViewport: false, suppressMarkers: true }); directionsDisplay2.setMap(map); //directionsDisplay2.setPanel(document.getElementById("directions_panel")); google.maps.event.addListener(directionsDisplay2, 'directions_changed', function() { if (currentDirections) { oldDirections.push(currentDirections); } currentDirections = directionsDisplay2.getDirections(); }); var request = { origin:{lat: x1, lng: y1}, destination:{lat: x2, lng: y2}, travelMode: google.maps.DirectionsTravelMode.DRIVING, avoidTolls: true }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay2.setDirections(response); } }); } function displayLocation(latitude,longitude){ var request = new XMLHttpRequest(); var method = 'GET'; var url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true'; //var async = true; request.open(method, url); request.onreadystatechange = function(){ if(request.readyState == 4 && request.status == 200){ var data = JSON.parse(request.responseText); var address = data.results[1]; //console.log(url); document.getElementById("txtFrom").value = address.address_components[2].long_name + address.address_components[1].long_name; } }; request.send(); }; function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition,showError); map.setCenter(initialLocation); } else{alert("Geolocation is not supported by this browser.");} } function showPosition(position) { console.log("Latitude: " + position.coords.latitude + " & Longitude: " + position.coords.longitude); } function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: alert("User denied the request for Geolocation."); break; case error.POSITION_UNAVAILABLE: alert("Location information is unavailable."); break; case error.TIMEOUT: alert("The request to get user location timed out."); break; case error.UNKNOWN_ERROR: alert("An unknown error occurred."); break; } }
kenchan20110/mini
public/javascripts/Geolocation.js
JavaScript
mit
7,550
var demo = (function() { var fileInput = document.getElementById('upload'), currentImg = document.createElement('img'), selectAll = document.getElementById('select-all'), selectPortionContainer = document.getElementById('select-portion-container'), selectPortion = document.getElementById('select-portion'), selectPortionCtx = selectPortion.getContext('2d'), clearSelection = document.getElementById('clear-selection'), statusContainer = document.getElementById('status-display'), inProgressIndicator = document.getElementById('pixelation-in-progress'), pixelationCompleteIndicator = document.getElementById('pixelation-complete'), widthInput = document.getElementById('section-width'), heightInput = document.getElementById('section-height'), pixelateBtn = document.getElementById('pixelate-btn'), outputContainer = document.getElementById('output-container'), beforeImg = document.getElementById('before'), afterImg = document.getElementById('after'), downloadNameInput = document.getElementById('download-name'), downloadLink = document.getElementById('download'), errorContainer = document.getElementById('error-container'), selectedPortion = { x: 0, y: 0, status: 0, SELECT_RECT_COLOR: '#FFFFFF', SELECT_RECT_WIDTH: 2, updateCanvas: function() { switch (this.status) { case 0: selectPortionCtx.drawImage(currentImg, 0, 0, currentImg.width, currentImg.height); break; case 1: selectPortionCtx.fillStyle = this.SELECT_RECT_COLOR; selectPortionCtx.fillRect(this.x, this.y, this.SELECT_RECT_WIDTH, this.SELECT_RECT_WIDTH); break; case 2: selectPortionCtx.strokeStyle = this.SELECT_RECT_COLOR; selectPortionCtx.lineWidth = this.SELECT_RECT_WIDTH; selectPortionCtx.beginPath(); selectPortionCtx.rect(this.x, this.y, this.width, this.height); selectPortionCtx.stroke(); } }, reset: function(opt_updateCanvas) { this.x = 0; this.y = 0; this.width = 0; this.height = 0; this.status = 0; if (opt_updateCanvas) { this.updateCanvas(); } }, clone: function() { var clone = {}; for (var key in this) { var value = this[key]; if (typeof value === 'function') { clone[key] = value.bind(clone); } else { clone[key] = value; } } return clone; } }, pixelations = []; fileInput.addEventListener('change', function() { var file = fileInput.files[0], reader = new FileReader(); if (file instanceof File && /\.(jpe?g|png|gif)$/i.test(file.name)) { reader.addEventListener('load', function() { currentImg.src = this.result; selectPortion.width = currentImg.width; selectPortion.height = currentImg.height; selectedPortion.reset(true); }); reader.readAsDataURL(file); if (selectAll.checked) { hide(selectPortionContainer); } else { show(selectPortionContainer); } } else { error('As of now, this tool only supports jpg, jpeg, png, and gif files.'); } }); pixelateBtn.addEventListener('click', function() { show(statusContainer); updateStatus(false); }); pixelateBtn.addEventListener('click', function() { var file = fileInput.files[0]; hide(errorContainer); if (file instanceof File && /\.(jpe?g|png|gif)$/i.test(file.name)) { var reader = new FileReader(), canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'); reader.addEventListener('load', function() { var dataURL = this.result, pixelatedPortionURL, pixelatedPortionImage = document.createElement('img'), afterImgDataURL, width, height, pixelator, useWholeImg = selectAll.checked || selectedPortion.width <= 0 || selectedPortion.height <= 0 || selectedPortion.status !== 2; beforeImg.src = dataURL; width = beforeImg.width; height = beforeImg.height; canvas.width = width; canvas.height = height; ctx.drawImage(beforeImg, 0, 0, width, height); if (useWholeImg) { pixelator = new Pixelator(ctx.getImageData(0, 0, width, height)); } else { pixelator = new Pixelator(ctx.getImageData(selectedPortion.x, selectedPortion.y, selectedPortion.width, selectedPortion.height)); } pixelatedPortionURL = pixelator.pixelate((widthInput.value | 0) || 10, (heightInput.value | 0) || 10).canvas.toDataURL('image/png', 1); pixelatedPortionImage.src = pixelatedPortionURL; if (useWholeImg) { ctx.drawImage(pixelatedPortionImage, 0, 0, width, height); } else { ctx.drawImage(pixelatedPortionImage, selectedPortion.x, selectedPortion.y, pixelatedPortionImage.width, pixelatedPortionImage.height); } afterImgDataURL = canvas.toDataURL('image/png', 1.0); afterImg.src = afterImgDataURL; downloadLink.href = afterImgDataURL; downloadLink.download = '(pixelated) ' + file.name; downloadNameInput.value = '(pixelated) ' + file.name; updateStatus(true); show(outputContainer); pixelations.push(new Pixelation(pixelator, dataURL, afterImgDataURL, selectedPortion.clone())); }); reader.readAsDataURL(file); } else { error('As of now, this tool only supports jpg, jpeg, png, and gif files.'); } }); selectAll.addEventListener('change', function() { if (selectAll.checked) { hide(selectPortionContainer); } else { show(selectPortionContainer); } }); selectPortion.addEventListener('click', function(e) { var status = selectedPortion.status, coords = getClickCoords(selectPortion, e), x = coords.x, y = coords.y; switch (status) { case 0: selectedPortion.x = x; selectedPortion.y = y; selectedPortion.status = 1; selectedPortion.updateCanvas(); break; case 1: if (x <= selectedPortion.x || y <= selectedPortion.y) { error('The second point must be lower and to the right of the first point.'); break; } selectedPortion.width = x - selectedPortion.x; selectedPortion.height = y - selectedPortion.y; selectedPortion.status = 2; selectedPortion.updateCanvas(); break; default: break; } }); clearSelection.addEventListener('click', function() { var userHasConfirmed = confirm('Are you sure you want to restart your selection?'); if (userHasConfirmed) { selectedPortion.reset(true); } }); downloadNameInput.addEventListener('change', function() { downloadLink.download = downloadNameInput.value; }); function error(msg) { show(errorContainer); hide(outputContainer); errorContainer.innerHTML = msg; } function show() { var i = arguments.length; while (i--) { arguments[i].style.display = 'inherit'; } } function hide() { var i = arguments.length; while (i--) { arguments[i].style.display = 'none'; } } function getClickCoords(elem, event) { var rect = elem.getBoundingClientRect(); return { x: event.x - rect.left, y: event.y - rect.top }; } function updateStatus(complete) { if (complete) { hide(inProgressIndicator); show(pixelationCompleteIndicator); } else { hide(pixelationCompleteIndicator); show(inProgressIndicator); } } function Pixelation(pixelator, beforeURL, afterURL, selectedPortion) { this.pixelator = pixelator; this.beforeURL = beforeURL; this.afterURL = afterURL; this.selectedPortion = selectedPortion; this.id = Pixelation.getId(); } Pixelation.getId = (function() { var id = 0; return function() { return id++; } })(); return { error: error, show: show, hide: hide, fileInput: fileInput, selectAll: selectAll, selectPortion: selectPortion, widthInput: widthInput, heightInput: heightInput, beforeImage: beforeImg, afterImage: afterImg, downloadLink: downloadLink, pixelations: pixelations }; // For debug purposes. })();
LeeryanK/pixelator
js/demo.js
JavaScript
mit
10,782
#!/usr/bin/env node require('../lib/setup')(); var wdn = require('../'); var minimist = require('minimist'); var defaults = { boolean: [ 'help', 'version', 'list', 'clear', 'clean', 'force', 'ssh' ], alias: { h: 'help', v: 'version', ls: 'list', a: 'add', rm: 'remove', 'rm-all': 'clear', 'remove-all': 'clear', s: 'show', x: 'clean', f: 'force', c: 'config' }, default: { help: false, version: false, list: false, clear: false, clean: false, force: false, config: null, add: null, remove: null, show: null, ssh: false } }; var keywords = [ 'help', 'h', 'version', 'v', 'list', 'ls', 'add', 'a', 'remove', 'rm', 'clear', 'rm-all', 'remove-all', 'show', 's', 'clean', 'x', 'ssh', '--setup' ]; var options = minimist(process.argv.slice(2), defaults); var firstArg = (options._.length) ? options._[0] : null; // allow cli options without leading dash and rebuild options if (keywords.indexOf(firstArg) !== -1) { if (/^help$|^h$/.test(firstArg)) { options.help = options.h = true; options._ = options._.slice(1); } else if (/^version|^v$/.test(firstArg)) { options.version = options.v = true; options._ = options._.slice(1); } else if (/^list|^ls$/.test(firstArg)) { options.list = options.ls = true; options._ = options._.slice(1); } else if (/^clear$|^rm\-all$|^remove\-all$/.test(firstArg)) { options.clear = true; options._ = options._.slice(1); } else if (/^clean$|^x$/.test(firstArg)) { options.clean = true; options._ = options._.slice(1); } else if (/^show$|^s$/.test(firstArg)) { options.show = options.s = options._[1] || process.cwd(); options._ = options._.slice(2); } else if (/^add$|^a$/.test(firstArg)) { options.add = options.a = options._[1]; options._ = options._.slice(2); } else if (/^remove$|^rm$/.test(firstArg)) { options.remove = options.rm = options._[1]; options._ = options._.slice(2); } else if (/^ssh$/.test(firstArg)) { options.ssh = true; options._ = options._.slice(1); } } wdn({ args: options._, help: options.help, version: options.version, list: options.list, clear: options.clear, add: options.add, remove: options.remove, show: options.show, clean: options.clean, force: options.force, config: options.config, ssh: options.ssh });
greg-js/wdn
bin/cli.js
JavaScript
mit
2,449
'use strict'; var express = require('express'); var config = require('./controller/config'); var router = express.Router(); // Route to UPDATE the config router.post('/config', function (req, res) { req.params.update = config.update(req); res.send(req.params.update); }); // Route to READ the config router.get('/config', function (req, res) { req.params.fetch = config.get(); res.send(req.params.fetch); }); // Render settings page router.get('/', function (req, res) { res.render('settings'); }); module.exports = router;
sahil505/StyleGuideDesigner
app/routes.js
JavaScript
mit
535
/* * seneca-nats-transport * For the full copyright and license information, please view the LICENSE.txt file. */ /* jslint node: true */ 'use strict'; var nats = require('nats'); module.exports = function(options) { var NATS_SERVERS = process.env.NATS_SERVERS, NATS_URL = process.env.NATS_URL; var seneca = this, plugin = 'nats-transport'; var senecaOpts = seneca.options(), transpUtils = seneca.export('transport/utils'); options = seneca.util.deepextend({ nats: { reconnect: true, maxReconnectAttempts: 9999, reconnectTimeWait: 1000 } }, senecaOpts.transport, options); // Check nats servers if(!options.nats.servers && NATS_SERVERS) { options.nats.servers = NATS_SERVERS.split(','); } if(options.nats.servers) { if(options.nats.servers instanceof Array) { for(var i = 0, len = options.nats.servers.length; i < len; i++) { if(typeof options.nats.servers[i] === 'string' && options.nats.servers[i].indexOf('nats://') !== 0) { options.nats.servers[i] = 'nats://' + options.nats.servers[i]; } } } } // Check nats url if(!options.nats.url && NATS_URL) { options.nats.url = NATS_URL; } if(options.nats.url) { if(typeof options.nats.url === 'string' && options.nats.url.indexOf('nats://') !== 0) { options.nats.url = 'nats://' + options.nats.url; } } // Listen hook for the transport seneca.add({role: 'transport', type: 'nats', hook: 'listen'}, function(msg, done) { var seneca = this, type = msg.type, clientOpts = seneca.util.clean(seneca.util.deepextend({}, options[type], msg)), clientName = 'listen-' + type, nc = nats.connect(options[type]); // Connect event nc.on('connect', function(/*client*/) { seneca.log.info('listen', 'open', clientOpts); }); // Error event nc.on('error', function(err) { seneca.log.error('listen', 'error', err); }); // Listen topics transpUtils.listen_topics(seneca, msg, clientOpts, function(topic) { var topicAct = topic + '_act', topicRes = topic + '_res'; // Subscribe to act topic nc.subscribe(topicAct, function(msg) { seneca.log.debug('listen', 'subscribe', topicAct, 'message', msg); // Handle request transpUtils.handle_request(seneca, transpUtils.parseJSON(seneca, clientName, msg), clientOpts, function(out) { // If there is an output then if(out) { // Publish it to response topic nc.publish(topicRes, transpUtils.stringifyJSON(seneca, clientName, out)); } }); }); seneca.log.info('listen', 'subscribe', topicAct); }); // Closer action seneca.add({role: 'seneca', cmd: 'close'}, function(args, cb) { seneca.log.debug('listen', 'close', clientOpts); nc.close(); this.prior(args, cb); }); done(); }); // Client hook for the transport seneca.add({role: 'transport', type: 'nats', hook: 'client'}, function(msg, done) { var seneca = this, type = msg.type, clientOpts = seneca.util.clean(seneca.util.deepextend({}, options[type], msg)), clientName = 'client-' + type, nc = nats.connect(options[type]); // Connect event nc.on('connect', function(/*client*/) { seneca.log.info('client', 'open', clientOpts); }); // Error event nc.on('error', function(err) { seneca.log.error('client', 'error', err); }); // Send is called for per topic function send(spec, topic, sendDone) { var topicAct = topic + '_act', topicRes = topic + '_res'; // Subscribe to response topic nc.subscribe(topicRes, function(msg) { seneca.log.debug('client', 'subscribe', topicRes, 'message', msg); // Handle response transpUtils.handle_response(seneca, transpUtils.parseJSON(seneca, clientName, msg), clientOpts); }); seneca.log.info('client', 'subscribe', topicRes); // Send message over the transport sendDone(null, function(msg, cb) { seneca.log.debug('client', 'publish', topicAct, 'message', msg); // Publish act nc.publish(topicAct, transpUtils.stringifyJSON(seneca, clientName, transpUtils.prepare_request(seneca, msg, cb))); }); // Closer action seneca.add({role: 'seneca', cmd: 'close'}, function(args, cb) { seneca.log.debug('client', 'close', clientOpts, 'topic', topic); nc.close(); this.prior(args, cb); }); } // Use transport utils to make client transpUtils.make_client(send, clientOpts, done); }); // Return return { name: plugin }; };
cmfatih/seneca-nats-transport
index.js
JavaScript
mit
4,798
var pull = require('pull-stream') var duplex = require('../') var test = require('tape') test('should start to flow when data listener is added', function (t) { var s = duplex(null, pull(pull.values(['hello']))), timer setTimeout(() => { s.on('data', (d) => { clearTimeout(timer) t.equal(d, 'hello') t.end() }) }, 100) timer = setTimeout(() => { t.fail('data event listener was not invoked') t.end() }, 200) })
dominictarr/pull-stream-to-stream
test/data-event.js
JavaScript
mit
465
/** * * @author : Mei XinLin * @version : 1.0 */ import React, { Component } from "react"; import PropTypes from 'prop-types'; import {connect} from "react-redux"; import * as frame from "mainApp/core/frame"; import {getBgImgInfo} from "./bgTool"; export class PanelContainer extends Component { static propTypes = { title: PropTypes.string, htmlSize: PropTypes.object.isRequired }; render() { let panelTitle; if (this.props.title) { panelTitle = ( <div className="panel-heading"> <h4 className="panel-title">{this.props.title}</h4> </div> ); } return ( <div className="panel panel-blur" style={calculateBgStyle(this.props.htmlSize)}> {panelTitle} <div className="panel-body"> {this.props.children} </div> </div> ); } } function calculateBgStyle(htmlSize) { const bgInfo = getBgImgInfo(htmlSize); let bgStyle = {}; if (bgInfo) { bgStyle['backgroundSize'] = Math.round(bgInfo.width) + 'px ' + Math.round(bgInfo.height) + 'px'; bgStyle['backgroundPosition'] = Math.floor(bgInfo.positionX) + 'px ' + Math.floor(bgInfo.positionY) + 'px'; } return bgStyle; } const mapStateToProps = (state) => ({ htmlSize: frame.selectors.getHtmlSize(state) }); export default connect(mapStateToProps, null)(PanelContainer);
m544498510/may-swim-app
src/main/frontend/src/script/mainApp/views/common/PanelContainer/index.js
JavaScript
mit
1,362
/** * An event mixin. * Event naming: * EventName - Common events * ComponentName.EventName - Component-specific events * @type {{on: Function, off: Function, trigger: Function}} */ var ObservableMixin = { _initEvents: function () { this._eventCallbacks = {}; }, on: function (event, callback) { if (!this._eventCallbacks[event]) { this._eventCallbacks[event] = []; } this._eventCallbacks[event].push(callback); }, off: function (event, callback) { if (Array.isArray(this._eventCallbacks[event])) { var index = this._eventCallbacks[event].indexOf(callback); if (index > -1) { this._eventCallbacks[event].splice(index, 1); } } }, trigger: function (event, data) { if (Array.isArray(this._eventCallbacks[event])) { var len = this._eventCallbacks[event].length; for (var iCallback = 0; iCallback < len; ++iCallback) { this._eventCallbacks[event][iCallback](data); } } if (this.parent && this.parent.trigger) { this.parent.trigger(event, data); } } }; function copyProperties(from, to) { for (var attr in from) { if (from.hasOwnProperty(attr)) { to[attr] = from[attr]; } } } /** * An Application * Handles components * * Usage: * // Create an application * var App = new Application(); * * // Create a component * App.component('Example', { * selector: '.component-class', * * init: function (app) { * // Initialize state here * } * }); * * // Initialize the application * App.init(); * * @constructor */ function Application() { copyProperties(ObservableMixin, this); this._initEvents(); this.components = []; this.uninitComponents = []; this.inactiveComponents = []; this.initialized = false; } Application.prototype = { constructor: Application, /** * Initializes the application */ init: function () { var components = this.uninitComponents; var component; for (var iComp = 0; iComp < components.length; ++iComp) { component = components[iComp]; component._prepare(this); if (component._shouldInitialize()) { component.init(this); this.components.push(component); console.log('Component ' + component.name + ' initialized.'); } else { component._reset(); this.inactiveComponents.push(component); } } this.uninitComponents.length = 0; }, /** * Reset all the components */ reset: function () { var components = this.components.concat(this.inactiveComponents); this.uninitComponents = components; this.components = []; this.inactiveComponents = []; for (var iComp = 0; iComp < components.length; ++iComp) { components[iComp]._reset(); } this.initialized = false; }, /** * Creates a component and add it the application * @param name * @param opts */ component: function (name, opts) { opts.name = name; var component = new Component(opts); this.addComponent(component); }, /** * Adds and initializes the component * @param component */ addComponent: function (component) { if (this.initialized) { component._prepare(this); if (component._shouldInitialize()) { component.init(this); this.components.push(component); } else { component._reset(); } } else { this.uninitComponents.push(component); } }, /** * Get a component by the name. * @param name */ getComponent: function (name) { var components = this.components; for (var iComp = 0; components.length; ++iComp) { if (components[iComp].name == name) { return components[iComp] } } } }; /** * A Component * @param opts {object} * @constructor */ function Component(opts) { copyProperties(ObservableMixin, this); this._initEvents(); this.guard = function () { return true; }; this.init = function () { console.warn('An init method is not provided for the ' + this.name + ' component.'); }; this.state = {}; for (var opt in opts) { if (opts.hasOwnProperty(opt)) { this[opt] = opts[opt]; } } } Component.prototype = { constructor: Component, /** * Prepares the component for initialization * Sets this.element using this.selector * @private */ _prepare: function (app) { if (!this.selector) { throw 'A selector is not provided for the ' + this.name + ' component.'; } this.element = $(this.selector); this.engine = app; this.parent = app; }, /** * Resets the component's state * @private */ _reset: function () { this.state = {}; delete this.engine; delete this.parent; delete this.element; }, /** * @returns {boolean} * @private */ _shouldInitialize: function () { return this.guard() && this.element.length; } }; exports.Application = Application; exports.Component = Component;
voidxnull/jqomp
jqomp.js
JavaScript
mit
5,007
import jspm from 'jspm'; import Promise from 'bluebird'; import whacko from 'whacko'; import _ from 'lodash'; import fs from 'fs'; import utils from 'systemjs-builder/lib/utils'; import path from 'path'; export function unbundle(_opts) { let opts = _.defaultsDeep(_opts, { packagePath: '.', template: {} }); jspm.setPackagePath(opts.packagePath); let builder = new jspm.Builder(); let tasks = [removeJSBundle(opts), removeTemplateBundles(opts, builder)]; return Promise.all(tasks); } function removeJSBundle(opts) { return jspm.unbundle(); } function removeTemplateBundles(opts, builder) { let baseURL = utils.fromFileURL(builder.loader.baseURL); let tmplCfg = opts.template; let tasks = []; Object .keys(tmplCfg) .forEach((key) => { let cfg = tmplCfg[key]; tasks.push(removeTemplateBundle(cfg, baseURL)) }); return Promise.all(tasks); function removeTemplateBundle(_cfg, _baseURL) { let cfg = _.defaultsDeep(_cfg, { indexFile: 'index.html', destFile: 'index.html' }); let file = path.resolve(_baseURL, cfg.destFile); return Promise .promisify(fs.readFile)(file, { encoding: 'utf8' }) .then((content) => { let $ = whacko.load(content); return Promise.resolve($); }) .then(($) => { return removeLinkInjections($) }) .then(($) => { return Promise.promisify(fs.writeFile)(file, $.html()); }); } } function removeLinkInjections($) { $('link[aurelia-view-bundle]').remove(); return Promise.resolve($); }
jdanyow/cli
src/lib/unbundler.js
JavaScript
mit
1,592
/** * @author Adam Meadows [@job13er](https://github.com/job13er) * @copyright 2015 Ciena Corporation. All rights reserved */ require('../typedefs'); module.exports = { /** * Throw a CliError * @param {String} message - the error message * @param {Number} [exitCode] - the exit code for CLI command * @throws {CliError} */ throwCliError: function (message, exitCode) { throw { message: message, exitCode: exitCode, }; }, };
nskrypnik/beaker
src/cli/utils.js
JavaScript
mit
507
/*! Deep linking options parsing support for DataTables * 2017 SpryMedia Ltd - datatables.net/license */ (function(l,m,b,n){var h=b.fn.dataTable.ext.internal._fnSetObjectDataFn;b.fn.dataTable.ext.deepLink=function(d){for(var e=location.search.replace(/^\?/,"").split("&"),f={},c=0,k=e.length;c<k;c++){var a=e[c].split("="),g=decodeURIComponent(a[0]),a=decodeURIComponent(a[1]);if("true"===a)a=!0;else if("false"===a)a=!1;else if(!a.match(/[^\d]/))a*=1;else if(0===a.indexOf("{")||0===a.indexOf("["))try{a=b.parseJSON(a)}catch(p){}"all"!==d&&-1===b.inArray(g,d)||h(g)(f,a)}return f}})(window,document,jQuery);
maulviinayat67/tugas-sbd
assets/plugins/DataTables/Plugins-master/features/deepLink/dataTables.deepLink.min.js
JavaScript
mit
611
/* eslint-env node, mocha */ /* global expect */ /* eslint no-console: 0 */ 'use strict'; // Uncomment the following lines to use the react test utilities // import TestUtils from 'react-addons-test-utils'; import createComponent from 'helpers/shallowRenderHelper'; import IndexComponent from 'components/popup/IndexComponent.js'; describe('IndexComponent', () => { let component; beforeEach(() => { component = createComponent(IndexComponent); }); it('should have its component name as default className', () => { expect(component.props.className).to.equal('index-component'); }); });
Philin-Anton/prototypeApp
test/components/popup/IndexComponentTest.js
JavaScript
mit
609
export default function messageDialog() { // DDO return { restrict: 'E', templateUrl: 'templates/_bootstrap/directives/messageDialog.tpl.html', transclude: true, scope: { visible: '=', title: '=', onYes: '&', onNo: '&' } }; }
justphil/angular-es6-components-seed
src/_bootstrap/directives/messageDialog.js
JavaScript
mit
326
import { Component } from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; export default class TagFilter extends Component { constructor(props) { super(props); this.goHome = this.goHome.bind(this); } initQueryFilter() { const { loadCategories, loadTags } = this.props; loadCategories(); loadTags(); } goHome() { const { dispatch } = this.props; dispatch(push('/')); } getFilteredPosts(categoryInput, tagInput, searchInput) { const { dispatch, loadPosts } = this.props; let fullUrl = ''; let params = {}; // if there is no input, then show all posts again, if not, then show posts filtered by queries if (searchInput.value !== '' || tagInput.value !== '' || categoryInput.value !== '') { if (categoryInput.value !== '') { fullUrl += `/category/${categoryInput.value}`; params.category = categoryInput.value; } if (tagInput.value !== '') { fullUrl += `/tag/${tagInput.value}`; params.tag = tagInput.value; } if (searchInput.value !== '') { fullUrl += `/search/${searchInput.value}`; params.search = searchInput.value; } dispatch(push(fullUrl)); loadPosts(fullUrl, params, false); } else { dispatch(push('/')) loadPosts('/', params, false); } } componentDidMount() { this.initQueryFilter(); } render() { let categoryInput; let tagInput; let searchInput; return ( <div> <form className="query-filter" onSubmit={e => { e.preventDefault(); this.getFilteredPosts(categoryInput, tagInput, searchInput); }}> <i className="header__icon [ icon ion-trash-b ] [ hide-mobile hide-palm ]" onClick={this.goHome}></i> <select className="query-filter__select query-filter__select--category" ref={node => { categoryInput = node}}> <option value="">Categories</option> {Object.keys(this.props.categories).length ? Object.values(this.props.categories).map(category => <option key={category.slug} value={category.slug}>{category.slug}</option>) : <option value="">Loading...</option> } </select> <select className="query-filter__select query-filter__select--tag" ref={node => { tagInput = node}}> <option value="">Tags</option> {Object.keys(this.props.tags).length ? Object.values(this.props.tags).map(tag => <option key={tag.slug} value={tag.slug}>{tag.slug}</option>) : <option value="">Loading...</option> } </select> <input className="query-filter__input query-filter__input--search" type="text" placeholder="search" ref={node => { searchInput = node; }}/> <button className="query-filter__button query-filter__button--submit" type="submit"></button> </form> </div> ) } } export default connect()(TagFilter);
RyoIkarashi/garbage
src/containers/QueryFilter.js
JavaScript
mit
3,069
memberSearchIndex = [{"p":"main","c":"MyString1","l":"charAt(int)"},{"p":"main","c":"MyString1","l":"equals(MyString1)","url":"equals-main.MyString1-"},{"p":"main","c":"MyString1","l":"length()"},{"p":"main","c":"MyString1","l":"MyString1(char[])"},{"p":"main","c":"MyString1","l":"substring(int, int)"},{"p":"main","c":"MyString1","l":"toLowerCase()"},{"p":"main","c":"MyString1","l":"valueOf(int)"}]
tliang1/Java-Practice
Practice/Intro-To-Java-8th-Ed-Daniel-Y.-Liang/Chapter-9/Chapter09P23/doc/member-search-index.js
JavaScript
mit
401
const chalk = require('chalk'); const fs = require('fs'); const path = require('path'); module.exports.out = { print: text => console.log(chalk.blue(text)), success: text => console.log(chalk.green(text)), error: text => console.log(chalk.bold.red(text)), }; module.exports.writeJSON = (filePath, data, reject) => { if (!fs.existsSync(path.dirname(filePath))) { fs.mkdirSync(path.dirname(filePath)); } fs.writeFile(filePath, JSON.stringify(data), { mode: '0600' }, (err) => { if (err) { // who knows what happened, just send it back reject(err); } }); };
ferjgar/youtube-backup
lib/util.js
JavaScript
mit
596
module.exports = function (minutes) { if(typeof minutes === 'string'){ minutes = Number(minutes); } var hours = parseInt( minutes/60, 10 ); var mins = minutes%60; return hours+'hr '+mins+'min'; }
time2hack/movie-db
src/js/utils/duration.js
JavaScript
mit
210
/* (The MIT License) Copyright (C) 2005-2013 Kai Davenport 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. */ /* Module dependencies. */ var _ = require('lodash'); var Warehouse = require('./warehouse'); module.exports = factory; /* supplier constructor if the network is provided then it means the supplier is connected otherwise it is running standalone (and will resolve it's own contracts) */ function factory(type, config, network){ config || (config = {}); if(!config.id){ throw new Error('Supplier requires an id in config'); } if(!type){ throw new Error('Supplier requires type in config'); } var SupplierClass = null; if(type.indexOf('quarry')==0){ SupplierClass = require('./supplier/' + type.replace(/^quarry\./, '').replace(/\./g, '/')); } else{ SupplierClass = require(type); } return SupplierClass(config, network); }
binocarlos/quarry.io
lib/supplier.js
JavaScript
mit
1,879
// via: http://stackoverflow.com/questions/22581345/click-button-copy-to-clipboard-using-jquery document.getElementById("copyButton").addEventListener("click", function() { copyToClipboard(document.getElementById("copyTarget")); }); function copyToClipboard(elem) { // create hidden text element, if it doesn't already exist var targetId = "_hiddenCopyText_"; var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA"; var origSelectionStart, origSelectionEnd; if (isInput) { // can just use the original source element for the selection and copy target = elem; origSelectionStart = elem.selectionStart; origSelectionEnd = elem.selectionEnd; } else { // must use a temporary form element for the selection and copy target = document.getElementById(targetId); if (!target) { var target = document.createElement("textarea"); target.style.position = "absolute"; target.style.left = "-9999px"; target.style.top = "0"; target.id = targetId; document.body.appendChild(target); } target.textContent = elem.textContent; } // select the content var currentFocus = document.activeElement; target.focus(); target.setSelectionRange(0, target.value.length); // copy the selection var succeed; try { succeed = document.execCommand("copy"); } catch(e) { succeed = false; } // restore original focus if (currentFocus && typeof currentFocus.focus === "function") { currentFocus.focus(); } if (isInput) { // restore prior selection elem.setSelectionRange(origSelectionStart, origSelectionEnd); } else { // clear temporary content target.textContent = ""; } return succeed; }
domhnallohanlon/thunkable_extensions
assets/js/copy-text.js
JavaScript
mit
1,874
const seneca = require('seneca'); const Commands = require('./commands'); const logger = require('./logger'); const amqpConfig = require('./config/amqp'); const start = () => { // get plugin with interfaces const commands = Commands.start(); amqpConfig.pin = commands.pins; // create listener const listener = seneca() .use('seneca-amqp-transport') .use(commands.plugin) .listen(amqpConfig); // start server return new Promise((fulfill) => { listener.ready((e) => { logger.info('listener is done'); fulfill(e); }); }); }; module.exports = { start };
davidlondono/boilerplate-seneca-n8
src/server.js
JavaScript
mit
601
version https://git-lfs.github.com/spec/v1 oid sha256:c77d296d504d4f36fbdbe499062840ba483ad971fb046ca3956a7a8bc1b6d8fc size 5519
yogeshsaroya/new-cdnjs
ajax/libs/codemirror/4.7.0/mode/gfm/test.js
JavaScript
mit
129
const express = require('express'); const router = express.Router(); router.get('/', function (req, res, next) { res.redirect('landing'); }); module.exports = router;
gvickstrom/Fishing_App
src/server/routes/index.js
JavaScript
mit
171
/** * DevExtreme (integration/knockout/components.js) * Version: 16.2.5 * Build date: Mon Feb 27 2017 * * Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED * EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml */ "use strict"; var $ = require("jquery"), errors = require("../../core/errors"), Action = require("../../core/action"), compileGetter = require("../../core/utils/data").compileGetter, ko = require("knockout"), iconUtils = require("../../core/utils/icon"), inflector = require("../../core/utils/inflector"), clickEvent = require("../../events/click"); ko.bindingHandlers.dxAction = { update: function(element, valueAccessor, allBindingsAccessor, viewModel) { var $element = $(element); var unwrappedValue = ko.utils.unwrapObservable(valueAccessor()), actionSource = unwrappedValue, actionOptions = { context: element }; if (unwrappedValue.execute) { actionSource = unwrappedValue.execute; $.extend(actionOptions, unwrappedValue) } var action = new Action(actionSource, actionOptions); $element.off(".dxActionBinding").on(clickEvent.name + ".dxActionBinding", function(e) { action.execute({ element: $element, model: viewModel, evaluate: function(expression) { var context = viewModel; if (expression.length > 0 && "$" === expression[0]) { context = ko.contextFor(element) } var getter = compileGetter(expression); return getter(context) }, jQueryEvent: e }); if (!actionOptions.bubbling) { e.stopPropagation() } }) } }; ko.bindingHandlers.dxControlsDescendantBindings = { init: function(_, valueAccessor) { return { controlsDescendantBindings: ko.unwrap(valueAccessor()) } } }; ko.bindingHandlers.dxPolymorphWidget = { init: function(element, valueAccessor, allBindings, viewModel, bindingContext) { var widgetName = ko.utils.unwrapObservable(valueAccessor()).name; if (!widgetName) { return } ko.virtualElements.emptyNode(element); if ("button" === widgetName || "tabs" === widgetName || "dropDownMenu" === widgetName) { var deprecatedName = widgetName; widgetName = inflector.camelize("dx-" + widgetName); errors.log("W0001", "dxToolbar - 'widget' item field", deprecatedName, "16.1", "Use: '" + widgetName + "' instead") } var markup = $('<div data-bind="' + widgetName + ': options">').get(0); ko.virtualElements.prepend(element, markup); var innerBindingContext = bindingContext.extend(valueAccessor); ko.applyBindingsToDescendants(innerBindingContext, element); return { controlsDescendantBindings: true } } }; ko.virtualElements.allowedBindings.dxPolymorphWidget = true; ko.bindingHandlers.dxIcon = { init: function(element, valueAccessor) { var options = ko.utils.unwrapObservable(valueAccessor()) || {}, iconElement = iconUtils.getImageContainer(options); ko.virtualElements.emptyNode(element); if (iconElement) { ko.virtualElements.prepend(element, iconElement.get(0)) } }, update: function(element, valueAccessor) { var options = ko.utils.unwrapObservable(valueAccessor()) || {}, iconElement = iconUtils.getImageContainer(options); ko.virtualElements.emptyNode(element); if (iconElement) { ko.virtualElements.prepend(element, iconElement.get(0)) } } }; ko.virtualElements.allowedBindings.dxIcon = true;
imironica/Fraud-Detection-System
FraudDetection.Web/wwwroot/node_modules/devextreme/integration/knockout/components.js
JavaScript
mit
3,925
function loadSVGBarChart() { $.fn.svgBarGraph = function(options) { _calcFinalDrop = function(array, height) { return (height - array[array.length - 1].y); } var defaults = { width: 100, height: 100, graduationX: 10, graduationY: 10, plotPoints: [{ //start time x: 0, // event id y: 100 }] }; var _options = $.extend(defaults, options), _this = this; _options.numberOfVertGridLines = (_options.width / _options.graduationX); _options.numberOfHorizGridLines = (_options.height / _options.graduationY) + 1; _options.finalDrop = _calcFinalDrop(_options.plotPoints, _options.height) console.log(_options); $.get('/svggraph.htm', function(data, status) { var renderer = Handlebars.compile(data); console.log(_options); var result = renderer(_options); _this.html(result); // var hoverWidget = _this.find('#hoverWidget'); // // add click handlers to points // hoverWidget.show(); // _this.mousemove(function(event) { // hoverWidget.attr({ // 'cx': event.clientX // }); // }); }); } }
SteFletcher/carrot
js/svggraph.js
JavaScript
mit
1,460
$(function(){ var themes = [{ name: 'default', title: 'Default' }, { name: 'slide', title: 'Slide' }, { name: 'dark', title: 'Dark' }, { name: 'chrome', title: 'Chrome' }]; var indicatorThemes = [{ name: 'default-indicator', title: 'Default' }, { name: 'slide-indicator', title: 'Slide' }, { name: 'dark-indicator', title: 'Dark' }, { name: 'chrome-indicator', title: 'Chrome' }]; var addThemes = function(themes, selector) { $.each(themes, function(i, theme){ $(selector).append('<div class="theme ' + (i % 2 === 0 ? 'even' : 'odd') + '">'+ '<h3>' + theme.title + '</h3>' + '<p><a href="/offline/themes/offline-theme-' + theme.name + '.css" class="download-link">download</a></p>'+ '<div class="browser"><iframe data-theme="' + theme.name + '"></iframe></div>' + '</div>'); }); }; addThemes(themes, '.full-themes'); addThemes(indicatorThemes, '.indicator-themes'); $('.browser iframe').each(function(){ var _this = this; var themeName = $(this).data('theme'); doc = (this.contentWindow || this.documentWindow).document; doc.open(); doc.write('' + '<link rel="stylesheet" href="/offline/themes/offline-theme-' + themeName + '.css" />' + '<div data-phase="0" class="offline-ui offline-ui-down"><div class="offline-ui-content"></div><a class="offline-ui-retry"></a></div>' + ''); doc.close(); }); var phases = [ [5, 'offline-ui offline-ui-down', '', ''], [3, 'offline-ui offline-ui-down offline-ui-connecting offline-ui-waiting', '5 seconds', '5s'], [1, 'offline-ui offline-ui-down offline-ui-connecting offline-ui-waiting', '4 seconds', '4s'], [1, 'offline-ui offline-ui-down offline-ui-connecting offline-ui-waiting', '3 seconds', '3s'], [1, 'offline-ui offline-ui-down offline-ui-connecting offline-ui-waiting', '2 seconds', '2s'], [1, 'offline-ui offline-ui-down offline-ui-connecting offline-ui-waiting', '1 seconds', '1s'], [1, 'offline-ui offline-ui-up offline-ui-up-5s', '', ''] ]; var nextPhase = function() { var phase; $('.browser iframe').each(function(){ var $offline = $(this).contents().find('.offline-ui'), $content = $offline.find('.offline-ui-content'); phase = parseInt($offline.attr('data-phase'), 10); $offline.get(0).className = phases[phase][1]; $content.attr('data-retry-in', phases[phase][2]); $content.attr('data-retry-in-abbr', phases[phase][3]); phase = (phase + 1) % phases.length; $offline.attr('data-phase', phase); }); setTimeout(function(){ nextPhase(); }, phases[phase][0] * 1000); }; nextPhase(); });
kenlimmj/teleprompter
js/offline/docs/welcome/app.js
JavaScript
mit
3,034
/* SQL Middleware Framework by @jheusala */ /* * Copyright (C) 2011 by Jaakko-Heikki Heusala <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /* for node-lint */ /*global Buffer: false, clearInterval: false, clearTimeout: false, console: false, global: false, module: false, process: false, querystring: false, require: false, setInterval: false, setTimeout: false, util: false, __filename: false, __dirname: false */ /* Create SQL object */ module.exports = function(sql) { /* Returns middleware to assign static key=value setting */ sql.assign = function(key, value) { var sql = this; return function(options, next) { if(key && options) { options[key] = value; } next(); }; }; }; /* EOF */
jheusala/node-sqlmw
lib/middlewares/assign.js
JavaScript
mit
1,785
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.IconButton = exports.iconButtonFactory = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _classnames2 = require('classnames'); var _classnames3 = _interopRequireDefault(_classnames2); var _reactCssThemr = require('react-css-themr'); var _identifiers = require('../identifiers.js'); var _FontIcon = require('../font_icon/FontIcon.js'); var _FontIcon2 = _interopRequireDefault(_FontIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var factory = function factory(FontIcon) { var IconButton = function (_Component) { _inherits(IconButton, _Component); function IconButton() { var _ref; var _temp, _this, _ret; _classCallCheck(this, IconButton); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = IconButton.__proto__ || Object.getPrototypeOf(IconButton)).call.apply(_ref, [this].concat(args))), _this), _this.handleMouseUp = function (event) { var button = _this.refs.button; var onMouseUp = _this.props.onMouseUp; button.blur(); if (onMouseUp) { onMouseUp(event); }; }, _this.handleMouseLeave = function (event) { var button = _this.refs.button; var onMouseLeave = _this.props.onMouseLeave; button.blur(); if (onMouseLeave) { onMouseLeave(event); }; }, _this.render = function () { var _classnames; var _this$props = _this.props; var children = _this$props.children; var className = _this$props.className; var floating = _this$props.floating; var href = _this$props.href; var icon = _this$props.icon; var inverse = _this$props.inverse; var label = _this$props.label; var mini = _this$props.mini; var primary = _this$props.primary; var secondary = _this$props.secondary; var tertiary = _this$props.tertiary; var theme = _this$props.theme; var disabled = _this$props.disabled; var others = _objectWithoutProperties(_this$props, ['children', 'className', 'floating', 'href', 'icon', 'inverse', 'label', 'mini', 'primary', 'secondary', 'tertiary', 'theme', 'disabled']); var element = href ? 'a' : 'button'; var classes = (0, _classnames3.default)(theme.button, (_classnames = {}, _defineProperty(_classnames, theme.floating, floating), _defineProperty(_classnames, theme.tertiary, tertiary && !secondary && !primary), _defineProperty(_classnames, theme.secondary, secondary && !tertiary && !primary), _defineProperty(_classnames, theme.primary, primary && !tertiary && !secondary), _defineProperty(_classnames, theme.mini, mini), _defineProperty(_classnames, theme.inverse, inverse), _classnames), className); var props = _extends({}, others, { href: href, ref: 'button', className: classes, disabled: disabled, onMouseUp: _this.handleMouseUp, onMouseLeave: _this.handleMouseLeave, 'data-react-zvui-framework': 'button' }); return _react2.default.createElement(element, props, icon ? _react2.default.createElement(FontIcon, { className: theme.icon, value: icon }) : null, children); }, _temp), _possibleConstructorReturn(_this, _ret); } return IconButton; }(_react.Component); IconButton.propTypes = { children: _react.PropTypes.node, className: _react.PropTypes.string, disabled: _react.PropTypes.bool, floating: _react.PropTypes.bool, href: _react.PropTypes.string, icon: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.element]), inverse: _react.PropTypes.bool, label: _react.PropTypes.string, mini: _react.PropTypes.bool, onMouseLeave: _react.PropTypes.func, onMouseUp: _react.PropTypes.func, primary: _react.PropTypes.bool, secondary: _react.PropTypes.bool, tertiary: _react.PropTypes.bool, theme: _react.PropTypes.shape({ button: _react.PropTypes.string, floating: _react.PropTypes.string, icon: _react.PropTypes.string, inverse: _react.PropTypes.string, mini: _react.PropTypes.string, primary: _react.PropTypes.string, secondary: _react.PropTypes.string, tertiary: _react.PropTypes.string, toggle: _react.PropTypes.string }), type: _react.PropTypes.string }; IconButton.defaultProps = { className: '', floating: false, mini: false, primary: false, secondary: false, tertiary: true, raised: false }; return IconButton; }; var IconButton = factory(_FontIcon2.default); exports.default = (0, _reactCssThemr.themr)(_identifiers.BUTTON)(IconButton); exports.iconButtonFactory = factory; exports.IconButton = IconButton;
sylvesteraswin/react-zvui-framework
lib/button/IconButton.js
JavaScript
mit
6,659
var express = require('express'); var router = express.Router(); var indexController = require('../controller/project2/indexController.js'); router.get("/project2/index", indexController.gotoIndex); module.exports = router;
midday/gfe-node-build
test/router/project2Router.js
JavaScript
mit
225
/* eslint-env mocha */ "use strict"; var assert = require("chai").assert; var reducer = require("../../src/reducers/transactions"); describe("reducers/transactions", function () { var test = function (t) { it(t.description, function () { t.assertions(reducer(t.state, t.action)); }); }; describe("ADD_TRANSACTION", function () { test({ description: "Add a new transaction, initial state empty", state: {}, action: { type: "ADD_TRANSACTION", transaction: { hash: "0xf00dbeef", payload: { method: "myOtherTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x42", count: 0, status: "pending", }, }, assertions: function (state) { assert.deepEqual(state, { "0xf00dbeef": { hash: "0xf00dbeef", payload: { method: "myOtherTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x42", count: 0, status: "pending", }, }); }, }); test({ description: "Add a new transaction, initial state non-empty", state: { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "myTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x12", count: 0, status: "pending", }, }, action: { type: "ADD_TRANSACTION", transaction: { hash: "0xf00dbeef", payload: { method: "myOtherTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x42", count: 0, status: "pending", }, }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "myTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x12", count: 0, status: "pending", }, "0xf00dbeef": { hash: "0xf00dbeef", payload: { method: "myOtherTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x42", count: 0, status: "pending", }, }); }, }); test({ description: "Overwrite an existing transaction", state: { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "myTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x12", count: 0, status: "pending", }, }, action: { type: "ADD_TRANSACTION", transaction: { hash: "0xdeadbeef", payload: { method: "myOtherTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x42", count: 0, status: "pending", }, }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "myOtherTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x42", count: 0, status: "pending", }, }); }, }); }); describe("UPDATE_ON_CHAIN_TRANSACTION", function () { test({ description: "Update on chain transaction data", state: { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "myTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x12", count: 0, status: "pending", tx: { key0: "value0" }, }, }, action: { type: "UPDATE_ON_CHAIN_TRANSACTION", hash: "0xdeadbeef", data: { key1: "value1" }, }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "myTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x12", count: 0, status: "pending", tx: { key0: "value0", key1: "value1", }, }, }); }, }); }); describe("UPDATE_TRANSACTION", function () { test({ description: "Add a new object field to an existing transaction", state: { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "myTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x12", count: 0, status: "pending", }, }, action: { type: "UPDATE_TRANSACTION", hash: "0xdeadbeef", data: { tx: { key1: "value1" } }, }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "myTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x12", count: 0, status: "pending", tx: { key1: "value1" }, }, }); }, }); test({ description: "Update two different object fields in an existing transaction", state: { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "myTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x12", count: 0, status: "pending", tx: { key1: "value1" }, }, }, action: { type: "UPDATE_TRANSACTION", hash: "0xdeadbeef", data: { payload: { method: "myOtherTransaction" }, tx: { key2: "value2" }, }, }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "myOtherTransaction", from: "0xb0b", to: "0xd00d", }, callReturn: "0x12", count: 0, status: "pending", tx: { key1: "value1", key2: "value2" }, }, }); }, }); }); describe("LOCK_TRANSACTION", function () { test({ description: "Lock a pending transaction", state: { "0xdeadbeef": { hash: "0xdeadbeef", status: "pending", }, }, action: { type: "LOCK_TRANSACTION", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", status: "pending", isLocked: true, }, }); }, }); }); describe("UNLOCK_TRANSACTION", function () { test({ description: "Unlock a pending transaction", state: { "0xdeadbeef": { hash: "0xdeadbeef", status: "pending", isLocked: true, }, }, action: { type: "UNLOCK_TRANSACTION", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", status: "pending", isLocked: false, }, }); }, }); }); describe("SET_TRANSACTION_CONFIRMATIONS", function () { test({ description: "Set confirmations to current block number minus mined block number", state: { "0xdeadbeef": { hash: "0xdeadbeef", tx: { blockNumber: "0x5d" }, }, }, action: { type: "SET_TRANSACTION_CONFIRMATIONS", hash: "0xdeadbeef", currentBlockNumber: "0x64", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", tx: { blockNumber: "0x5d" }, confirmations: 7, }, }); }, }); }); describe("TRANSACTION_PENDING", function () { test({ description: "Set transaction status to 'pending'", state: { "0xdeadbeef": { hash: "0xdeadbeef", status: "sealed", confirmations: 3, }, }, action: { type: "TRANSACTION_PENDING", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", status: "pending", confirmations: 0, }, }); }, }); }); describe("TRANSACTION_FAILED", function () { test({ description: "Set transaction status to 'failed'", state: { "0xdeadbeef": { hash: "0xdeadbeef", status: "sealed", }, }, action: { type: "TRANSACTION_FAILED", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", status: "failed", }, }); }, }); }); describe("TRANSACTION_SEALED", function () { test({ description: "Set transaction status to 'mined'", state: { "0xdeadbeef": { hash: "0xdeadbeef", status: "pending", }, }, action: { type: "TRANSACTION_SEALED", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", status: "sealed", }, }); }, }); }); describe("TRANSACTION_RESUBMITTED", function () { test({ description: "Set transaction status to 'resubmitted'", state: { "0xdeadbeef": { hash: "0xdeadbeef", status: "sealed", }, }, action: { type: "TRANSACTION_RESUBMITTED", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", status: "resubmitted", }, }); }, }); }); describe("TRANSACTION_CONFIRMED", function () { test({ description: "Set transaction status to 'confirmed'", state: { "0xdeadbeef": { hash: "0xdeadbeef", status: "sealed", }, }, action: { type: "TRANSACTION_CONFIRMED", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", status: "confirmed", }, }); }, }); }); describe("INCREMENT_TRANSACTION_COUNT", function () { test({ description: "Increment an existing transaction count", state: { "0xdeadbeef": { hash: "0xdeadbeef", count: 1, }, }, action: { type: "INCREMENT_TRANSACTION_COUNT", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", count: 2, }, }); }, }); test({ description: "Set an undefined transaction count to 1", state: { "0xdeadbeef": { hash: "0xdeadbeef", }, }, action: { type: "INCREMENT_TRANSACTION_COUNT", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", count: 1, }, }); }, }); }); describe("INCREMENT_TRANSACTION_PAYLOAD_TRIES", function () { test({ description: "Increment an existing transaction payload tries counter", state: { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "sayHelloToTheWorld", tries: 2, }, }, }, action: { type: "INCREMENT_TRANSACTION_PAYLOAD_TRIES", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "sayHelloToTheWorld", tries: 3, }, }, }); }, }); test({ description: "Set an transaction payload with undefined tries counter to 1", state: { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "sayHelloToTheWorld", }, }, }, action: { type: "INCREMENT_TRANSACTION_PAYLOAD_TRIES", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", payload: { method: "sayHelloToTheWorld", tries: 1, }, }, }); }, }); test({ description: "Set an empty transaction payload tries counter to 1", state: { "0xdeadbeef": { hash: "0xdeadbeef", payload: {}, }, }, action: { type: "INCREMENT_TRANSACTION_PAYLOAD_TRIES", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", payload: { tries: 1 }, }, }); }, }); test({ description: "Set an undefined transaction payload tries counter to 1", state: { "0xdeadbeef": { hash: "0xdeadbeef", }, }, action: { type: "INCREMENT_TRANSACTION_PAYLOAD_TRIES", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xdeadbeef": { hash: "0xdeadbeef", payload: { tries: 1 }, }, }); }, }); }); describe("REMOVE_TRANSACTION", function () { test({ description: "Remove a transaction", state: { "0xdeadbeef": { hash: "0xdeadbeef", status: "sealed", }, "0xf00dbeef": { hash: "0xf00dbeef", status: "pending", }, }, action: { type: "REMOVE_TRANSACTION", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, { "0xf00dbeef": { hash: "0xf00dbeef", status: "pending", }, }); }, }); test({ description: "Remove the last transaction", state: { "0xdeadbeef": { hash: "0xdeadbeef", status: "sealed", }, }, action: { type: "REMOVE_TRANSACTION", hash: "0xdeadbeef", }, assertions: function (state) { assert.deepEqual(state, {}); }, }); }); describe("REMOVE_ALL_TRANSACTIONS", function () { test({ description: "Remove all transactions (reset state)", state: { "0xdeadbeef": { hash: "0xdeadbeef", status: "sealed", }, "0xf00dbeef": { hash: "0xf00dbeef", status: "pending", }, }, action: { type: "REMOVE_ALL_TRANSACTIONS", }, assertions: function (state) { assert.deepEqual(state, {}); }, }); }); });
ethereumjs/ethrpc
test/reducers/transactions.js
JavaScript
mit
16,127
define(function () { return function (ParsleyUI) { describe('ParsleyUI', function () { it('should be a function', function () { expect(ParsleyUI).to.be.a('function'); }); it('should have a listen() method', function () { var UI = new ParsleyUI(); expect(UI.listen).not.to.be(undefined); }); it('should create proper errors container', function () { $('body').append('<input type="text" id="element" data-parsley-required />'); var parsleyField = $('#element').psly(); expect($('#element').attr('data-parsley-id')).to.be(parsleyField.__id__); expect($('ul#parsley-id-' + parsleyField.__id__).length).to.be(1); expect($('ul#parsley-id-' + parsleyField.__id__).hasClass('parsley-errors-list')).to.be(true); }); it('should handle errors-container option', function () { $('body').append( '<form id="element">' + '<input id="field1" type="text" required data-parsley-errors-container="#container" />' + '<div id="container"></div>' + '<div id="container2"></div>' + '</form>'); $('#element').psly(); expect($('#container .parsley-errors-list').length).to.be(1); $('#element').psly().destroy(); $('#field1').removeAttr('data-parsley-errors-container'); $('#element').psly({ errorsContainer: function () { return $('#container2'); } }).validate(); expect($('#container2 .parsley-errors-list').length).to.be(1); }); it('should handle wrong errors-container option', function () { $('body').append('<input type="text" id="element" data-parsley-errors-container="#donotexist" />'); window.console.warn = sinon.spy(); var parsleyInstance = $('#element').psly(); expect(window.console.warn.called).to.be(true); }); it('should add proper parsley class on success or failure (type=text)', function () { $('body').append('<input type="text" id="element" required />'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('#element').hasClass('parsley-error')).to.be(true); expect($('#element').hasClass('parsley-success')).to.be(false); $('#element').val('foo').psly().validate(); expect($('#element').hasClass('parsley-success')).to.be(true); expect($('#element').hasClass('parsley-error')).to.be(false); }); it('should add proper parsley class on success or failure (type=radio)', function () { $('body').append('<input type="radio" id="element" required />'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('#element').parent().hasClass('parsley-error')).to.be(true); expect($('#element').parent().hasClass('parsley-success')).to.be(false); $('#element').attr('checked', 'checked').psly().validate(); expect($('#element').parent().hasClass('parsley-success')).to.be(true); expect($('#element').parent().hasClass('parsley-error')).to.be(false); }); it('should add proper parsley class on success or failure (input=checkbox)', function () { $('body').append('<input type="checkbox" id="element" required />'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('#element').parent().hasClass('parsley-error')).to.be(true); expect($('#element').parent().hasClass('parsley-success')).to.be(false); $('#element').attr('checked', 'checked').psly().validate(); expect($('#element').parent().hasClass('parsley-success')).to.be(true); expect($('#element').parent().hasClass('parsley-error')).to.be(false); }); it('should add proper parsley class on success or failure (select multiple)', function () { $('body').append('<select multiple id="element" required><option value="foo">foo</option></select>'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('#element').hasClass('parsley-error')).to.be(true); expect($('#element').hasClass('parsley-success')).to.be(false); $('#element option[value="foo"]').attr('selected', 'selected'); parsleyField.validate(); expect($('#element').hasClass('parsley-success')).to.be(true); expect($('#element').hasClass('parsley-error')).to.be(false); }); it('should handle class-handler option', function () { $('body').append( '<form id="element">' + '<input id="field1" type="email" data-parsley-class-handler="#field2" required />' + '<div id="field2"></div>' + '<div id="field3"></div>' + '</form>'); $('#element').psly().validate(); expect($('#field2').hasClass('parsley-error')).to.be(true); $('#element').psly().destroy(); $('#field1').removeAttr('data-parsley-class-handler'); $('#element').psly({ classHandler: function () { return $('#field3'); } }).validate(); expect($('#field3').hasClass('parsley-error')).to.be(true); }); it('should show higher priority error message by default', function () { $('body').append('<input type="email" id="element" required />'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('#element').hasClass('parsley-error')).to.be(true); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-required')).to.be(true); $('#element').val('foo').psly().validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-type')).to.be(true); }); it('should show all errors message if priority enabled set to false', function () { $('body').append('<input type="email" id="element" required data-parsley-priority-enabled="false"/>'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(2); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').eq(0).hasClass('parsley-required')).to.be(true); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').eq(1).hasClass('parsley-type')).to.be(true); $('#element').val('foo').psly().validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-type')).to.be(true); }); it('should show custom error message by validator', function () { $('body').append('<input type="email" id="element" required data-parsley-required-message="foo" data-parsley-type-message="bar"/>'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('foo'); $('#element').val('foo').psly().validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('bar'); }); it('should show custom error message with variabilized parameters', function () { $('body').append('<input type="text" id="element" value="bar" data-parsley-minlength="7" data-parsley-minlength-message="foo %s bar"/>'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('foo 7 bar'); }); it('should show custom error message for whole field', function () { $('body').append('<input type="email" id="element" required data-parsley-error-message="baz"/>'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('baz'); $('#element').val('foo').psly().validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('baz'); $('#element').val('[email protected]').psly().validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); }); it('should display no error message if diabled', function () { $('body').append('<input type="email" id="element" required data-parsley-errors-messages-disabled />'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); expect($('#element').hasClass('parsley-error')).to.be(true); }); it('should handle simple triggers (change, focus..)', function () { $('body').append('<input type="email" id="element" required data-parsley-trigger="change" />'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); $('#element').trigger($.Event('change')); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); }); it('should auto bind error trigger on selet field error (input=text)', function () { $('body').append('<input type="email" id="element" required />'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-required')).to.be(true); $('#element').val('foo').trigger($.Event('keyup')); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-type')).to.be(true); }); it('should auto bind error trigger on selet field error (select)', function () { $('body').append('<select id="element" required>'+ '<option value="">Choose</option>' + '<option value="foo">foo</option>' + '<option value="bar">bar</option>' + '</select>'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-required')).to.be(true); $('#element [option="foo"]').attr('selected', 'selected'); $('#element').trigger($.Event('change')); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-type')).to.be(false); }); it('should handle complex triggers (keyup, keypress..)', function () { $('body').append('<input type="email" id="element" required data-parsley-trigger="keyup" />'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); $('#element').val('foo').trigger($.Event('keyup')); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); $('#element').val('foob').trigger($.Event('keyup')); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); }); it('should handle trigger keyup threshold validation', function () { $('body').append('<input type="email" id="element" data-parsley-validation-threshold="2" required data-parsley-trigger="keyup" />'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); $('#element').val('fo').trigger($.Event('keyup')); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); $('#element').val('foo').trigger($.Event('keyup')); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); }); it('should handle UI disabling', function () { $('body').append('<input type="email" id="element" data-parsley-ui-enabled="false" required data-parsley-trigger="keyup" />'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__).length).to.be(0); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__).length).to.be(0); }); it('should add novalidate on form elem', function () { $('body').append( '<form id="element" data-parsley-trigger="change">' + '<input id="field1" type="text" data-parsley-required="true" />' + '<div id="field2"></div>' + '<textarea id="field3" data-parsley-notblank="true"></textarea>' + '</form>'); var parsleyForm = new Parsley($('#element')); expect($('#element').attr('novalidate')).not.to.be(undefined); }); it('should test the no-focus option', function () { $('body').append( '<form id="element" data-parsley-focus="first">' + '<input id="field1" type="text" data-parsley-required="true" data-parsley-no-focus />' + '<input id="field2" data-parsley-required />' + '</form>'); $('#element').parsley().validate(); expect($('#element').parsley()._focusedField.attr('id')).to.be('field2'); $('#field2').val('foo'); $('#element').psly().validate(); expect($('#element').parsley()._focusedField).to.be(null); $('#field1').removeAttr('data-parsley-no-focus'); $('#element').psly().validate(); expect($('#element').parsley()._focusedField.attr('id')).to.be('field1'); $('#element').attr('data-parsley-focus', 'last'); $('#element').psly().validate(); expect($('#element').parsley()._focusedField.attr('id')).to.be('field1'); $('#field2').val(''); $('#element').psly().validate(); expect($('#element').parsley()._focusedField.attr('id')).to.be('field2'); }); it('should test the manual add / update / remove error', function () { $('body').append('<input type="text" id="element" />'); var parsleyField = $('#element').parsley(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); expect($('#element').hasClass('parsley-error')).to.be(false); window.ParsleyUI.addError(parsleyField, 'foo', 'bar'); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); expect($('#element').hasClass('parsley-error')).to.be(true); expect($('li.parsley-foo').length).to.be(1); expect($('li.parsley-foo').text()).to.be('bar'); window.ParsleyUI.updateError(parsleyField, 'foo', 'baz'); expect($('li.parsley-foo').text()).to.be('baz'); window.ParsleyUI.removeError(parsleyField, 'foo'); expect($('#element').hasClass('parsley-error')).to.be(false); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); }); afterEach(function () { if ($('#element').length) $('#element').remove(); if ($('.parsley-errors-list').length) $('.parsley-errors-list').remove(); }); }); }; });
codal/Parsley.js
test/features/ui.js
JavaScript
mit
15,927
// @flow import React from 'react' import ReactDom from 'react-dom' import { BrowserRouter } from 'react-router-dom' import { REACT_ROOT_ID } from '../../contstants' import App from '../../components/App' import '../css/core.scss' const Router = () => ( <BrowserRouter> <App store={window.store} /> </BrowserRouter> ) ReactDom.render(React.createElement(Router), document.querySelector(`#${REACT_ROOT_ID}`))
GeekyAubergine/chrisaubert.me
src/public/js/app.js
JavaScript
mit
416
function roll(initialText,tokens) { if(tokens.length != 1 || (tokens[0] != 'left'&& tokens[0] != 'right')){ console.log('Error: invalid command parameters') return; } let wordsArr = initialText.split(' '); if(tokens[0] == 'left'){ let firstWord = wordsArr.shift(); wordsArr.push(firstWord); } if(tokens[0] == 'right'){ let lastWord = wordsArr[wordsArr.length-1]; wordsArr.splice(0,0,lastWord); wordsArr.splice(wordsArr.length-1,1); } return wordsArr.join(' '); } module.exports = {roll}
JSTeamwork-Command-Parser/Command-Parser
js/roll.js
JavaScript
mit
570
'use strict'; var winston = require('winston'); var _ = require('lodash'); var json = require('circular-json'); var path = require('path'); var fs = require('fs-extra'); var moment = require('moment'); var config = require('../../../config/app-config'); var logDir = path.join(config.PERSISTENT_DATA_DIR, config.LOG_DIR_NAME); fs.ensureDir(logDir, function(err) { logger.debug(err); }); winston.addColors({ debug: 'cyan' // Override dark blue by sky blue of cyan. }); var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ timestamp: function() { return moment().format('HH:mm:ss.SSS'); }, level: 'debug', colorize: 'true' }), new (winston.transports.DailyRotateFile)({ filename: logDir + '/' + config.LOG_FILE_NAME, datePattern: '.yyyy-MM-dd', level: 'debug', json: false }) ] }); module.exports = function(module) { var loggerName = path.basename(module); function buildMsg(args) { var msg = '[' + loggerName + ']'; for (var i = 0; i < args.length; i++) { var arg = args[i]; if (_.isObject(arg)) { arg = JSON.stringify(arg, null, 2); } msg = msg + ' ' + arg; } return msg; } function buildLogger(loggerFunc) { return function() { loggerFunc(buildMsg(arguments)); }; } return { debug: buildLogger(logger.debug), info: buildLogger(logger.info), warn: buildLogger(logger.warn), error: buildLogger(logger.error) } };
siman/meetua
app/controllers/util/logger.js
JavaScript
mit
1,525
// @flow /* eslint-disable no-magic-numbers */ import type {TData, TCommand} from './types' const ERROR_MAX_STRING_LENGTH = 15 const error = (msg: string, string: string, i: number) => { const textBefore = string.substr(0, i) const char = string.charAt(i) const textAfter = (string.length - i) > ERROR_MAX_STRING_LENGTH ? string.substr(i + 1, ERROR_MAX_STRING_LENGTH) + '...' : string.substr(i + 1) return Error(`${msg}; context (${i}): ${textBefore}[${char}]${textAfter} `) } const makeNumber = (numberString: string, string, i): number => { //todo: check format const result = Number(numberString) if (Number.isNaN(result)) { throw error(`Bad number format: "${numberString}"`, string, i) } return result } const parseArguments = (string, i): [number[], number] => { const result = [] let nextI = i let number = '' while (nextI < string.length) { const char = string[nextI] //todo: parse \n too if (/\s/.test(char) || char === ',') { if (number !== '') { result.push(makeNumber(number, string, nextI)) number = '' } } // todo: ged rid of regexp else if (/\d/.test(char)) { number += char } else if (char === '-') { if (number === '-') { throw error('Minus symbol in an unexpected place', string, nextI) } else if (number !== '') { result.push(makeNumber(number, string, nextI)) number = '-' } else { number += char } } else if (char === '.') { number += char } else { break } nextI++ } if (number !== '') { result.push(makeNumber(number, string, nextI)) } return [result, nextI] } const parseArgumentsGeneral = (string: string, i: number, perCommand: number): [number[][], number] => { const [args, nextI] = parseArguments(string, i) if (perCommand === 0) { if (args.length !== 0) { throw error(`Wrong parameters count (${args.length}), should be ${perCommand} per command`, string, i) } } else { if (args.length === 0) { throw error(`Wrong parameters count (${args.length}), should be ${perCommand} per command`, string, i) } if (args.length % perCommand !== 0) { throw error(`Wrong parameters count (${args.length}), should be ${perCommand} per command`, string, i) } } const argGroups: number[][] = [] for (let i = 0; i < args.length; i += perCommand) { const group = [] for (let j = 0; j < perCommand; j++) { group.push(args[i + j]) } argGroups.push(group) } return [argGroups, nextI] } const parseMove = (string, i, relative = false): [TCommand[], number] => { const [argGroups, nextI] = parseArgumentsGeneral(string, i, 2) const commands: TCommand[] = [] for (let i = 0; i < argGroups.length; ++i) { if (relative) { commands.push({c: 'm', dx: argGroups[i][0], dy: argGroups[i][1]}) } else { commands.push({c: 'M', x: argGroups[i][0], y: argGroups[i][1]}) } } return [commands, nextI] } const parseClose = (string, i, relative = false): [TCommand[], number] => { const [_, nextI] = parseArgumentsGeneral(string, i, 0) return [[relative ? {c: 'z'} : {c: 'Z'}], nextI] } const parseLine = (string, i, relative = false): [TCommand[], number] => { const [argGroups, nextI] = parseArgumentsGeneral(string, i, 2) const commands: TCommand[] = [] for (let i = 0; i < argGroups.length; ++i) { if (relative) { commands.push({c: 'l', dx: argGroups[i][0], dy: argGroups[i][1]}) } else { commands.push({c: 'L', x: argGroups[i][0], y: argGroups[i][1]}) } } return [commands, nextI] } const parseHorizontal = (string, i, relative = false): [TCommand[], number] => { const [argGroups, nextI] = parseArgumentsGeneral(string, i, 1) const commands: TCommand[] = [] for (let i = 0; i < argGroups.length; ++i) { if (relative) { commands.push({c: 'h', dx: argGroups[i][0]}) } else { commands.push({c: 'H', x: argGroups[i][0]}) } } return [commands, nextI] } const parseVertical = (string, i, relative = false): [TCommand[], number] => { const [argGroups, nextI] = parseArgumentsGeneral(string, i, 1) const commands: TCommand[] = [] for (let i = 0; i < argGroups.length; ++i) { if (relative) { commands.push({c: 'v', dy: argGroups[i][0]}) } else { commands.push({c: 'V', y: argGroups[i][0]}) } } return [commands, nextI] } const parseCurve = (string, i, relative = false): [TCommand[], number] => { const [argGroups, nextI] = parseArgumentsGeneral(string, i, 6) const commands: TCommand[] = [] for (let i = 0; i < argGroups.length; ++i) { if (relative) { commands.push({ c: 'c', dx1: argGroups[i][0], dy1: argGroups[i][1], dx2: argGroups[i][2], dy2: argGroups[i][3], dx: argGroups[i][4], dy: argGroups[i][5], }) } else { commands.push({ c: 'C', x1: argGroups[i][0], y1: argGroups[i][1], x2: argGroups[i][2], y2: argGroups[i][3], x: argGroups[i][4], y: argGroups[i][5], }) } } return [commands, nextI] } const parseShortCurve = (string, i, relative = false): [TCommand[], number] => { const [argGroups, nextI] = parseArgumentsGeneral(string, i, 4) const commands: TCommand[] = [] for (let i = 0; i < argGroups.length; ++i) { if (relative) { commands.push({ c: 's', dx2: argGroups[i][0], dy2: argGroups[i][1], dx: argGroups[i][2], dy: argGroups[i][3], }) } else { commands.push({ c: 'S', x2: argGroups[i][0], y2: argGroups[i][1], x: argGroups[i][2], y: argGroups[i][3], }) } } return [commands, nextI] } const parseQuadCurve = (string, i, relative = false): [TCommand[], number] => { const [argGroups, nextI] = parseArgumentsGeneral(string, i, 4) const commands: TCommand[] = [] for (let i = 0; i < argGroups.length; ++i) { if (relative) { commands.push({ c: 'q', dx1: argGroups[i][0], dy1: argGroups[i][1], dx: argGroups[i][2], dy: argGroups[i][3], }) } else { commands.push({ c: 'Q', x1: argGroups[i][0], y1: argGroups[i][1], x: argGroups[i][2], y: argGroups[i][3], }) } } return [commands, nextI] } const parseShortQuadCurve = (string, i, relative = false): [TCommand[], number] => { const [argGroups, nextI] = parseArgumentsGeneral(string, i, 2) const commands: TCommand[] = [] for (let i = 0; i < argGroups.length; ++i) { if (relative) { commands.push({ c: 't', dx: argGroups[i][0], dy: argGroups[i][1], }) } else { commands.push({ c: 'T', x: argGroups[i][0], y: argGroups[i][1], }) } } return [commands, nextI] } const parseArc = (string, i, relative = false): [TCommand[], number] => { const [argGroups, nextI] = parseArgumentsGeneral(string, i, 7) const commands: TCommand[] = [] for (let i = 0; i < argGroups.length; ++i) { if (relative) { commands.push({ c: 'a', rx: argGroups[i][0], ry: argGroups[i][1], xAxisRotation: argGroups[i][2], largeArcFlag: argGroups[i][3], sweepFlag: argGroups[i][4], dx: argGroups[i][5], dy: argGroups[i][6], }) } else { commands.push({ c: 'A', rx: argGroups[i][0], ry: argGroups[i][1], xAxisRotation: argGroups[i][2], largeArcFlag: argGroups[i][3], sweepFlag: argGroups[i][4], x: argGroups[i][5], y: argGroups[i][6], }) } } return [commands, nextI] } export const parseNextCommand = (string: string, i: number) => { const ch = string[i] const commandStartI = i + 1 switch (ch) { case 'M': return parseMove(string, commandStartI) case 'm': return parseMove(string, commandStartI, true) case 'Z': return parseClose(string, commandStartI) case 'z': return parseClose(string, commandStartI, true) case 'L': return parseLine(string, commandStartI) case 'l': return parseLine(string, commandStartI, true) case 'H': return parseHorizontal(string, commandStartI) case 'h': return parseHorizontal(string, commandStartI, true) case 'V': return parseVertical(string, commandStartI) case 'v': return parseVertical(string, commandStartI, true) case 'C': return parseCurve(string, commandStartI) case 'c': return parseCurve(string, commandStartI, true) case 'S': return parseShortCurve(string, commandStartI) case 's': return parseShortCurve(string, commandStartI, true) case 'Q': return parseQuadCurve(string, commandStartI) case 'q': return parseQuadCurve(string, commandStartI, true) case 'T': return parseShortQuadCurve(string, commandStartI) case 't': return parseShortQuadCurve(string, commandStartI, true) case 'A': return parseArc(string, commandStartI) case 'a': return parseArc(string, commandStartI, true) default: throw error(`Unknown c: ${ch}`, string, i) } } export const parse = (string: string): TData => { const result = [] let i = 0 while (i < string.length) { const [commands, nextI] = parseNextCommand(string, i) result.push(...commands) i = nextI } return result }
koluch/svg-path-round-corners
src/parse.js
JavaScript
mit
10,755
var React = require('react'); var appendVendorPrefix = require('react-kit/appendVendorPrefix'); var CrossIcon = React.createClass({ getCrossStyle(type) { return appendVendorPrefix({ position: 'absolute', width: 3, height: 14, top: 14, right: 18, cursor: 'pointer', transform: type === 'before' ? 'rotate(45deg)' : 'rotate(-45deg)', zIndex: 1 }); }, render() { var buttonStyle = appendVendorPrefix({ width: 14, height: 14, position: 'absolute', right: 13, top: 14, padding: 0, overflow: 'hidden', textIndent: 14, fontSize: 14, border: 'none', background: 'transparent', color: 'transparent', outline: 'none', zIndex: 1 }); return ( <div> <span className="bm-cross" style={ this.getCrossStyle('before') }></span> <span className="bm-cross" style={ this.getCrossStyle('after') }></span> <button onClick={ this.props.onClick } style={ buttonStyle }>Close Menu</button> </div> ); } }); export default CrossIcon;
sylphdesign/react-menu-clone
src/CrossIcon.js
JavaScript
mit
1,112
[ {title: 'noodle 1', description: 'noodle test 1', category: 'cat1', price: 100}, {title: 'noodle 2', description: 'noodle test 2', category: 'cat1', price: 200}, {title: 'noodle 3', description: 'noodle test 3', category: 'cat2', price: 300}, {title: 'noodle 4', description: 'noodle test 4', category: 'cat2', price: 400} ]
glxcc/bar
packages/pub/public/services/json.js
JavaScript
mit
342
var expect = require('chai').expect; var _ = require('lodash'); var tu = require('../TestUtils'); var ChessBoardRepresentation = require('../../app/ChessBoard/ChessBoardRepresentation'); var ChessPiecesFactory = require('../../app/ChessPiecesFactory'); var ChessSet = require('../../app/ChessSet'); describe('Rook', function() { it('should move on board', function() { var board = new ChessBoardRepresentation(); var rook = new ChessPiecesFactory.Rook(ChessSet.white); var pawn = new ChessPiecesFactory.Pawn(ChessSet.white); board.select(0, 0).occupyBy(rook); board.select(0, 5).occupyBy(pawn); var possibleMoves = rook.generateAllPossibleMoves(); expect(possibleMoves.length).to.be.equal(11); var expectedMoves = [ tu.makeMove(1, 0), tu.makeMove(2, 0), tu.makeMove(3, 0), tu.makeMove(4, 0), tu.makeMove(5, 0), tu.makeMove(6, 0), tu.makeMove(7, 0), tu.makeMove(0, 1), tu.makeMove(0, 2), tu.makeMove(0, 3), tu.makeMove(0, 4) ]; expect(tu.checkMoves(possibleMoves, expectedMoves)).to.be.true; }); it('should allow to beat enemy', function() { var board = new ChessBoardRepresentation(); var rook = new ChessPiecesFactory.Rook(ChessSet.white); var pawn1 = new ChessPiecesFactory.Pawn(ChessSet.black); var pawn2 = new ChessPiecesFactory.Pawn(ChessSet.black); board.select(0, 0).occupyBy(rook); board.select(0, 1).occupyBy(pawn1); board.select(1, 0).occupyBy(pawn2); var possibleMoves = rook.generateAllPossibleMoves(); expect(possibleMoves.length).to.be.equal(2); var expectedMoves = [ tu.makeMove(1, 0), tu.makeMove(0, 1) ]; expect(tu.checkMoves(possibleMoves, expectedMoves)).to.be.true; }) });
krzkaczor/Chess.ai.js
test/ChessPieces/Rook.spec.js
JavaScript
mit
1,780
/** * @file Attributes validation helpers * @since 0.2.8 */ /*#ifndef(UMD)*/ "use strict"; /*global _GPF_DEFINE_CLASS_ATTRIBUTES_NAME*/ // $attributes /*global _gpfArrayTail*/ // [].slice.call(,1) /*global _gpfErrorDeclare*/ // Declare new gpf.Error names /*exported _gpfAttributesCheckAppliedOnBaseClass*/ // Ensures attribute is applied on a specific base class /*exported _gpfAttributesCheckAppliedOnlyOnce*/ // Ensures attribute is used only once /*exported _gpfAttributesCheckClassOnly*/ // Ensures attribute is used only at class level /*exported _gpfAttributesCheckMemberOnly*/ // Ensures attribute is used only at member level /*#endif*/ _gpfErrorDeclare("attributes/check", { /** * ### Summary * * Class attribute only * * ### Description * * A class attribute can't be assigned to a member * @since 0.2.8 */ classAttributeOnly: "Class attribute only", /** * ### Summary * * Member attribute only * * ### Description * * A member attribute can't be assigned to a class * @since 0.2.8 */ memberAttributeOnly: "Member attribute only", /** * ### Summary * * Restricted base class attribute * * ### Description * * The attribute is restricted to a given base class, check the attribute documentation. * @since 0.2.8 */ restrictedBaseClassAttribute: "Restricted base class attribute", /** * ### Summary * * Unique attribute used twice * * ### Description * * The attribute is restricted to a single use * @since 0.2.8 */ uniqueAttributeUsedTwice: "Unique attribute used twice" }); /** * Ensures attribute is used only at class level * * @param {String} member Member name or empty if global to the class * @throws {gpf.Error.ClassAttributeOnly} * @since 0.2.8 */ function _gpfAttributesCheckClassOnly (member) { if (member) { gpf.Error.classAttributeOnly(); } } /** * Ensures attribute is used only at member level * * @param {String} member Member name or empty if global to the class * @throws {gpf.Error.MemberAttributeOnly} * @since 0.2.8 */ function _gpfAttributesCheckMemberOnly (member) { if (!member) { gpf.Error.memberAttributeOnly(); } } function _gpfAttributesCheckAppliedOnBaseClassIsInstanceOf (prototype, ExpectedBaseClass) { if (!(prototype instanceof ExpectedBaseClass)) { gpf.Error.restrictedBaseClassAttribute(); } } /** * Ensures attribute is applied on a specific base class * * @param {_GpfClassDefinition} classDefinition Class definition * @param {Function} ExpectedBaseClass Expected base class * @throws {gpf.Error.RestrictedBaseClassAttribute} * @since 0.2.8 */ function _gpfAttributesCheckAppliedOnBaseClass (classDefinition, ExpectedBaseClass) { var Extend = classDefinition._extend; if (Extend !== ExpectedBaseClass) { _gpfAttributesCheckAppliedOnBaseClassIsInstanceOf(Extend.prototype, ExpectedBaseClass); } } function _gpfAttributesCheckGetMemberAttributes (member, classDefinition, AttributeClass) { var allAttributes = classDefinition.getAttributes(AttributeClass); if (member) { return allAttributes[member]; } return allAttributes[_GPF_DEFINE_CLASS_ATTRIBUTES_NAME]; } /** * Ensures attribute is used only once * * @param {String} member Member name or empty if global to the class * @param {_GpfClassDefinition} classDefinition Class definition * @param {Function} AttributeClass Attribute class * @throws {gpf.Error.UniqueAttributeUsedTwice} * @since 0.2.8 */ function _gpfAttributesCheckAppliedOnlyOnce (member, classDefinition, AttributeClass) { var attributes = _gpfAttributesCheckGetMemberAttributes(member, classDefinition, AttributeClass); if (_gpfArrayTail(attributes).length) { gpf.Error.uniqueAttributeUsedTwice(); } }
ArnaudBuchholz/gpf-js
src/attributes/check.js
JavaScript
mit
3,917
/* * Gets data from address bar using Iron-Router * Sets the session according this data. */ Router.configure({ layoutTemplate: 'dummy' }); Router.route('/:_id', { data: function () { var courses; var option = Router.current().params._id; Meteor.subscribe("cities", function(){ $(".loading-screen").fadeOut(function(){ $(this).remove(); Meteor.subscribe("answers"); Session.setDefault("strength-t",100); Session.setDefault("strength-p",100); Session.setDefault("strength-s",100); Session.setDefault("strength-h",100); Session.setDefault("option",option); Session.setDefault("qnumber",0); Session.setDefault("slider1",100); Session.setDefault("slider2",100); Session.setDefault("gold1",100); Session.setDefault("gold2",100); Session.setDefault("gold3",100); Session.setDefault("gold4",100); Session.setDefault("actions_sw",0); Session.setDefault("actions_ss",0); Session.setDefault("actions_st",0); Session.setDefault("actions_sa",0); Session.setDefault("actions_cw",0); Session.setDefault("actions_cs",0); Session.setDefault("actions_ct",0); Session.setDefault("actions_ca",0); Session.setDefault("ssid",Meteor.default_connection._lastSessionId); a = [1,2,3]; b = [4,5,6,7,8,9,10,11,12]; b = shuffle(b); c = Array.prototype.concat.apply([], [a, b]); Session.setDefault("order",c); var isChrome = !!window.chrome && !!window.chrome.webstore; if(isChrome) { Blaze.render(Template.welcome,$(".welcome-screen")[0]); if(option == "map") Blaze.render(Template.map,$("body")[0]); if(option == "chart") Blaze.render(Template.regression,$("body")[0]); if(option == "dots") Blaze.render(Template.dots,$("body")[0]); } else { $(".welcome-screen").text("This evaluation is only available in Google Chrome. 1.0 - 48 or above."); } jQuery(document).ready(function($) { if (window.history && window.history.pushState) { $(window).on('popstate', function() { var hashLocation = location.hash; var hashSplit = hashLocation.split("#!/"); var hashName = hashSplit[1]; if (hashName !== '') { var hash = window.location.hash; if (hash === '') { alert('Warning, if you press back button, you will lose your progress...'); } } }); window.history.pushState('forward', null, './'+option); } }); }); }); } }); function shuffle(array) { var tmp, current, top = array.length; if(top) while(--top) { current = Math.floor(Math.random() * (top + 1)); tmp = array[current]; array[current] = array[top]; array[top] = tmp; } return array; }
FranciscoGutierrez/LifeQualityViz
client/routes.js
JavaScript
mit
3,001
it("slot description apply for, init true", function (done) { // [inject] init expect(wrap.getElementsByTagName('p').length).toBe(2); expect(wrap.getElementsByTagName('p')[0].innerHTML).toBe('MVVM component framework'); expect(wrap.getElementsByTagName('p')[1].innerHTML).toBe('MVVM component framework'); expect(wrap.getElementsByTagName('b')[0].innerHTML).toBe('San'); myComponent.data.set('folderHidden', true); san.nextTick(function () { expect(wrap.getElementsByTagName('p').length).toBe(0); expect(wrap.getElementsByTagName('b')[0].innerHTML).toBe('San'); myComponent.dispose(); document.body.removeChild(wrap); done(); }); });
ecomfe/san
test/ssr/slot-desc-for-true/spec.js
JavaScript
mit
710
"use strict"; var cheerio = require('cheerio'); var request = require('request'); var _ = require('lodash'); var async = require('async'); var danhngon_1 = require("./danhngon"); var fs = require("fs"); var siteUrl = "http://khotangdanhngon.com/page/"; var listDanhNgon = []; function getPage(pageIndex, callback) { request(siteUrl + pageIndex, function (error, response, body) { var pageQueue = async.queue(getDanhNgon, 5); pageQueue.drain = function () { console.log("Finish page" + pageIndex); callback(); }; var $ = cheerio.load(body); var listitem = $(".entry-content"); _.each(listitem, function (item) { var url = $(item).find("a").attr("href"); pageQueue.push(url); return; }); }); } function getDanhNgon(url, callback) { request(url, function (error, response, body) { if (!error && response.statusCode === 200) { var $ = cheerio.load(body); var danhngon = new danhngon_1.DanhNgon(); danhngon.url = url.replace('http://khotangdanhngon.com/', ''); danhngon.noidung = $('.entry-content > p > span').first().text(); danhngon.tacgia = $('.entry-author > a').first().text(); danhngon.phanloai = $('.posts-same-term > span >a ').first().text(); listDanhNgon.push(danhngon); console.log("Them danh ngon"); } else { console.log("Khong time thay bai viet " + url); } callback(); }); } var queues = async.queue(function (task, callback) { getPage(task, callback); }, 4); queues.drain = function () { console.log("Every thing done"); fs.writeFile('./danhngon.txt', JSON.stringify({ name: "danh ngon", content: listDanhNgon }), 'utf8'); }; for (var i = 1; i < 218; i++) { queues.push(i); }
windwp/myexp
nodewrapper/lib/index.js
JavaScript
mit
1,903
import CmdUtil from './CmdUtil.js' import DynamicCmdPage from '@/components/common/data/DynamicCmdPage' export default { name: 'GCCmdResult', components: { DynamicCmdPage }, functional: true, props: [ 'cmdExecMethod', 'cmdInfo', 'execResult', 'resultType', 'currParams', 'refreshCmd', 'controlledDatas', 'ctrlDatasIgnoreCase', 'cardStyle' ], data () { return { currTab: null } }, render: (h, ctx) => { let renderItem = CmdUtil.renderResult( h, ctx.props.cmdExecMethod, ctx.props.cmdInfo, ctx.props.execResult, ctx.props.resultType, ctx.props.currParams, ctx.props.refreshCmd, ctx, ctx.props.controlledDatas, ctx.props.ctrlDatasIgnoreCase, ctx.props.cardStyle ) if (Array.isArray(renderItem)) { let divideHeight let divideWidth if (renderItem.length > 3) { divideWidth = 50 divideHeight = 100 / Math.floor(renderItem.length / 2) } else { divideHeight = 100 / renderItem.length divideWidth = 100 } // , maxHeight: divideHeight + '%' renderItem = renderItem.map(item => h('div', { style: { float: 'left', width: divideWidth + '%', height: divideHeight + '%', paddingTop: '2px' } }, [item])) return [renderItem] } else { return renderItem } } }
Esilen/GCBatch
gc-web-admin/src/components/common/GCCmdResult.js
JavaScript
mit
1,296
/*! * # Semantic UI - Dimmer * http://github.com/semantic-org/semantic-ui/ * * * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { 'use strict'; window = (typeof window != 'undefined' && window.Math == Math) ? window : (typeof self != 'undefined' && self.Math == Math) ? self : Function('return this')() ; $.fn.dimmer = function(parameters) { var $allModules = $(this), time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.dimmer.settings, parameters) : $.extend({}, $.fn.dimmer.settings), selector = settings.selector, namespace = settings.namespace, className = settings.className, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, moduleSelector = $allModules.selector || '', clickEvent = ('ontouchstart' in document.documentElement) ? 'touchstart' : 'click', $module = $(this), $dimmer, $dimmable, element = this, instance = $module.data(moduleNamespace), module ; module = { preinitialize: function() { if( module.is.dimmer() ) { $dimmable = $module.parent(); $dimmer = $module; } else { $dimmable = $module; if( module.has.dimmer() ) { if(settings.dimmerName) { $dimmer = $dimmable.find(selector.dimmer).filter('.' + settings.dimmerName); } else { $dimmer = $dimmable.find(selector.dimmer); } } else { $dimmer = module.create(); } module.set.variation(); } }, initialize: function() { module.debug('Initializing dimmer', settings); module.bind.events(); module.set.dimmable(); module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, instance) ; }, destroy: function() { module.verbose('Destroying previous module', $dimmer); module.unbind.events(); module.remove.variation(); $dimmable .off(eventNamespace) ; }, bind: { events: function() { if(module.is.page()) { // touch events default to passive, due to changes in chrome to optimize mobile perf $dimmable.get(0).addEventListener('touchmove', module.event.preventScroll, { passive: false }); } if(settings.on == 'hover') { $dimmable .on('mouseenter' + eventNamespace, module.show) .on('mouseleave' + eventNamespace, module.hide) ; } else if(settings.on == 'click') { $dimmable .on(clickEvent + eventNamespace, module.toggle) ; } if( module.is.page() ) { module.debug('Setting as a page dimmer', $dimmable); module.set.pageDimmer(); } if( module.is.closable() ) { module.verbose('Adding dimmer close event', $dimmer); $dimmable .on(clickEvent + eventNamespace, selector.dimmer, module.event.click) ; } } }, unbind: { events: function() { if(module.is.page()) { $dimmable.get(0).removeEventListener('touchmove', module.event.preventScroll, { passive: false }); } $module .removeData(moduleNamespace) ; $dimmable .off(eventNamespace) ; } }, event: { click: function(event) { module.verbose('Determining if event occured on dimmer', event); if( $dimmer.find(event.target).length === 0 || $(event.target).is(selector.content) ) { module.hide(); event.stopImmediatePropagation(); } }, preventScroll: function(event) { event.preventDefault(); } }, addContent: function(element) { var $content = $(element) ; module.debug('Add content to dimmer', $content); if($content.parent()[0] !== $dimmer[0]) { $content.detach().appendTo($dimmer); } }, create: function() { var $element = $( settings.template.dimmer() ) ; if(settings.dimmerName) { module.debug('Creating named dimmer', settings.dimmerName); $element.addClass(settings.dimmerName); } $element .appendTo($dimmable) ; return $element; }, show: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; module.debug('Showing dimmer', $dimmer, settings); if( (!module.is.dimmed() || module.is.animating()) && module.is.enabled() ) { module.animate.show(callback); settings.onShow.call(element); settings.onChange.call(element); } else { module.debug('Dimmer is already shown or disabled'); } }, hide: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if( module.is.dimmed() || module.is.animating() ) { module.debug('Hiding dimmer', $dimmer); module.animate.hide(callback); settings.onHide.call(element); settings.onChange.call(element); } else { module.debug('Dimmer is not visible'); } }, toggle: function() { module.verbose('Toggling dimmer visibility', $dimmer); if( !module.is.dimmed() ) { module.show(); } else { module.hide(); } }, animate: { show: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if(settings.useCSS && $.fn.transition !== undefined && $dimmer.transition('is supported')) { if(settings.opacity !== 'auto') { module.set.opacity(); } $dimmer .transition({ displayType : 'flex', animation : settings.transition + ' in', queue : false, duration : module.get.duration(), useFailSafe : true, onStart : function() { module.set.dimmed(); }, onComplete : function() { module.set.active(); callback(); } }) ; } else { module.verbose('Showing dimmer animation with javascript'); module.set.dimmed(); if(settings.opacity == 'auto') { settings.opacity = 0.8; } $dimmer .stop() .css({ opacity : 0, width : '100%', height : '100%' }) .fadeTo(module.get.duration(), settings.opacity, function() { $dimmer.removeAttr('style'); module.set.active(); callback(); }) ; } }, hide: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if(settings.useCSS && $.fn.transition !== undefined && $dimmer.transition('is supported')) { module.verbose('Hiding dimmer with css'); $dimmer .transition({ displayType : 'flex', animation : settings.transition + ' out', queue : false, duration : module.get.duration(), useFailSafe : true, onStart : function() { module.remove.dimmed(); }, onComplete : function() { module.remove.active(); callback(); } }) ; } else { module.verbose('Hiding dimmer with javascript'); module.remove.dimmed(); $dimmer .stop() .fadeOut(module.get.duration(), function() { module.remove.active(); $dimmer.removeAttr('style'); callback(); }) ; } } }, get: { dimmer: function() { return $dimmer; }, duration: function() { if(typeof settings.duration == 'object') { if( module.is.active() ) { return settings.duration.hide; } else { return settings.duration.show; } } return settings.duration; } }, has: { dimmer: function() { if(settings.dimmerName) { return ($module.find(selector.dimmer).filter('.' + settings.dimmerName).length > 0); } else { return ( $module.find(selector.dimmer).length > 0 ); } } }, is: { active: function() { return $dimmer.hasClass(className.active); }, animating: function() { return ( $dimmer.is(':animated') || $dimmer.hasClass(className.animating) ); }, closable: function() { if(settings.closable == 'auto') { if(settings.on == 'hover') { return false; } return true; } return settings.closable; }, dimmer: function() { return $module.hasClass(className.dimmer); }, dimmable: function() { return $module.hasClass(className.dimmable); }, dimmed: function() { return $dimmable.hasClass(className.dimmed); }, disabled: function() { return $dimmable.hasClass(className.disabled); }, enabled: function() { return !module.is.disabled(); }, page: function () { return $dimmable.is('body'); }, pageDimmer: function() { return $dimmer.hasClass(className.pageDimmer); } }, can: { show: function() { return !$dimmer.hasClass(className.disabled); } }, set: { opacity: function(opacity) { var color = $dimmer.css('background-color'), colorArray = color.split(','), isRGB = (colorArray && colorArray.length == 3), isRGBA = (colorArray && colorArray.length == 4) ; opacity = settings.opacity === 0 ? 0 : settings.opacity || opacity; if(isRGB || isRGBA) { colorArray[3] = opacity + ')'; color = colorArray.join(','); } else { color = 'rgba(0, 0, 0, ' + opacity + ')'; } module.debug('Setting opacity to', opacity); $dimmer.css('background-color', color); }, active: function() { $dimmer.addClass(className.active); }, dimmable: function() { $dimmable.addClass(className.dimmable); }, dimmed: function() { $dimmable.addClass(className.dimmed); }, pageDimmer: function() { $dimmer.addClass(className.pageDimmer); }, disabled: function() { $dimmer.addClass(className.disabled); }, variation: function(variation) { variation = variation || settings.variation; if(variation) { $dimmer.addClass(variation); } } }, remove: { active: function() { $dimmer .removeClass(className.active) ; }, dimmed: function() { $dimmable.removeClass(className.dimmed); }, disabled: function() { $dimmer.removeClass(className.disabled); }, variation: function(variation) { variation = variation || settings.variation; if(variation) { $dimmer.removeClass(variation); } } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { if($.isPlainObject(settings[name])) { $.extend(true, settings[name], value); } else { settings[name] = value; } } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(!settings.silent && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(!settings.silent && settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { if(!settings.silent) { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); } }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; module.preinitialize(); if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.dimmer.settings = { name : 'Dimmer', namespace : 'dimmer', silent : false, debug : false, verbose : false, performance : true, // name to distinguish between multiple dimmers in context dimmerName : false, // whether to add a variation type variation : false, // whether to bind close events closable : 'auto', // whether to use css animations useCSS : true, // css animation to use transition : 'fade', // event to bind to on : false, // overriding opacity value opacity : 'auto', // transition durations duration : { show : 500, hide : 500 }, onChange : function(){}, onShow : function(){}, onHide : function(){}, error : { method : 'The method you called is not defined.' }, className : { active : 'active', animating : 'animating', dimmable : 'dimmable', dimmed : 'dimmed', dimmer : 'dimmer', disabled : 'disabled', hide : 'hide', pageDimmer : 'page', show : 'show' }, selector: { dimmer : '> .ui.dimmer', content : '.ui.dimmer > .content, .ui.dimmer > .content > .center' }, template: { dimmer: function() { return $('<div />').attr('class', 'ui dimmer'); } } }; })( jQuery, window, document );
martindale/Semantic-UI
src/definitions/modules/dimmer.js
JavaScript
mit
21,339
var coffeeTransfer = { name: "coffeeTransfer", desc: "์ฃผ์–ด์ง„ ์›ํ™” ๊ธˆ์•ก์„ ์ปคํ”ผ ์ž” ์ˆ˜๋กœ ํ™˜์‚ฐํ•ด์ฃผ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์ž…๋‹ˆ๋‹ค.", cofffeeName: "UNKNOWN", coffeePrice: 4000, setCoffee: function (_coffeeName, _coffeePrice) { this.cofffeeName = _coffeeName; this.coffeePrice = Number(_coffeePrice); }, getCoffeeName: function () { return this.cofffeeName; }, getCoffeePrice: function () { return this.coffeePrice; }, //๊ธˆ์•ก ์ •๋ณด๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” class์—์„œ ์ •๊ทœ์‹์„ ํ†ตํ•ด ์›ํ™” ์ •๋ณด๋ฅผ ์ถ”์ถœ. cofffeeTransfer: function (_className) { var bfCoffeeTransferElemArr = document.getElementsByClassName(_className); //์ฒ˜๋ฆฌ ๋Œ€์ƒ var krwPrice = []; var thisElem, krwAmt, coffeeAmt; for (var i = 0; bfCoffeeTransferElemArr.length > i; i++) { thisElem = bfCoffeeTransferElemArr[i]; krwAmt = Number(thisElem.innerHTML.replace(/[^0-9.]/g, '')); coffeeAmt = Math.ceil(krwAmt / this.coffeePrice); thisElem.innerHTML = thisElem.innerHTML + ' <div class="coffee-amt"><i class="fa fa-coffee"></i>'+ this.getCoffeeName() +' ์•ฝ' + coffeeAmt + '์ž” ๊ฐ€๊ฒฉ </div>'; krwPrice.push({ elem: thisElem, krwAmt: krwAmt, coffeeAmt: coffeeAmt }); } return krwPrice; }, };
kuil09/codeBetter
coffeeTransfer.js
JavaScript
mit
1,441
import Ember from 'ember'; import CollectionWidget from 'ember-eureka/widget-collection'; import layout from '../templates/components/widget-collection-aggregation'; export default CollectionWidget.extend({ layout: layout, label: Ember.computed.alias('config.label'), aggregator: Ember.computed.alias('config.aggregator'), options: Ember.computed.alias('config.options'), displayType : Ember.computed.alias('config.display.as'), displayAsNumber: Ember.computed('displayType', function() { return this.get('displayType') === 'number'; }), number: null, chartHeight: Ember.computed.alias('config.display.height'), xLabel : Ember.computed('config.display.x', function() { let label = this.get('config.display.x'); if (typeof label === 'string') { return label; } return this.get('config.display.x.as'); }), xTitle : Ember.computed.alias('config.display.x.title'), xSuffix : Ember.computed.alias('config.display.x.suffix'), xSeries: Ember.computed('config.display.x', function() { let series = this.getWithDefault('config.display.x.series', []); if (!series.length) { let xConfig = this.get('config.display.x'); let xConfigAs, xConfigName; if (typeof xConfig === 'string') { xConfigAs = xConfig; } else { xConfigAs = xConfig.as; xConfigName = xConfig.title; } series.push({ as: xConfigAs, name: xConfigName }); } return series; }), yLabel : Ember.computed('config.display.y', function() { let label = this.get('config.display.y'); if (typeof label === 'string') { return label; } return this.get('config.display.y.as'); }), yTitle : Ember.computed.alias('config.display.y.title'), ySuffix : Ember.computed.alias('config.display.y.suffix'), ySeries: Ember.computed('config.display.y', function() { let series = this.getWithDefault('config.display.y.series', []); if (!series.length) { let yConfig = this.get('config.display.y'); let yConfigAs, yConfigName; if (typeof yConfig === 'string') { yConfigAs = yConfig; } else { yConfigAs = yConfig.as; yConfigName = yConfig.title; } series.push({ as: yConfigAs, name: yConfigName }); } return series; }), chartTitle: Ember.computed.alias('config.display.title'), chartSubtitle: Ember.computed.alias('config.display.subtitle'), chartMode: false, chartData: null, chartOptions: Ember.computed( 'displayType', // 'chartCategories.[]', 'chartTitle', 'chartSubtitle', 'xTitle', 'yTitle', 'xSuffix', 'ySuffix', 'color', 'operator', function() { let chartType = this.get('displayType'); // let chartCategories = this.get('chartCategories'); let chartTitle = this.get('chartType') || ''; let chartSubtitle = this.get('chartSubtitle') || ''; let chartHeight = this.get('chartHeight'); let xTitle = this.get('xTitle'); let yTitle = this.get('yTitle'); let xSuffix = this.get('xSuffix'); let ySuffix = this.get('ySuffix'); if (chartType === 'bar') { [xTitle, yTitle] = [yTitle, xTitle]; [xSuffix, ySuffix] = [ySuffix, xSuffix]; } return { chart: { type: chartType, height: chartHeight }, title: { text: chartTitle }, subtitle: { text: chartSubtitle }, xAxis: { categories: [],//chartCategories, title: xTitle, labels: { format: xSuffix && `{value}${xSuffix}` || '{value}' } }, tooltip: { valueSuffix: ySuffix }, legend: { labelFormatter: function() { // if (chartType === 'pie') { // if (operator === 'count') { // return `${this.name} (${this.percentage.toFixed(1)}%)`; // } else { // return `${this.name} (${this.value}${valueSuffix})`; // } // } return this.name; } }, // plotOptions: { // pie: { // allowPointSelect: true, // cursor: 'pointer', // dataLabels: { // enabled: false // }, // showInLegend: true // } // }, yAxis: { title: { text: yTitle, align: 'high' }, gridLineInterpolation: 'polygon', labels: { format: ySuffix && `{value}${ySuffix}` || '{value}' } } }; }), // _chartData: Ember.computed('[email protected]', 'serieName', function() { // var serieName = this.get('serieName'); // var data = this.get('data').map(function(item) { // return { // name: item.label, // y: item.value, // selected: item.selected // }; // }); // return [{ // name: serieName, // data: data // }]; // }), /** update the collection from the `routeModel.query` */ fetch: Ember.on('init', Ember.observer( 'routeModel.query.hasChanged', 'routeModel.meta', 'store', 'aggregator', 'displayConfig', 'singleValueRepresentation', 'considerUnfilled', function() { this.set('isLoading', true); let routeQuery = this.get('routeModel.query')._toObject(); let query = {}; for (let fieldName of Object.keys(routeQuery)) { if (fieldName[0] === '_') { query[fieldName.slice(1)] = routeQuery[fieldName]; } else { query.filter = query.filter || {}; query.filter[fieldName] = routeQuery[fieldName]; } } // if (this.get(`routeModel.meta.${property}Field.isRelation`)) { // property = `${property}.title`; // } let store = this.get('store'); let aggregator = this.get('aggregator'); let options = this.get('options'); let promises = Ember.A(); promises.pushObject(store.aggregate(aggregator, query, options)); // let considerUnfilled = this.get('considerUnfilled'); // if (considerUnfilled) { // let unfilledQuery = {}; // Ember.setProperties(unfilledQuery, query); // unfilledQuery[property] = {'$exists': false}; // promises.pushObject(store.count(unfilledQuery)); // } Ember.RSVP.all(promises).then((data) => { let results = data[0]; if (this.get('displayAsNumber')) { if (results.length) { this.set('number', parseInt(results[0].x, 10)); } else { this.set('number', null); } } else { // if (considerUnfilled) { // results.push({label: '_unfilled', value: data[1], selected: true}); // } // let xLabel = this.get('xLabel'); // let yLabel = this.get('yLabel'); // let series = this.get('ySeries'); let displayType = this.get('displayType'); // if (displayType === 'bar') { // xLabel = this.get('yLabel'); // yLabel = this.get('xLabel'); // series = this.get('xSeries'); // } // let chartCategories = results.mapBy(xLabel).uniq(); let getPointCoordinates = function(item) { if (typeof item.x === 'boolean') { item.x = `${item.x}`; } if (typeof item.y === 'boolean') { item.y = `${item.y}`; } if (displayType === 'bar') { return [item.y, item.x]; } return [item.x, item.y]; }; let chartData = []; if (this.get('aggregator.color')) { let colorValues = results.mapBy('color').uniq(); for (let colorValue of colorValues) { let filteredResults = results.filterBy('color', colorValue); if (typeof colorValue === 'boolean') { colorValue = `${colorValue}`; } chartData.push({ name: colorValue, data: filteredResults.map(getPointCoordinates) }); } } else { chartData = [{ name: ' ', data: results.map(getPointCoordinates) }]; } // if (displayType === 'pie') { // let serie = series[0]; // chartData = [{ // name: serie.title, // data: results.mapBy(serie.as).map((value, index) => { // return { // name: chartCategories[index], // y: value // }; // }) // }]; // } else if (this.get('aggregator.color')) { // chartData = []; // for (let serie of series) { // let colorValues = results.mapBy('color').uniq(); // let _data = {}; // for (let colorValue of colorValues) { // _data[colorValue] = []; // } // for (let item of results) { // for (let colorValue of colorValues) { // let val = null; // if (colorValue === item.color) { // val = item[serie.as]; // } // _data[colorValue].push(val); // } // } // for (let colorValue of Object.keys(_data)) { // chartData.push({ // name: colorValue, // data: _data[colorValue] // }); // } // } // } else { // chartData = series.map((serie) => { // return { // name: serie.name, // data: results.mapBy(serie.as) // }; // }); // } this.setProperties({ chartData: chartData // chartCategories: chartCategories }); } this.set('isLoading', false); }); })) });
namlook/eureka-widget-collection-aggregation
addon/components/widget-collection-aggregation.js
JavaScript
mit
11,927
require('./explosion'); const colors = [ '#e00b0b', '#477bff', '#4cff00', '#ff8300', '#ffffff', '#fff951' ]; function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } function getColor(data) { const color = colors[getRandomInt(0, colors.length)]; return color; } module.exports = function (rootOSCServer) { AFRAME.registerComponent('channel', { schema: { id: { type: 'int', default: 1 } }, init() { const id = this.data.id; const el = this.el; const sphere = el.querySelector('.sphere'); const explosion = el.components.explosion; rootOSCServer.on(`raw-data:channel-${id}`, (data) => { explosion.create({ color: getColor(data), matrixWorld: sphere.object3D.matrixWorld }); }); } }); return function createChannel(parent, id) { parent.insertAdjacentHTML('beforeend', ` <a-entity id="channel-${id}" explosion channel="id: ${id};"> <a-sphere class="sphere" wireframe radius="0.5" position="${id} 0 -20" color="#bc2f2f" metalness="0.5"> <a-animation attribute="rotation" to="-360 -360 0" dur="5000" easing="linear" repeat="indefinite"> </a-animation> </a-sphere> <a-animation attribute="rotation" to="0 -360 0" dur="10000" easing="linear" repeat="indefinite"> </a-animation> </a-entity> `); }; };
tinchoz49/vr-synthesis-osc
client/src/vr/channel.js
JavaScript
mit
1,628